Django 表单:将参数传递给表单 [英] Django Forms: pass parameter to form
本文介绍了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
推荐答案
您应该定义表单的 __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 表单:将参数传递给表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文