maca
maca

Reputation: 540

How to Loop through enum in Django?

I have a model in Django

class Order(models.Model):
   class Gender(models.IntegerChoices):
      Male = (1,), _("Male")
      Female = (2,), _("Female")

I want to send male and female in context

context["genders"] = Order.Gender

I use that in template like this

{% for gender in genders %}
   <p>{{ gender }}</p>
{% endfor %}

I want to show male and female in front

Upvotes: 1

Views: 593

Answers (1)

Marco
Marco

Reputation: 2854

Pass choices to the template, unpack and display them:

views.py

context["genders"] = Order.Gender.choices

template.html

{% for key, gender in genders %}
    <p>{{ gender }}</p>
{% endfor %}

Upvotes: 1

Related Questions