Viktor Danilov Viktor Danilov - 1 year ago 83
Ajax Question

How to ajaxable validate a PasswordChangeForm?

I have some forms that I want to validate with an ajax view.

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')
text['key'] = '#id_%s' % k
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

As you can see, I have 3 different forms. First two work just fine. But the third one returns me an error.

__init__() takes at least 2 arguments (1 given)

I believe that it happens because my form requires a user to validate his old password, so I did this:

'safety': forms.ProfileEditPasswordForm(user=self.request.user)

And know it throws another error:

'ProfileEditPasswordForm' object is not callable

And here I stuck.

File "***/env/local/lib/python2.7/site-packages/django/core/handlers/" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "***/env/local/lib/python2.7/site-packages/django/views/generic/" in view
71. return self.dispatch(request, *args, **kwargs)
File "***/env/local/lib/python2.7/site-packages/django/views/generic/" in dispatch
89. return handler(request, *args, **kwargs)
File "***/env/local/lib/python2.7/site-packages/django/views/generic/" in post
213. form = self.get_form()
File "***/env/local/lib/python2.7/site-packages/django/views/generic/" 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

csrfmiddlewaretoken = u'MjSRpY4NQsTuv6hG8HLYZYI3n9HpPU4R'
form = u'safety'
old_password = u''
new_password1 = u''
new_password2 = u''

Answer Source

I think the problem is that django FormView is not compatible with PasswordChangeForm. The form requires the user to be passed to its constructor, but the view will not do that. You could try overriding get_form_kwargs method like this:

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

The kwargs will be passed to form constructor and it should work. get_form_class is OK in your main code example

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download