Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Display Choice Value

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) 

On the template, when I call person.gender, I get 'M' or 'F' instead of 'Male' or 'Female'.

How to display the value ('Male' or 'Female') instead of the code ('M'/'F')?

like image 967
Shankze Avatar asked Dec 01 '10 02:12

Shankze


People also ask

How to display choice field Django?

To display choice value with Python Django, we call the get_FOO_display() method in our template. to create the Person model with the gender field. to return the results of the get_gender_display method where person is a Person instance.

How do I add a choice to a model in Django?

Django Field Choices. According to documentation Field Choices are a sequence consisting itself of iterables of exactly two items (e.g. [(A, B), (A, B) …]) to use as choices for some field. For example, consider a field semester which can have options as { 1, 2, 3, 4, 5, 6 } only.


1 Answers

It looks like you were on the right track - get_FOO_display() is most certainly what you want:

In templates, you don't include () in the name of a method. Do the following:

{{ person.get_gender_display }} 
like image 169
jMyles Avatar answered Oct 12 '22 23:10

jMyles