简体   繁体   中英

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 (eg 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)

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 %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM