Explain Codes LogoExplain Codes Logo

Django: Display Choice Value

python
django-templates
best-practices
model-choices
Anton ShumikhinbyAnton Shumikhin·Feb 5, 2025
TLDR

To retrieve Django's field display value, use get_FOO_display(). Let's assume you have a gender field in Person model. Here's how you'd get it:

display_value = Person.objects.get(id=1).get_gender_display() print(display_value) # "<insert gender here>"

Leveraging get_FOO_display() in templates

When using Django templates, don't forget to leave out the parentheses when calling the method:

{{ person.get_gender_display }}

If the expected value isn't popping up, ensure your to_be_listed filter is correctly applied in your view:

persons = Person.objects.filter(to_be_listed=True)

And Voilà! persons now holds the filtered object list.

Defining and using choices

Define your choices as tuples within your model. Here's how you'd define gender choices for a Person:

class Person(models.Model): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ('O', 'Other'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) to_be_listed = models.BooleanField(default=False) # With Django’s `get_FOO_display()`, no need for custom methods # They said it couldn't be done... # They said it was impossible... # But Django did it! 🎉

In your templates, simply call get_gender_display() without parentheses to get the human-readable value. If needed elsewhere, convert your choices into a dictionary using dict(YOUR_CHOICES).

Wisdom for the ages (Best Practices)

Keeping your code DRY

A rule of the thumb: Define choices once, use everywhere. Prevents inconsistencies and promotes clean code.

No need to reinvent the wheel

Use Django's built-in get_FOO_display() to get human-readable names. Avoid creating custom methods for existing features. It's like building a ladder to reach the cookies on the top shelf when there's a perfectly good cookie jar on the counter.

Filtering and Displaying

It's always prudent to filter your objects with to_be_listed=True before invoking get_FOO_display(). This way, unwanted objects never see the light of day.

Handling tricky scenarios

When choices are dynamic

In some cases, choices could be populated dynamically or altered post-migration. Override the save method or use signals to make sure Django plays nice.

Multilingual dilemma

For multilingual support, use functions such as ugettext_lazy or gettext_lazy. These translate display values based on the user's language preference.

Refactoring model choices

If choices are used across different models, you guessed it, D.R.Y.! Place the CHOICES definition in a constants.py module.