Search code examples
pythonhtmldjangoformsmodel

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!


Solution

  • In your Person model add:

    def __unicode__(self):
        return u'{0}'.format(self.lname)
    

    If you are using Python 3, then define __str__ instead of __unicode__.

    def __str__(self):
        return u'{0}'.format(self.lname)