[英]How to replace choices list for TypedChoiceField in Django form?
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
. 我想使用基于此模型的表单,但是我想将选择列表的一部分传递给它,
PublicTracks.TRACK_CHOICES
。
I've looked at the structure of the form. 我看了表格的结构。 In the
base_fields
dictionary, track
is a TypedChoiceField
object. 在
base_fields
词典中, track
是一个TypedChoiceField
对象。 That object has an attribute choices
, which is list(AllTracks.TRACK_CHOICES)
. 该对象具有一个
choices
属性,即list(AllTracks.TRACK_CHOICES)
。 I've tried replacing it with list(AllTracks.TRACK_CHOICES)
but it doesn't seem to take. 我尝试用
list(AllTracks.TRACK_CHOICES)
替换它,但似乎没有用。
Any suggestions on how I might override the list from the model definition would be appreciated. 关于如何从模型定义中覆盖列表的任何建议将不胜感激。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.