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,


class vModelChoiceField(forms.ModelChoiceField):
def label_from_instance(self, obj):
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!