在django表单中显示特定字段

ou6hu8tu  于 2022-12-05  发布在  Go
关注(0)|答案(3)|浏览(160)

我在django表单中有以下字段:

position = forms.ModelChoiceField(Position.objects.order_by('-ordering'),
                                    empty_label='Select Position',)

在我的Position模型中,我使用unicode字段来显示名为“position”的字段。然而,在这个特定的表单中,我希望输出是模型中名为“position-select”的不同字段。如果不更改unicode字段的默认输出,我该如何做到这一点?

  • 谢谢-谢谢
inb24sb2

inb24sb21#

这是有效的方法:

class PositionSelect(forms.ModelChoiceField):
    def label_from_instance(self, obj):
        return obj.select_display

class Position(forms.Form):
    position = PositionSelect(Position.objects.order_by('-ordering'),
                                    empty_label='Select Position',)
guykilcj

guykilcj2#

根据www.example.com上的示例,尝试“子类化ModelChoiceField并覆盖label_from_instance”https://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield。您可以在该覆盖类中指定对其他字段的__unicode__函数的引用。

toiithl6

toiithl63#

在表单的init方法内的一行中:

self.fields['position'].label_from_instance = lambda obj: f"{obj.position_select}"

相关问题