Django-更改选择项显示 [英] Django - change select items display
本文介绍了Django-更改选择项显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 ModelForm
。字段之一是:
repertoire = models.ForeignKey(Repertoire)
我需要更改其显示类型。而不是使用 __ str __
(或Python 2中的 __ unicode __
)在显示中,我想显示曲目的名称和日期。
I need to change its display type. Instead of using __str__
(or __unicode__
in Python 2) in display I want to show name and date of repertoire.
如何使用 ModelForm
完成此操作?
推荐答案
子类 ModelChoiceField
并覆盖 label_from_instance
以返回曲目名称和日期。然后在 ModelForm
中使用新字段。
Subclass ModelChoiceField
and override label_from_instance
to return the repertoire name and date. Then use the new field in your 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())
这篇关于Django-更改选择项显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文