djangodjango-modelsdjango-templates

How to print the string value of a choices field


I have an integer field that provides 3 choices for a blog post:

class Post(models.Model):
    STATUS_DRAFT = 0
    STATUS_PUBLISHED = 1
    STATUS_DELETED = 2
    STATUS_CHOICES = (
        (STATUS_DRAFT, 'draft'),
        (STATUS_PUBLISHED, 'published'),
        (STATUS_DELETED, 'deleted'),
    )

    status = IntegerField(choices=STATUS_CHOICES, default=STATUS_DRAFT)

When I render this in a template with {{ blog.status }} it prints the integer value (0, 1, 2). How can I call it to print the string value (draft, published, deleted)?


Solution

  • Yes, you can use get_fieldname_display [Django-doc]:

    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 this case, you thus can implement it with:

    {{ blog.get_status_display }}