[Python] How to choose the value and label from Django ModelChoiceField queryset

Discussão em 'Python' iniciado por Stack, Novembro 27, 2025.

  1. Stack

    Stack Membro Participativo

    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!

    Continue reading...

Compartilhe esta Página