How to change a user’s password in Django

In order to let Django users to change their own passwords, it is necessary to provide them with an interface, that is not “admin”. Following is a bare bone sample for the change view.

One item of importance and the reason I am writing this post is that, in most (maybe all) documents and samples I had access to, login() call (at 48th line of my view sample) after saving user instant, was not mentioned. That is required, because when you overwrite current request’s user’s records, you also need to relogin current user again, as credentials needed to be renewed in such situations.

View sample:

#coding: UTF-8
from django.shortcuts import render
from django.contrib.auth import authenticate, login, logout
from django.http.response import HttpResponseRedirect
from django.urls import resolve, reverse
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ObjectDoesNotExist

from project.settings import LOGIN_URL

from cuser.middleware import CuserMiddleware

@login_required
def PassView(request):
    template_name='ServiceApp/pass.html'
    if request.method=="POST":
        current=request.POST['current']
        password_1=request.POST['password_1']
        password_2=request.POST['password_2']
        prob_mismatch=False
        prob_length=False
        prob_current=False
        prob_user_ex=False
        error_message=[]
        if password_1!=password_2:
            prob_mismatch=True
            error_message.append(u'New Passwords do not match')
        if password_1.__len__()<9:
            prob_length=True
            error_message.append(u'New password must be at least 9 characters long')
        try:
            user=User.objects.get(username=CuserMiddleware.get_user().__str__())
        except ObjectDoesNotExist:
            prob_user_ex=True
            error_message.append('Our user has experienced an existential crisis')
        if user.check_password(gecerli)==False:
            prob_current=True
            error_message.append(u'Current password given, do not match records)
        if prob_current or prob_length or prob_mismatch or prob_user_ex:
            context={
                'error_message':error_message,
                }
            return render(request,template_name,context)
        else:
            user.set_password(password_1)
            user.save()
            login(request,user)
            return HttpResponseRedirect(reverse('main_screen'))
    else:
        context={
            'error_message':error_message,
            }
        return render(request,template_name,context)