Django - change select items display
I use ModelForm
. One of the fields is:
repertoire = models.ForeignKe开发者_运维知识库y(Repertoire)
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.
How can I do this with 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())
精彩评论