2015-05-05 37 views
1

當我嘗試將MultipleChoiceField與CheckboxSelectMultiple小部件一起使用時,出現錯誤消息。我內置使用Django的MultipleChoiceField顯示一組複選框用戶表單選擇:Django MultipleChoiceField選擇元組的限制

class CheckBoxForm(forms.Form): 
def __init__(self,*args,**kwargs): 
    arg_list = kwargs.pop('arg_list') 
    section_label = kwargs.pop('section_label') 
    super(CheckBoxForm,self).__init__(*args,**kwargs) 
    self.fields['box_ID'].choices=arg_list 
    print arg_list 
    self.fields['box_ID'].label=section_label 

box_ID = forms.MultipleChoiceField(required=True, widget=forms.CheckboxSelectMultiple) 

的看法是這樣的:

sat_list = (
    ('a','SAT1'), 
    ('b','SAT2') 
    ) 

if request.method == 'POST': 

    form_scID = CheckBoxForm(request.POST,arg_list=sat_list,section_label="Please Select Satelites") 

    if form_scID.is_valid(): 
     scID = form_scID.cleaned_data['box_ID'] 

    return HttpResponse("Satellite: {sat}".format(sat=scID,type=taskType)) 

else: 
    form_scID = CheckBoxForm(arg_list=sat_list,section_label="Please Select Satelites") 

return render(request, 'InterfaceApp/schedule_search.html', {'form3': form_scID}) 

當我嘗試這個,我得到的錯誤:局部變量「SCID」分配之前引用,但它工作時,我成立了選擇的元組使用數字作爲第一要素,像這樣:

sat_list = (('1','SAT1'),('2','SAT2')) 

爲什麼我的第一個元素設置爲若干FO它工作?

+1

檢查您的縮進。如此處所示,即使表單無效,您也會嘗試構建並返回一個「HttpResponse」對象。在這種情況下,'scID'從來沒有被分配過,導致顯示異常。這可能不是你唯一的錯誤,但這是第一個要解決的問題。你也不要在代碼展示中給'taskType'分配任何東西,或者在你的格式字符串中使用它。 –

回答

0

表單不一定是唯一的。您可以在指定表單時指定前綴:

form_1 = DataTypeForm(request.POST or None,initial_value=True,prefix="1") 
form_2 = DataTypeForm(request.POST or None,initial_value=False,prefix="2")