[Solved]-Custom label on ModelChoiceField form field


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

Leave a comment