Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to choose the value and label from Django ModelChoiceField queryset

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!

like image 985
helloworld2013 Avatar asked Nov 15 '13 23:11

helloworld2013


Video Answer


1 Answers

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
like image 199
Thomas Turner Avatar answered Oct 13 '22 00:10

Thomas Turner