About Enumeration-type Choices

Use models.TextChoices to create enumeration-type choices for your model fields:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from django.db import models
from django.utils.translation import gettext_lazy as _

class Post(models.Model):
    class PublishingStatus(models.TextChoices):
        DRAFT = "d", _("Draft")
        PUBLISHED = "p", _("Published")

    publishing_status = models.CharField(
        _("Publishing status"),
        max_length=1,
        choices=PublishingStatus.choices,
        default=PublishingStatus.DRAFT,
    )

Then you can check the publishing status in the template as follows:

1
2
3
4
{% load i18n %}
{% if post.publishing_status == post.PublishingStatus.DRAFT %}
    <button type="button" id="publish">{% translate "Publish" %}</button>
{% endif %}

Tips and Tricks Programming Django 4.2 Django 3.2