Custom label on ModelChoiceField form field

时间:2018-01-23 19:20:17

标签: django forms

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?

1 个答案:

答案 0 :(得分:6)

请参阅https://docs.djangoproject.com/en/2.0/ref/forms/fields/#modelchoicefield的最后一部分

  

将调用模型的 str ()方法以生成对象的字符串表示形式,以便在字段的选择中使用。要提供自定义表示,请继承ModelChoiceField并覆盖label_from_instance。

所以,在你的情况下,你可以这样做:

from django.forms import ModelChoiceField

class NamesChoiceField(ModelChoiceField):

    def label_from_instance(self, obj):
        return '{firstname} {lastname}'.format(firstname=obj.first_name, lastname=obj.last_name)

然后,

class InvoiceModelForm(forms.ModelForm):

   u = NamesChoiceField(queryset=User.objects.all())