Home » Python » Django: Display Choice Value

Django: Display Choice Value

Posted by: admin November 1, 2017 Leave a comment

Questions:

Model:

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)?

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 }}

Questions:
Answers:

you can use BooleanField instead of CharField,
and in model:

BOOL_CHOICES = ((True, 'Male'), (False, 'Female'))
gender = models.BooleanField(choices=BOOL_CHOICES)

Questions:
Answers:

I’ve recently moved beyond Django, so I’m more familiar with Jinja2 templating, but here we go:

Note that it is stored in the database as ‘M’ and ‘F’

Psuedo:

# Iterate through list of people  
  # Check if male  
    # output span w/ gender  

Actual:

{% for person in latest_person_list2 %}  
{% if person.gender == 'M' %}  
  <span>Male</span>  
{% else %}  
  <span>Female</span>  
{% endif %}  
{% endfor %}  

For something more complex with more choices it might be worth writing some logic to search through the CATEGORY_CHOICES tuple of tuples. As of now, with two choices for gender, I don’t see that being the case.

also see: Django Template Tags