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?
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With