How to choose the value and label from Django ModelChoiceField queryset

0 votes

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!

Jul 29, 2020 in Python by kartik
• 37,510 points
6,118 views

1 answer to this question.

0 votes

Hello @kartik,

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)

Hope it helps!!
Thank you!!

answered Jul 29, 2020 by Niroj
• 82,880 points

Related Questions In Python

0 votes
3 answers

How to get the return value from a thread using python?

FWIW, the multiprocessing module has a nice interface for ...READ MORE

answered Dec 15, 2020 in Python by Roshni
• 10,520 points
105,133 views
–1 vote
2 answers
0 votes
0 answers
0 votes
1 answer

How to execute a Python script from the Django shell?

Hello @kartik, The << part is wrong, use < instead: $ ./manage.py shell ...READ MORE

answered Jun 22, 2020 in Python by Niroj
• 82,880 points
9,779 views
0 votes
1 answer

How to temporarily disable a foreign key constraint in MySQL?

Hello @kartik, To turn off foreign key constraint ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,880 points
2,041 views
0 votes
1 answer

How do I use Django templates without the rest of Django?

Hello @kartik, Let's say you have this important ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,880 points
1,190 views
0 votes
1 answer

How to get the SQL from a Django QuerySet?

Hello @kartik, Try this in your queryset: print my_queryset.query For ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,880 points
7,617 views
0 votes
1 answer

How do I add a link from the Django admin page of one object to the admin page of a related object?

Hello @kartik, Set show_change_link to True (False by default) in your inline ...READ MORE

answered Jun 12, 2020 in Python by Niroj
• 82,880 points
9,884 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP