Django:如何将参数传递给表单 [英] Django: how to pass parameters to forms

查看:118
本文介绍了Django:如何将参数传递给表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用bootstrap3呈现的Django表单。我希望能够将参数传递到表单中以使其更通用。我的表格如下:

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)

我的视图如下:

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

当我r取消此代码,我收到错误消息:

When I run this code I get the error:

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

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

推荐答案

问题是定义表单字段时,即 choices 变量不可用。 Python解析 forms.py 文件,该文件仅在实例化表单时在 __ init __ 中可用。然后,您需要更新 __ init __ 中的字段。

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

这篇关于Django:如何将参数传递给表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆