Django:' Form'对象没有属性' clean_data'

时间:2017-02-17 07:43:17

标签: python django forms web

我制作了密码重置表格,其中包含3个密码,旧密码,新密码,并确认新密码。到目前为止,我成功地将其显示在HTML中,但无法继续进行。每当我单击提交按钮时,它会显示错误消息。我已经在堆栈溢出中搜索了这个错误并更改了它但仍然显示错误。

这是错误消息。

AttributeError at /blog/password_change/blue/
'PasswordChangeForm' object has no attribute 'clean_data'

View.py

@login_required
def password_change(request, username):
    if request.method == 'POST':
        form = PasswordChangeForm(data=request.POST, user=request.POST)

        if form.is_valid():            
            oldpassword = form.cleaned_data.get('oldpassword')
            password = form.cleaned_data.get('password')
            password2 = form.cleaned_data.get('password2')
        if oldpassword == password2:
            update_session_auth_hash(request, form.username)
            form.save()
            return HttpResponseRedirect('/blog/password_change_done/') 
        else:
            return render(request, 'blog/detail.html', {'error_message': 'password mismatch'})
            #return redirect(reverse('blog:home'))
            #return redirect(reverse('blog:profile', args=[form.user.get_username()]))

else:
    print("C")
    form = PasswordChangeForm(user=request.user)
    return redirect(reverse('blog:profile', args=[form.user.get_username()]))

对于oldpassword = form.cleaned_data.get(' oldpassword'),我也尝试过oldpassword = form.Cleaned_data [' oldpassword'],但它也提出了相同的错误消息。

forms.py

class PasswordChangeForm(forms.Form):
oldpassword = forms.CharField(widget=PasswordInput())
password1 = forms.CharField(widget=PasswordInput())
password2 = forms.CharField(widget=PasswordInput())

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

def clean_oldpassword(self):
    if self.clean_data.get('oldpassword') and not self.user.check_password(self.clean_data['oldpassword']):
        raise ValidationError('Please type your current password.')
    return self.clean_data['oldpassword']

def clean_password2(self):
    if self.clean_data.get('password1') and self.clean_data.get('password2') and self.clean_data['password1'] != self.clean_data['password2']:
        raise ValidationError('The new passwords are not the same')
    return self.clean_data['password2']

1 个答案:

答案 0 :(得分:1)

您的代码有多个问题,

1)而不是clean_data,它应该是cleaned_data

2)在表单中传递用户对象时,您应该设置user=request.user而不是user=request.POST

form = PasswordChangeForm(data=request.POST, user=request.user)