问题
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
回答1:
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=[])
来源:https://stackoverflow.com/questions/29974105/django-how-to-pass-parameters-to-forms