我正在使用 ModelForms 为网站制作表单,但我想更好地控制“选择”框中显示的文本。
示例模型可能如下所示
class Test(models.Model)
ID = IntegerField()
Label = CharacterField()
recipient = ForeignKey(Person)
product = ForeignKey(Product)
所以,我的问题是,当我制作这个模型的 modelForm 时,外键字段被制成选择字段,在基础值中具有对象的主键,显示的文本是来自对象 __unicode__()
方法。在这种情况下,只显示产品 ID(这是一个序列号,对用户没有意义)。我希望能够制作一个自定义标签,例如“[序列号]、[产品名称]”。
我似乎无法在官方 Django 文档中找到任何指示,所以我想知道是否有人可以提供帮助? :)
最佳答案
查看 Django docs regarding the ModelChoiceField .引用:
The
__unicode__
method of the model will be called to generate string representations of the objects for use in the field's choices; to provide customized representations, subclass ModelChoiceField and override label_from_instance. This method will receive a model object, and should return a string suitable for representing it. For example:class MyModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return "My Object #%i" % obj.id
关于python - Django 选择表单字段的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11981526/