这是我的表格:
class ch_form(forms.Form):
ch_field = forms.ChoiceField(
required=True , label= 'ch_field : ' ,
)
这是我的观点:
def testView(request):
form = ch_form(
initial={
'ch_field':[
(1, 'test1'),
(2, 'test2'),
(3, 'test3'),
]
}
)
但是它不起作用。
所以我的问题是,如何在运行时为视图功能中的forms.ChoiceField
设置值。
对不起,我的英语不好。
答案 0 :(得分:1)
您可以尝试使用lastUpdated
形式的方法来设置选择,也许是这样的:
__init__()
然后这样称呼它:
class MyForm(forms.Form):
ch_field = forms.ChoiceField(
required=True,
label= 'ch_field')
def __init__(self, *args, **kwargs):
my_choices = kwargs.pop('my_choices')
super().__init__(*args, **kwargs)
self.fields['ch_field'].choices = my_choices