我想用ajax视图验证一些表单。
class ProfileEditPasswordForm(PasswordChangeForm):
class Meta:
model = User
class AjaxValidation(generic.edit.FormView):
def get(self, request, *args, **kwargs):
return HttpResponseRedirect('/')
def form_invalid(self, form):
data = []
for k, v in form._errors.iteritems():
text = {
'desc': ', '.join(v),
}
if k == '__all__':
text['key'] = '#%s' % self.request.POST.get('form')
else:
text['key'] = '#id_%s' % k
data.append(text)
return HttpResponse(json.dumps(data))
def form_valid(self, form):
return HttpResponse("ok")
def get_form_class(self):
form_dict = {
'signup': forms.RegisterForm,
'signin': forms.LoginForm,
'safety': forms.ProfileEditPasswordForm
}
return form_dict[self.request.POST.get('form')] #=> TypeError
如您所见,我有3种不同的形式。前两个工作就好了。但第三个给我一个错误。
__init__() takes at least 2 arguments (1 given)
我相信这是因为我的表单要求用户验证他的旧密码,所以我这样做了:
'safety': forms.ProfileEditPasswordForm(user=self.request.user)
并且知道它会引发另一个错误:
'ProfileEditPasswordForm' object is not callable
在这里我卡住了。
Traceback:
File "***/env/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "***/env/local/lib/python2.7/site-packages/django/views/generic/base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "***/env/local/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
89. return handler(request, *args, **kwargs)
File "***/env/local/lib/python2.7/site-packages/django/views/generic/edit.py" in post
213. form = self.get_form()
File "***/env/local/lib/python2.7/site-packages/django/views/generic/edit.py" in get_form
74. return form_class(**self.get_form_kwargs())
Exception Type: TypeError at /accounts/validate/
Exception Value: 'ProfileEditPasswordForm' object is not callable
Request information:
GET: No GET data
POST:
csrfmiddlewaretoken = u'MjSRpY4NQsTuv6hG8HLYZYI3n9HpPU4R'
form = u'safety'
old_password = u''
new_password1 = u''
new_password2 = u''
答案 0 :(得分:1)
我认为问题是django FormView
与PasswordChangeForm
不兼容。表单要求将用户传递给其构造函数,但视图不会这样做。您可以尝试覆盖get_form_kwargs
这样的方法:
class AjaxValidation(generic.edit.FormView):
# your methods
def get_form_kwargs(self):
kwargs = super(AjaxValidation, self).get_form_kwargs()
kwargs['user'] = self.request.user
return kwargs
kwargs
将传递给表单构造函数,它应该可以工作。您的主代码示例中的get_form_class
正常