I was trying to create a django form and one of my field contain a ModelChoiceField
class FooForm(forms.Form):
person = forms.ModelChoiceField(queryset=Person.objects.filter(is_active=True).order_by('id'), required=False)
age = forms.IntegerField(min_value=18, max_value=99, required=False)
When I try the code above what it return as an html ouput is
<option value="1">Person object</option>
on my Person Model I have the fields "id, fname, lname, is_active" . Is it possible to specify that my dropdown option will use "id" as the value and "lname" as the label? The expected html should be
<option value="1">My Last Name</option>
Thanks in advance!
You can just add a call to label_from_instance in the init of Form ie
by adding something like
class TestForm(ModelForm):
def __init__(self, *args, **kwargs):
super(TestForm, self).__init__(*args, **kwargs)
self.fields['field_name'].label_from_instance = self.label_from_instance
@staticmethod
def label_from_instance(obj):
return "My Field name %s" % obj.name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With