Rendering a drop down box in Django using ModelChoiceField

Usually, if you were to use something like,

``

class testform(forms.Form):
n = forms.ModelChoiceField(queryset=Models.objects.filter(id=32773), empty_label="All")

you’ll end up with a drop down box populated with “M objects” rather than a field from the model.

Instead, this works better,

<br></br>class vModelChoiceField(forms.ModelChoiceField):<br></br> def label_from_instance(self, obj):<br></br> return "%s" % obj.name

class testform(forms.Form):
n = vModelChoiceField(queryset=Models.objects.filter(id=32773), empty_label="All")

t = testform()
print t

And you’re done!

--

If you have any questions or thoughts, don't hesitate to reach out. You can find me as @viksit on Twitter.