0

我有如下密码更改表格

表格.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

模板.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>

视图.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})       

那么在上面的代码中,我们如何使用用户提供的旧密码检查保存在数据库中的密码呢?另外,我们如何创建新密码并存入数据库?

之后向用户发送电子邮件,您的密码已成功更改

4

2 回答 2

2

你有用户对象。所以你可以调用它的set_password方法。

request.user.set_password(password) 

此外,您不需要再次从数据库中获取用户。您正在发出不必要的数据库请求。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. 如果表单有效(空表单永远不会),那么您更改密码并将其发送到成功页面。否则,您将空表单(或带有验证错误的表单)返回给用户。

于 2013-11-08T11:52:29.393 回答
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()
于 2013-11-08T11:53:37.820 回答