如何在Django表单中替换TypedChoiceField的选择列表?(How to replace choices list for TypedChoiceField in Django form

编程入门 行业动态 更新时间:2024-10-27 11:16:42
如何在Django表单中替换TypedChoiceField的选择列表?(How to replace choices list for TypedChoiceField in Django form?)

我有一个类,其中包含一个带有选项列表的字段:

class Game(models.Model): track = models.CharField(max_length=5, choices=AllTracks.TRACK_CHOICES)

我想使用基于此模型的表单,但我想将其传递给选项列表PublicTracks.TRACK_CHOICES的子集。

我看过表格的结构。 在base_fields字典中, track是TypedChoiceField对象。 该对象有一个属性choices ,即list(AllTracks.TRACK_CHOICES) 。 我已经尝试用list(AllTracks.TRACK_CHOICES)替换它,但它似乎没有。

有关如何从模型定义覆盖列表的任何建议将不胜感激。

I have a class which includes a field with a choice list:

class Game(models.Model): track = models.CharField(max_length=5, choices=AllTracks.TRACK_CHOICES)

I want to use a form based on this model, but I want to pass it a subset of the choice list, PublicTracks.TRACK_CHOICES.

I've looked at the structure of the form. In the base_fields dictionary, track is a TypedChoiceField object. That object has an attribute choices, which is list(AllTracks.TRACK_CHOICES). I've tried replacing it with list(AllTracks.TRACK_CHOICES) but it doesn't seem to take.

Any suggestions on how I might override the list from the model definition would be appreciated.

最满意答案

您可以在表单类上定义完全自定义字段,否则将覆盖从模型自动生成的字段 ,如覆盖默认字段中所述 :

class GameForm(forms.ModelForm): track = forms.ChoiceField(choices=WHATEVER, ...) class Meta(object): model = Game

You can define a completely custom field on your form class, overriding the one that would be auto-generated from your model otherwise, as described in Overriding the default fields:

class GameForm(forms.ModelForm): track = forms.ChoiceField(choices=WHATEVER, ...) class Meta(object): model = Game

更多推荐

本文发布于:2023-07-31 13:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1345284.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表单   列表   如何在   Django   form

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!