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

kdu*_*ubs 2 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)
Run Code Online (Sandbox Code Playgroud)

我的观点如下:

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})
Run Code Online (Sandbox Code Playgroud)

当我运行此代码时,出现错误:

/InterfaceApp/schedule_search/ 处的 NameError,未定义名称“选择”

aum*_*umo 5

问题是choices当您定义表单字段时该变量不可用,即当 Python 解析forms.py文件时,它仅在表单被实例化时可用,在__init__. 然后你需要更新里面的字段__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=[])
Run Code Online (Sandbox Code Playgroud)