This site runs best with JavaScript enabled.

Django Tip: get_FIELD_display()


Magic template functions in Django

I'm posting this because it seems rather simple, but it took me a while to find - even with some tips from some helpful people in the #django IRC channel.

Let's say you have a ChoiceField set up like the documents describe:

1class Foo(models.Model):
2 GENDER_CHOICES = (
3 ('M', 'Male'),
4 ('F', 'Female'),
5 )
6 gender = models.CharField(max_length=1, choices=GENDER_CHOICES)

Now, you want to display the gender field in a template. If you use the {{ person.gender }} variable, you would get "M" or "F" to display on your page. But what if you want "Male" or "Female"? Then you would use {{ person.get_gender_display }}.

Nifty.

Discuss on TwitterEdit post on GitHub

Share article
Dustin Davis

Dustin Davis is a software engineer, people manager, hacker, and entreprenuer. He loves to develop systems and automation. He lives with his wife and five kids in Utah.

Join the Newsletter



Dustin Davis