1

I am getting an error message when I try to use MultipleChoiceField with the CheckboxSelectMultiple widget. I built a form using Django's MultipleChoiceField that displays a set of checkboxes for the user to select:

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)

The view looks like this:

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})

When I try this I get the error: local variable 'scID' referenced before assignment, but it works when I set up the choices tuple using numbers as the first element, like this:

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

Why do I have to set the first element as a number for it to work?

kdubs
  • 936
  • 3
  • 22
  • 45
  • 1
    Check your indentation. As shown here, you'll try to build and return an `HttpResponse` object even if the form is not valid. In which case `scID` has never been assigned, leading to the exception shown. That may not be your only error, but it's the first thing to fix. You also don't assign anything to `taskType` in the code show here, or deference it in your format string. – Peter DeGlopper May 05 '15 at 17:16

1 Answers1

0

The forms don't have to be unique. You can specify a prefix for the form when you call it:

form_1 = DataTypeForm(request.POST or None,initial_value=True,prefix="1")
form_2 = DataTypeForm(request.POST or None,initial_value=False,prefix="2")
kdubs
  • 936
  • 3
  • 22
  • 45