Django ModelForm-表单显示值 [英] Django ModelForm - form display values
问题描述
我有一个模型:
class SchedulerProfile(models.Model):
user = models.ForeignKey(User, unique=True)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
def __unicode__(self):
return u'%s' % (self.user)
我也有一个模型与Scheduler之间的M2M关系:
I also have a model that has a M2M relationship with the Scheduler:
class OfficialProfile(models.Model):
user = models.ForeignKey(User, unique=True)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
schedulers = models.ManyToManyField(SchedulerProfile, verbose_name="Your schedulers", related_name="off_schedulers")
当我从OfficialProfile创建一个ModelForm时,该表单将调度程序的内容呈现为multiselect作为用户名。我想让它在字段中显示 user.first_name user.last_name
而不是用户。我知道我可以更改unicode返回值来完成此操作,但出于某些原因,我不愿意这样做。在ModelForm的 __ init __
中,您应该可以执行以下操作:
When I create a ModelForm from the OfficialProfile, the form renders the contents of the scheduler multiselect as the username. I'd like to get it to display user.first_name user.last_name
in the field instead of the user. I know I can change the unicode return value to accomplish this, but I'd rather not do that for reasons. In the __init__
of the ModelForm, you should be able to do something like:
self.fields['schedulers'].queryset = SchedulerProfile.objects.values('user__first_name', 'user__last_name')
但这不会产生预期的结果。这似乎是一个非常基本的问题,但是搜索答案并没有太多揭示。
But that doesn't produce the desired results. This seems like a really basic question, but searching for the answer hasn't revealed much.
推荐答案
子类 ModelMultipleChoiceField
并覆盖 label_from_instance
。
from django.forms import ModelMultipleChoiceField
class SchedulerProfileChoiceField(ModelMultipleChoiceField):
def label_from_instance(self, obj):
return "%s %s" % (obj.first_name, obj.last_name)
然后在模型表单中使用您的多项选择字段。
Then use your multiple choice field in the model form.
class OfficialProfileForm(forms.ModelForm):
schedulers = SchedulerProfileChoiceField(queryset=SchedulerProfile.objects.all())
这篇关于Django ModelForm-表单显示值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!