我有密码更改表格,如下所示
forms.py
class PasswordChangeForm(forms.Form):
old_password = forms.CharField(widget=forms.PasswordInput())
new_password = forms.CharField(widget=forms.PasswordInput())
confirm_password = forms.CharField(widget=forms.PasswordInput())
def clean(self):
if self.cleaned_data['new_password'] != self.cleaned_data['confirm_password']:
raise forms.ValidationError(_('The new passwords must be same'))
else:
return self.cleaned_data
template.html
<form action="/save/data/" method="post">
<div>
<p>{{form.old_password}}</p>
<span>{{form.old_password.errors}}</span>
</div>
<div>
<p>{{form.new_password}}</p>
<span>{{form.new_password.errors}}</span>
</div>
<div>
<p>{{form.confirm_password}}</p>
<span>{{form.confirm_password.errors}}</span>
</div>
</form>
views.py
@login_required
def change_password(request):
user_obj = User.objects.get(id=request.user.id)
form = PasswordChangeForm()
if request.method=="POST":
form = PasswordChangeForm(reques.POST)
#########
Here in this part i need to check if the user given old passoword
matched the already saved password in the database, create a password
with the user given new password
#########
new_password = form.cleaned_data['new_password']
......
user_obj.password = new_password
..........
return render_to_response('template.html',{'form':form})
所以在上面的代码中,我们如何使用用户提供的旧密码检查数据库中保存的密码?还有,我们如何创建新密码并进入数据库?
之后向用户发送电子邮件,该密码已成功更改
答案 0 :(得分:2)
您拥有用户对象。所以你可以称之为set_password
方法。
request.user.set_password(password)
此外,您无需再次从数据库中获取用户。你正在做一个不必要的DB请求。 request.user
是用户。
我会像这样重写整个视图,
from django.shortcuts import render
@login_required
def change_password(request):
form = PasswordChangeForm(request.POST or None)
if form.is_valid()
if request.user.check_password(form.cleaned_data['old_password']):
request.user.set_password(form.cleaned_data['new_password'])
request.user.save()
return render(request, 'success.html')
return render(request, 'template.html', {'form':form})
这意味着如果有POST数据,则用它初始化表单。否则它会None
。如果表单有效(永远不会是空表单),那么您将更改密码并将其发送到成功页面。否则,您将空表单(或带有验证错误的表单)返回给用户。
答案 1 :(得分:0)
您可以通过check_password方法查看。
if request.user.check_password(form.cleaned_data['old_password']):
request.user.set_password(form.cleaned_data['new_password'])
request.user.save()