我已经构建了一个表单,它通过覆盖表单的__init
__方法来获取动态的选择列表。
class AssociateSfnForm(forms.Form):
chosen_sfns = forms.ChoiceField(label='', widget=forms.CheckboxSelectMultiple)
def __init__(self, sfn_choices, *args, **kwargs):
super(AssociateSfnForm, self).__init__(*args, **kwargs)
self.fields['chosen_sfns'].choices = sfn_choices
print self.fields['chosen_sfns'].choices
一切正常,但我不断收到验证错误,说明选择无效。在我看来,我在测试表单验证之前设置了选择列表:
def manually_match_sfns(request, cgs335_id):
cgs335 = get_object_or_404(Cgs335, pk=cgs335_id)
# number of SFNs to bring back and display to the user
number = 10
sfn_choices = get_sfn_choices(cgs335.aircraft, cgs335.flying_date, number)
if request.method == 'POST':
form = AssociateSfnForm(sfn_choices, request.POST )
if form.is_valid():
--- processing here ----
else:
form = AssociateSfnForm(sfn_choices)
extra_context = {}
extra_context.update({'cgs335': cgs335})
extra_context.update({'form': form})
return render(request, 'sumdata/manually_match_sfns.html', extra_context)
调试此问题时,我检查form.fields ['chosen_sfns']。选项,每次它们相同但is_valid()方法抛出验证错误。
页面加载前的选择...
-> return render(request, 'sumdata/manually_match_sfns.html', extra_context)
(Pdb) form.fields['chosen_sfns'].choices
[('149907AUT_26/03/13 15:28:37', '149907AUT_26/03/13 15:28:37 -- 2013-03-26 12:34:02 -- Debrief #1 Post RON Entered By XXXXXX From CGS335# 13103'), ..., ('Irreconcilable', 'Irreconcilable -- Do not try to associate again.'), ('Not Associated', 'Not Associated -- Come back to this one later')]
验证前的选择......
-> if form.is_valid():
(Pdb) form.fields['chosen_sfns'].choices
[('149907AUT_26/03/13 15:28:37', '149907AUT_26/03/13 15:28:37 -- 2013-03-26 12:34:02 -- Debrief #1 Post RON Entered By XXXXXX From CGS335# 13103'), ..., ('Irreconcilable', 'Irreconcilable -- Do not try to associate again.'), ('Not Associated', 'Not Associated -- Come back to this one later')]
我选择了Irreconcilable并收到以下错误消息: 选择一个有效的选择。 [u'Irreconcilable']不是可用的选择之一。
我不知道为什么会出现错误,因为“不可调和”显然是在每种情况下的选择列表中。
如果有人能看出我做错了什么,我真的很感激他们指出来。
提前致谢。
答案 0 :(得分:0)
字段类型和窗口小部件之间存在不匹配。我想要多重选择。
变化:
chosen_sfns = forms.ChoiceField(label='', widget=forms.CheckboxSelectMultiple)
要:
chosen_sfns = forms.MultipleChoiceField(label='', widget=forms.CheckboxSelectMultiple)