我已经构建了一个表单,它通过覆盖表单的__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'].choices 并且每次它们都相同但 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'] 不是可用的选择之一。
我不知道为什么会出现错误,因为“不可调和”显然在每种情况下的选择列表中。
如果有人能看到我做错了什么,我将非常感谢他们指出这一点。
提前致谢。