当用户成功登录并进入主页时,有一个链接“更改密码”用于更改密码。它显示一个表格来更改密码,其中有三个旧密码输入框,新密码确认新密码
这是我的代码。
forms.py
class reset_form(forms.Form):
oldpassword = forms.CharField(max_length = 20, widget=forms.TextInput(attrs={'type':'password', 'placeholder':'your old Password', 'class' : 'span'}))
newpassword1 = forms.CharField(max_length = 20, widget=forms.TextInput(attrs={'type':'password', 'placeholder':'New Password', 'class' : 'span'}))
newpassword2 = forms.CharField(max_length = 20, widget=forms.TextInput(attrs={'type':'password', 'placeholder':'Confirm New Password', 'class' : 'span'}))
def clean(self):
if 'newpassword1' in self.cleaned_data and 'newpassword2' in self.cleaned_data:
if self.cleaned_data['newpassword1'] != self.cleaned_data['newpassword2']:
raise forms.ValidationError(_("The two password fields did not match."))
return self.cleaned_data
views.py
def change_password(request):
if request.method == 'POST':
form = reset_form(request.POST)
if form.is_valid():
newpassword=form.cleaned_data['newpassword1'],
username=request.user.username
password=request.user.password
user = authenticate(username=username, password=password)
if user is not None:
user.set_password(newpassword)
user.save()
return HttpResponseRedirect('/reset/success/')
else:
return render(request, 'reset_password.html',{'error':'You have entered wrong old password','form': form})
else:
return render(request, 'reset_password.html',{'error':'You have entered old password','form': form})
else:
form = reset_form()
content = RequestContext(request, {'form': form})
return render(request, 'reset_password.html', content,)
在提交带有正确旧密码的表单后,我收到此消息您输入了错误的旧密码我不知道为什么我要纠正此错误消息请帮助此代码
答案 0 :(得分:5)
出于某种原因,您通过request.user
使用存储在数据库中的密码字段,而不是他们实际在表单中输入的密码字段。数据库版本经过哈希处理,当您调用authenticate
时,它会再次哈希,因此无法匹配。
您应该使用用户在表单中输入的值:
username = request.user.username
password = form.cleaned_data['oldpassword']
user = authenticate(username=username, password=password)