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

回答:

你应该定义表单的__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()

以上是 Django表单:将参数传递给表单 的全部内容, 来源链接: utcz.com/qa/422014.html

回到顶部