Django - change select items display

牧云@^-^@ 提交于 2019-12-17 21:23:07

问题


I use ModelForm. One of the fields is:

repertoire = models.ForeignKey(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?


回答1:


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())


来源:https://stackoverflow.com/questions/6754776/django-change-select-items-display

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!