1

My Django model class is as follows:

class MyClass(models.Model):
    CHOICE1 = "CHOICE1"
    CHOICE2 = "CHOICE2"

    FIELD_CHOICES = (
        (CHOICE1, CHOICE1),
        (CHOICE2, CHOICE2),
    )
    my_field = models.CharField(
        max_length=254,
        null=False,
        blank=False,
        choices=FIELD_CHOICES,
        default=CHOICE1,
    )

I pass my_instance which is an instance of MyClass into the template. From within that template how can I do an if-else check on the possible values of my_field?

I do the following, but it doesn't work:

{% if my_instance.my_field == my_instance.__class__.CHOICE1 %}
    <p>BLAH BLAH1</p>
{% elif my_instance.my_field == my_instance.__class__.CHOICE2 %}
    <p>BLAH BLAH2</p>
{% endif %}

EDIT: I can pass the class MyClass into the template context and then use MyClass.CHOICEX. That works. But it seems wasteful to have to pass in the class itself in addition to the instance. Can't I get the Class from the instance and then use CHOICEX?

Saqib Ali
  • 11,931
  • 41
  • 133
  • 272

1 Answers1

3

You can access class variables from instance:

{% if my_instance.my_field == my_instance.CHOICE1 %}
    <p>BLAH BLAH1</p>
{% elif my_instance.my_field == my_instance.CHOICE2 %}
    <p>BLAH BLAH2</p>
{% endif %}

Check this answer for more information on class variables.

Community
  • 1
  • 1
Ernest
  • 2,799
  • 12
  • 28