Django - 更改选择项显示 [英] Django - change select items display

查看:30
本文介绍了Django - 更改选择项显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 ModelForm.其中一个字段是:

I use ModelForm. One of the fields is:

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 执行此操作?

How can I do this with ModelForm?

推荐答案

Subclass 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆