2

I have a Django form that is rendered with bootstrap3. I want to be able to pass parameters into my form to make it more generic. My forms looks like:

class SpacecraftID(forms.Form):
  def __init__(self,*args,**kwargs):
    choices = kwargs.pop('choices')
    #self.choices = kwargs.pop('choices') produces same error
    super(SpacecraftID,self).__init__(*args,**kwargs)

  scID = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=choices)

And my view looks like:

def schedule_search(request):
 choices = (
    ('1','SAT1'),
    ('2','SAT2'),
    ('3','SAT3'),
    )

 if request.method == 'POST':
    form_ID = SpacecraftID(request.POST,choices=choices)
    if form.is_valid():
        scID = form_ID.cleaned_data['scID']

 else:
    form_ID = SpacecraftID(choices=choices)

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

When I run this code I get the error:

NameError at /InterfaceApp/schedule_search/, name 'choices' is not defined

kdubs
  • 936
  • 3
  • 22
  • 45

1 Answers1

5

The problem is that the choices variable is not available when you define your form fields, that is when Python parse the forms.py file, it is only available when the form is instantiated, inside __init__. You then need to update the field inside __init__.

class SpacecraftID(forms.Form):
    def __init__(self,*args,**kwargs):
        choices = kwargs.pop('choices')

        super(SpacecraftID,self).__init__(*args,**kwargs)

        # Set choices from argument.
        self.fields['scId'].choices = choices

    # Set choices to an empty list as it is a required argument.
    scID = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=[])
aumo
  • 5,344
  • 22
  • 25
  • changing `choices = kwargs.pop('choices')` to `self.choices = kwargs.pop('choices')` produces the same error – kdubs Apr 30 '15 at 17:52
  • @klwahl You cannot use `choices` in the `scID` field definition. I had not seen you where using it here. I'll try to edit my answer to make it work. – aumo Apr 30 '15 at 18:11