django ModelChoiceField: how to iter through the instances in the template?
django, django-forms, django-templates
Solution
{% 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 %}
Problem
I am trying to get access to the instances of a ModelChoiceField to render them the way I want in a template by displaying several fields of the instances. ``` class MyForm(forms.Form): mychoices = forms.ModelChoiceField( queryset=ObjectA.objects.all(), widget=forms.RadioSelect(), empty_label=None ) ``` This does not work: ``` {% for choice in form.mychoices %} {{ choice.pk}} {% endfor %} ``` I also tried to use the queryset but it does not render anything ``` {% for choice in form.mychoices.queryset %} {{ choice.pk}} {% endfor %} ``` Any idea? Thanks