djangodjango-modelsdjango-templatesmodelchoicefield

I have constants defined in a Django model class. How can I access the constants in a template?


I have a model class with a choice field and its possible values defined as constants, as recommended in https://docs.djangoproject.com/en/3.0/ref/models/fields/#choices

class Student(models.Model):
    FRESHMAN = 'FR'
    SOPHOMORE = 'SO'
    JUNIOR = 'JR'
    YEAR_IN_SCHOOL_CHOICES = [
        (FRESHMAN, 'Freshman'),
        (SOPHOMORE, 'Sophomore'),
        (JUNIOR, 'Junior'),
    ]
    year_in_school = models.CharField(
        max_length=2,
        choices=YEAR_IN_SCHOOL_CHOICES,
        default=FRESHMAN,
    )

In regular Python code (e.g. in a view), I can easily use the constants like so:

if my_student.year_in_school == Student.FRESHMAN:
    # do something

My question is: can I do something like this in a template as well? Something like

{% if student.year_in_school == Student.FRESHMAN %}
    Welcome
{% endif %}

... this works if I hard-code the value 'FR' in the template, but that kind of defies the purpose of constants...

(I am using Python 3.7 and Django 3.0)


Solution

  • There is no way templates will get those values other than explicitly passing them to your template, if you go this path you have two options: pass Student to your template render context, or use context processors to auto add it to your templates context

    The better approch would be adding a method to that class, so you don't need Student constants in your template, ex:

    class Student(models.Model):
        ...
        @property
        def is_freshman(self):
            return self.year_in_school == self.FRESHMAN
    

    and use it directly in your template:

    {% if student.is_freshman %}
        Welcome
    {% endif %}