Django templates: verbose version of a choice Django templates: verbose version of a choice django django

Django templates: verbose version of a choice


In Django templates you can use the "get_FOO_display()" method, that will return the readable alias for the field, where 'FOO' is the name of the field.

Note: in case the standard FormPreview templates are not using it, then you can always provide your own templates for that form, which will contain something like {{ form.get_meal_display }}.


The best solution for your problem is to use helper functions.If the choices are stored in the variable CHOICES and the model field storing the selected choice is 'choices' then you can directly use

 {{ x.get_choices_display }}

in your template. Here, x is the model instance.Hope it helps.


My apologies if this answer is redundant with any listed above, but it appears this one hasn't been offered yet, and it seems fairly clean. Here's how I've solved this:

from django.db import modelsclass Scoop(models.Model):    FLAVOR_CHOICES = [        ('c', 'Chocolate'),        ('v', 'Vanilla'),    ]    flavor = models.CharField(choices=FLAVOR_CHOICES)    def flavor_verbose(self):        return dict(Scoop.FLAVOR_CHOCIES)[self.flavor]

My view passes a Scoop to the template (note: not Scoop.values()), and the template contains:

{{ scoop.flavor_verbose }}