![](/img/trans.png)
[英]display a list of items in a select box in my html template in django 2.2
[英]Django - change select items display
我使用ModelForm
。 其中一个字段是:
repertoire = models.ForeignKey(Repertoire)
我需要改变它的显示类型。 而不是在显示中使用__str__
(或 Python 2 中的__unicode__
),我想显示曲目的名称和日期。
如何使用ModelForm
做到这一点?
子类ModelChoiceField
并覆盖label_from_instance
以返回曲目名称和日期。 然后使用ModelForm
中的新字段。
from django import forms
class RepertoireModelChoiceField(forms.ModelChoiceField):
def label_from_instance(self, obj):
return "%s - %s" % (obj.name, obj.date)
class MyModelForm(forms.ModelForm):
repertoire = RepertoireModelChoiceField(queryset=Repertoire.objects.all())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.