django更改密码表单不会引发错误

时间:2015-07-08 11:19:47

标签: python django forms validation

我有一个更改密码的表单:

class PasswordChangeForm(forms.Form):
old_password = forms.CharField(max_length=20)
new_password1 = forms.CharField(max_length=20)
new_password2 = forms.CharField(max_length=20)

def __init__(self, user, *args, **kwargs):
    self.user = user
    super(PasswordChangeForm, self).__init__(*args, **kwargs)

def clean_old_password(self):
    old_password = self.cleaned_data.get("old_password")

    if not self.user.check_password(old_password):
        raise forms.ValidationError("Your old password is wrong")
    return old_password

def clean_new_password2(self):
    new_password1 = self.cleaned_data.get("new_password1")
    new_password2 = self.cleaned_data.get("new_password2")
    if new_password1 and new_password2 and new_password1 != new_password2:
        raise forms.ValidationError("Your new passwords didn't match")
    return new_password2

在我看来,我有:

class PasswordChangeView(View):
form_class = PasswordChangeForm
template_name = 'registration/password_change.html'

def get(self, request, *args, **kwargs):
    form = self.form_class(user=self.request.user)
    return render(request, self.template_name, {'form': form})

def post(self, request, *args, **kwargs):
    form = self.form_class(request.POST)
    print("wow")
    if form.is_valid():
        #My logic here
        return redirect("password_change_successful")
    return render(request, self.template_name, {'form': form})

但是我的form.is_valid()函数没有被调用..即使我输入了错误的旧密码或错误的新密码,它也不会引起错误。

这里有什么问题? 谢谢

1 个答案:

答案 0 :(得分:0)

我相信你滥用基于类的观点。 您的观点应该继承自FormView,而不是简单View。 它应该有一个带有签名form_valid(self, form)的方法,只要提交了有效的表单就会调用它。 此外,您不需要覆盖get和post方法。事实上,这样做并不是一个好主意。 我为这些批评道歉。 以下是您的观点的样子:

class PasswordChangeView(FormView):
    form_class = PasswordChangeForm
    success_url = reverse("password_change_successful")  # if form had no errors, FormView redirects to this url
    template_name = 'registration/password_change.html'

    def form_valid(self, form, *args, **kwargs):
    # print "wow"
    logger.debug("Wow, some user has sent a valid form!")
    return super(PasswordChangeView, self).form_valid(form, *args, **kwargs)

    # def get(...)
    # there is really no need to override get(), FormView will do everything for you 

    # def post(...)
    # same story with the post, if your form was valid,
    # form_valid() will be called, otherwise user will stay on the
    # same page, with the same form displaying the validation errors