[Solved]-Django ModelChoiceField: how to iter through the instances in the template?



{% for choice in form.mychoices.field.queryset %}
    {{ choice.pk }}
{% endfor %}

Notice the extra .field. It’s a bit strange the first time you come across it, but it gives you what you want. You can also access the choices attribute of that object, instead of accessing queryset directly, but you’ll need to access the first element of the choice to get the PK of the instance, like this:

{% for choice in form.mychoices.field.choices %}
    {{ choice.0 }}
{% endfor %}

Leave a comment