我使用Django 1.8.14。我有两个模型:
class Event(models.Model):
title = models.CharField(max_length=255,)
date = models.DateTimeField()
...
def __unicode__(self):
return self.title
class Card(models.Model):
user = models.ForeignKey(MyUser, related_name="user")
event = models.ForeignKey(Event,)
...
卡片型号:
class CardForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(CardForm, self).__init__(*args, **kwargs)
self.fields['event'].empty_label = None
class Meta:
model = Card
fields = ('event', )
widgets = {'event': forms.RadioSelect, }
我渲染这样的形式:
<form method="POST">
{% csrf_token %}
{% for choice in cardform.event %}
{{ choice.tag }}
{{ choice.choice_label }}
{% endfor %}
</form >
在每个单选按钮的标签中,我需要显示两个字段值&#34; title&#34;和&#34;日期&#34;事件模型是Card的ForeignKey。现在标签仅包含&#34; title&#34;值。最好的方法是什么? 我尝试过 {{cardform.instance.event.date}} ,但它无法正常工作。
答案 0 :(得分:0)
我找到了解决方案。
class CardForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(CardForm, self).__init__(*args, **kwargs)
self.fields['event'].label_from_instance = lambda obj: "%s %s" % (obj.title, obj.date)