python - Django 选择表单字段的标签

标签 python django forms select label

我正在使用 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/

相关文章:

python - python中的文件操作能去一行吗?

python - django-我如何为查询创建排序以将一个特定元素放在第一位,然后按某个字段保留?

python - 我想使用 django 模型表单生成 4 级下拉表单

javascript - 如何使用javascript防止输入字段中出现空格和句号

javascript - 根据之前的选择数据从 JSON 数据加载选择选项

java - 将 HTML 5 数据属性传递给 Play!表单输入

python - 除非我停止并重新启动我的程序,否则我无法选择最近的 INSERT 到我的数据库

python - 如何实现L1逻辑回归?

python -matplotlib : figsize for subplots - adding space between rows

javascript - 使用 Django 按钮来选择项目