Django:如何将参数传递给表单

时间:2015-04-30 17:24:56

标签: django django-forms

我有一个用bootstrap3渲染的Django表单。我希望能够将参数传递给我的表单,使其更通用。我的表格如下:

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)

我的观点如下:

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

当我运行此代码时,我收到错误:

/ InterfaceApp / schedule_search /上的NameError, 名称'选项'未定义

1 个答案:

答案 0 :(得分:2)

问题是,当您定义表单字段时,choices变量不可用,即当Python解析forms.py文件时,它仅在表单实例化时可用,在{{1}内1}}。然后,您需要更新__init__内的字段。

__init__