Categories
Python Answers

How to Display Choice Value with Python Django?

Spread the love

Sometimes, we want to display choice value with Python Django.

In this article, we’ll look at how to display choice value with Python Django.

How to Display Choice Value with Python Django?

To display choice value with Python Django, we call the get_FOO_display() method in our template.

For instance, we write

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)

to create the Person model with the gender field.

Then in our template, we add

{{ person.get_gender_display }}

to return the results of the get_gender_display method where person is a Person instance.

Conclusion

To display choice value with Python Django, we call the get_FOO_display() method in our template.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *