Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom label on ModelChoiceField form field

Tags:

forms

django

I am using forms with the following:

class InvoiceModelForm ( forms.ModelForm ):

    u = forms.ModelChoiceField ( queryset = User.objects.all () )

But in the form field it is displaying the username. I would like to change that to use the first and last names.

I do not want to change the

def __str__(self):
    return self.username

How can I change what values that are displayed in the form field?

like image 543
diogenes Avatar asked Jan 23 '18 19:01

diogenes


1 Answers

See the last part of https://docs.djangoproject.com/en/stable/ref/forms/fields/#modelchoicefield

The str() method of the model will be called to generate string representations of the objects for use in the field’s choices. To provide customized representations, subclass ModelChoiceField and override label_from_instance.

So, in your case you could do:

from django.forms import ModelChoiceField

class NameChoiceField(ModelChoiceField):

    def label_from_instance(self, obj):
        return f'{obj.first_name} {obj.last_name}'

and then,

class InvoiceModelForm(forms.ModelForm):

   u = NameChoiceField(queryset=User.objects.all())
like image 175
trinchet Avatar answered Nov 02 '22 22:11

trinchet