小编典典

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

django

如何将参数传递给表单?

someView()..
    form = StylesForm(data_dict) # I also want to pass in site_id here.

class StylesForm(forms.Form):
    # I want access to site_id here

根据以下答案进行编辑:

someView()..
    form = StylesForm(data_dict, site_id = 1)

class StylesForm(forms.Form):
     def __init__(self,*args,**kwargs):
        self.site_id = kwargs.pop('site_id')
        super(StylesForm,self).__init__(*args,**kwargs)

     height = forms.CharField(widget=forms.TextInput(attrs={'size':site_id}))

阅读 667

收藏
2020-04-01

共1个答案

小编典典

你应该定义表单的__init__方法,如下所示:

class StylesForm(forms.Form):
    def __init__(self,*args,**kwargs):
        self.site_id = kwargs.pop('site_id')
        super(StylesForm,self).__init__(*args,**kwargs)
当然,在创建对象之前,你无法访问self.site_id,因此该行:

     height = forms.CharField(widget=forms.TextInput(attrs={'size':site_id}))

没有意义。创建表单后,必须将属性添加到窗口小部件。尝试这样的事情:

class StylesForm(forms.Form):
    def __init__(self,*args,**kwargs):
        self.site_id = kwargs.pop('site_id')
        super(StylesForm,self).__init__(*args,**kwargs)
        self.fields['height'].widget = forms.TextInput(attrs={'size':site_id})

    height = forms.CharField()
2020-04-01