我有一个类,其中包含一个带有选项列表的字段:
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 = GameYou 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更多推荐
发布评论