我有一个选择表,它允许用户选择分配有特定范围的员工。
class ReservationBookingForm(forms.Form):
employee = forms.ModelChoiceField(
queryset = Employee.objects.none(),
#widget = forms.RadioSelect,
empty_label = None,
required = True,
label = '',
widget=forms.Select(attrs={'class':'input-lg text-center'}),
)
def __init__(self, rangeId, *args, **kwargs):
super(ReservationBookingForm, self).__init__(*args, **kwargs)
self.fields['employee'].queryset = Employee.objects.filter(Q(range = rangeId ) | Q(range = 'B'))
我想做的是将显示选择选项显示为Employee.first_name和Employee.last_name。我真的不想通过unicode方法做到这一点。
有没有办法做到这一点?
我得到的(没有unicode)是:
option1 - Employee Object
option2 - Employee Object
我想要的是:
option1 - John Doe
option2 - Jack Doe
但我想实现这一目标而不要覆盖unicode方法。
在ModelChoiceField部分的末尾:
将调用模型的
__str__
(__unicode__
在Python 2上)方法来生成对象的字符串表示形式,以供在字段的选择中使用;提供自定义的表示形式,子类ModelChoiceField
和重写label_from_instance
。此方法将接收一个模型对象,并应返回适合于表示它的字符串。
在您的情况下:
from django.forms import ModelChoiceField
class MyModelChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
return "{} {}".format(obj.first_name, obj.last_name)
class ReservationBookingForm(forms.Form):
employee = MyModelChoiceField(...)
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句