Answer a question

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!

Answers

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)
Logo

学AI,认准AI Studio!GPU算力,限时免费领,邀请好友解锁更多惊喜福利 >>>

更多推荐