Django Forms:传递参数以形成 [英] Django Forms: pass parameter to form
本文介绍了Django Forms:传递参数以形成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将参数传递给我的表单?
How do I pass a parameter to my form?
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__您的表单的方法,如下所示:
You should define the __init__ method of your form, like that:
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直到对象被创建,所以行:
of course you cannot access self.site_id until the object has been created, so the line:
height = forms.CharField(widget=forms.TextInput(attrs={'size':site_id}))
没有任何意义。您必须在窗体创建后将该属性添加到窗口小部件。尝试这样的东西:
makes no sense. You have to add the attribute to the widget after the form has been created. Try something like this:
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 Forms:传递参数以形成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文