【问题标题】:Django: how to pass parameters to formsDjango:如何将参数传递给表单
【发布时间】:2015-07-10 12:45:43
【问题描述】:

我有一个用 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/ 处的名称错误, 名称“选择”未定义

【问题讨论】:

  • 请添加完整的错误回溯

标签: django django-forms


【解决方案1】:

问题是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=[])

【讨论】:

  • choices = kwargs.pop('choices') 更改为self.choices = kwargs.pop('choices') 会产生同样的错误
  • @klwahl 您不能在scID 字段定义中使用choices。我没有看到你在这里使用它。我将尝试编辑我的答案以使其正常工作。
猜你喜欢
  • 2020-04-13
  • 2013-01-17
  • 2020-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-11
  • 2011-11-10
  • 1970-01-01
相关资源
最近更新 更多