2013-05-31 19 views
0

我已經構建了一個表單,它通過覆蓋表單的__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')] 

我選擇了不可調和的,並得到了以下錯誤消息: 選擇一個有效的選擇。 [u'irreconcilable']不是可用的選擇之一。

我很茫然,爲什麼會出現錯誤,因爲在每種情況下,「無法調節」顯然都在選項列表中。

如果有人能看到我在做什麼錯我會非常感激他們指出。

在此先感謝。

回答

0

字段類型和小部件之間存在不匹配。我想多選。

變化:

chosen_sfns = forms.ChoiceField(label='', widget=forms.CheckboxSelectMultiple) 

要:

chosen_sfns = forms.MultipleChoiceField(label='', widget=forms.CheckboxSelectMultiple)