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:

  1. Django: ProgrammingError: Can’t Adapt I find I get an error like this far too...
  2. 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

  1. Mike Riley from - October 5, 2008

    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.

  2. Kevin from Great Wall of China - October 15, 2008

    WOW. This is a small code. I thought it would be a lot longer.

  3. Aaron from Birth of Mothra - October 23, 2008

    I was also noticing that it reminds me of ROR… Good stuff.

  4. Sarah Volker - February 13, 2009

    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.

  5. Özgür - March 29, 2009

    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.