Shankze
Shankze

Reputation: 4099

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

Upvotes: 372

Views: 280414

Answers (4)

baldy
baldy

Reputation: 5541

I do this by defining constants the following way:

class Person(models.Model):
    MALE = 'M'
    FEMALE = 'F'
    CATEGORY_CHOICES = (
        (MALE, 'Male'),
        (FEMALE, 'Female'),
    )

    name = models.CharField(max_length=200)
    gender = models.CharField(max_length=200, choices=CATEGORY_CHOICES)
    to_be_listed = models.BooleanField(default=True)
    description = models.CharField(max_length=20000, blank=True)

The M and F values will be stored in the database, while the Male and Female values will display everywhere.

Upvotes: 0

Daniel O'Brien
Daniel O'Brien

Reputation: 365

Others have pointed out that a get_FOO_display method is what you need. I'm using this:

def get_type(self):
    return [i[1] for i in Item._meta.get_field('type').choices if i[0] == self.type][0]

which iterates over all of the choices that a particular item has until it finds the one that matches the items type

Upvotes: -1

jMyles
jMyles

Reputation: 12172

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

Upvotes: 715

Muhammad Faizan Fareed
Muhammad Faizan Fareed

Reputation: 3758

For every field that has choices set, the object will have a get_FOO_display() method, where FOO is the name of the field. This method returns the “human-readable” value of the field.

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

Upvotes: 59

Related Questions