About Constants in Django

Keep model-related constants at the model level instead of the module level. You can save some extra imports in the views, forms or middlewares, and will have a clear namespace.

articles/models.py:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Article(models.Model):
    DRAFT = "d"
    PUBLISHED = "p"
    PUBLISHING_STATUS_CHOICES = (
        (DRAFT, _("In preparation")),
        (PUBLISHED, _("Published")),
    )
    publishing_status = models.CharField(
        _("Publishing status"),
        default=DRAFT,
        choices=PUBLISHING_STATUS_CHOICES,
        max_length=1,
    )
1
2
3
4
5
6
<h1>
    {{ article.title }}
    {% if article.publishing_status == article.DRAFT %}
        (draft)
    {% endif %}
</h1>

Tips and Tricks Programming Architecture Django 4.2 Django 3.2 Django 2.2 Django 1.11 Django 1.8