0

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)

spst
  • 50
  • 5

1 Answers1

2

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 %}
Jeff Bowen
  • 5,904
  • 1
  • 28
  • 41
ahmed
  • 5,430
  • 1
  • 20
  • 36