Django Tip: get_FIELD_display()
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:
Â
class Foo(models.Model): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) 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.
Related posts:
- Django: ProgrammingError: Can’t Adapt I find I get an error like this far too...
- Django: Login Form on Every Page Up to the point, when it has come to Django...
Related posts brought to you by Yet Another Related Posts Plugin.
October 3, 2008
Posted in: Yada




5 Responses
I’m just starting out in django, it’s funny how a lot of it (like these smart functions) is so similar to Ruby on Rails.
WOW. This is a small code. I thought it would be a lot longer.
I was also noticing that it reminds me of ROR… Good stuff.
Nice compact code. The best part is, the smaller the code, the less space that is used and the faster the execution. Thanks for posting this.
What about this issue?
{% for field in fields %}
{% if field.value %}
{{ field.verbose_name|title }}:
{% ifequal field.name “occuption” %}
## supposed to be field.get.value.display, but it doesnt work
{% endifequal %}
{% endif %}
{% endfor %}
Comments are closed for this entry.