Django: Display Choice Value
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:
Leveraging get_FOO_display()
in templates
When using Django templates, don't forget to leave out the parentheses when calling the method:
If the expected value isn't popping up, ensure your to_be_listed
filter is correctly applied in your view:
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
:
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.
Was this article helpful?