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,520 points
2,634 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,760 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,480 points
63,860 views
0 votes
2 answers
0 votes
1 answer

How do I clone a Django model instance object and save it to the database?

Hello @kartik, Just change the primary key of ...READ MORE

answered Jun 22, 2020 in Python by Niroj
• 82,760 points
1,269 views
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,760 points
5,025 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,760 points
834 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,760 points
349 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,760 points
585 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,760 points
3,124 views