You have the user object. So you can just call it's set_password
method.
request.user.set_password(password)
Also, you don't need to get the user again from the database. You're making an unnecessary DB request. request.user
is the user.
I would rewrite the entire view like so,
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})
This means that if there is POST data you initialise the form with it. Otherwise it gets None
. If the form is valid (which an empty form never will be) then you do the password change and send them to a success page. Otherwise you return the empty form (or the form with the validation errors) to the user.