Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django ModelChoiceField: how to iter through the instances in the template?

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

like image 352
Michael Avatar asked Feb 26 '14 02:02

Michael


1 Answers

{% 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 %}
like image 103
orokusaki Avatar answered Oct 22 '22 04:10

orokusaki