[Answered ]-Django loop over modelchoicefield queryset

2👍

You shouldn’t be trying to loop over field choices in the template. Instead, you should customise the form field itself to give you the output you want.

In the case of a ModelChoiceField, as the documentation explains, the way to customise the output is to subclass the field and define label_from_instance:

class AnExampleModelChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        return '{}: {}'.format(obj.area, obj.description)

class myForm(forms.ModelForm):
    an_example = forms.AnExampleModelChoiceField(widget=forms.RadioSelect,
        queryset=AnExample.objects.all(),
        required=True)

Now you can just do {{ form_from_view.an_example }} in your template to output the whole thing.

Leave a comment