当我在视图中调用表单时,我正在尝试将OTHER_VALUE作为参数传递给表单。
之所以这样做,是因为我想从视图中获取验证并进入表单。
views.py
OTHER_VALUE = "the query that i run to get silly conditions"
if request.method=='POST':
form = MY_FORM(request.POST, OTHER_VALUE)
forms.py
class MY_FORM(forms.Form):
real_value = forms.CharField()
def clean_real_value(self):
if OTHER_VALUE ...
这可能会引发错误:
__init__() got an unexpected keyword argument 'OTHER_VALUE'
=========
我尝试使用__init__
的一些不同变体来设置init:
class MY_FORM(forms.Form):
real_value = forms.CharField()
def __init__(self, *args, **kwargs):
OTHER_VALUE = kwargs.pop('OTHER_VALUE')
super(MY_FORM, self).__init__(*args, **kwargs)
self.fields['OTHER_VALUE'].initial = OTHER_VALUE
但是我一直收到这种类型的错误:
Exception Value: 'employee'
Exception Location: /Users/macbook/Desktop/OrgDB/orgchart/forms.py in __init__, line 42
答案 0 :(得分:2)
一种方法是将隐藏输入作为表单中的字段
class MY_FORM(forms.Form):
real_value = forms.CharField()
other_value = forms.CharField(max_length=255,required=False,
widget=forms.HiddenInput())
此新字段可以在您的表单中提供,但最重要的是确保在检查表单验证之前添加值。
OTHER_VALUE = "other_value"
if request.method=='POST':
data = request.POST.copy()
data['other_value'] = OTHER_VALUE
form = MY_FORM(data)
if form.is_valid():
pass
在您的表单中,您可以访问以下值:
....# codes
real_value = forms.CharField()
other_value = forms.CharField(max_length=255,required=False,
widget=forms.HiddenInput())
def clean_real_value(self):
cleaned_data = super(FormName,self).clean_real_value()
OTHER_VALUE = cleaned_data.get("other_value")
if OTHER_VALUE ...
答案 1 :(得分:-1)
将OTHER_VALUE传递给表单时,请为其分配键OTHER_VALUE=OTHER_VALUE
,而不仅仅是按位置访问它。
views.py
if request.method=='POST':
form = MY_FORM(request.POST, OTHER_VALUE=OTHER_VALUE)
forms.py
def __init__(self, *args, **kwargs):
self.OTHER_VALUE = kwargs.pop('OTHER_VALUE', None)
super(MY_FORM, self).__init__(*args, **kwargs)
在其余表单类中将OTHER_VALUE引用为self.OTHER_VALUE