Problem
models.py:
class Person(models.Model):
name = models.CharField(max_length=200)
CATEGORY_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
gender = models.CharField(max_length=200, choices=CATEGORY_CHOICES)
to_be_listed = models.BooleanField(default=True)
description = models.CharField(max_length=20000, blank=True)
views.py:
def index(request):
latest_person_list2 = Person.objects.filter(to_be_listed=True)
return object_list(request, template_name='polls/schol.html',
queryset=latest_person_list, paginate_by=5)
When I call person.gender on the template, I receive ‘M’ or ‘F’ instead of ‘Male’ or ‘Female.’
How do I display the value (‘Male’ or ‘Female’) rather than the code (‘M’/’F’) instead of the code (‘M’/’F’)?
Asked by Shankze
Solution #1
It appears like you were on the right track – get FOO display() is exactly what you’re looking for:
You don’t use () in the name of a method in templates. Perform the following actions:
{{ person.get_gender_display }}
Answered by jMyles
Solution #2
In Views
person = Person.objects.filter(to_be_listed=True)
context['gender'] = person.get_gender_display()
In Template
{{ person.get_gender_display }}
Documentation of get_FOO_display()
Answered by Muhammad Faizan Fareed
Solution #3
Others have suggested that you use the get FOO display method. This is what I’m using:
def get_type(self):
return [i[1] for i in Item._meta.get_field('type').choices if i[0] == self.type][0]
It iterates through all of the options available for a given item until it finds one that matches the item’s type.
Answered by Daniel O’Brien
Post is based on https://stackoverflow.com/questions/4320679/django-display-choice-value