Skip to content

Change Password

In this video, we are going to learn how to implement the feature of change password in django.

Resources:

Forms

In the forms.py file, at first import the PasswordChangeForm

from django.contrib.auth.forms import (PasswordChangeForm)

Now create a class named ChangePasswordForm that inherits this PasswordChangeForm

class ChangePasswordForm(PasswordChangeForm):
    # Now, we have to add form-control to every field of this form
    def __init__(self, *args, **kwargs):
        super(ChangePasswordForm, self).__init__(*args, **kwargs)
        for visible in self.visible_fields():
            visible.field.widget.attrs["class"] = "form-control"

    # After that create a meta class to link the user model with this form.
    class Meta:
        model = User
        fields = "__all__"

In this way, we have written ChangePasswordForm that inheirts the functionality of this built PasswordChangeForm by django.

Views

In the views.py file, import this form.

from user.forms import ChangePasswordForm

Now, lets write a view name change_pasword.

[At first explain the get method and then post method]

def change_password(request):
    # When the user sends the POST request.
    if request.method == "POST":
        # At first, we will instantiate the form.
        form = ChangePasswordForm(request.user, request.POST)
        # To change the password the user must be logged in 
        # and when the user is logged in we can get their information from request.user
        # If the form is valid
        if form.is_valid():
            # We will save the form
            form.save()
            # After saving the form, we need to update the session auth information of that user in session table.
            # For that, django provides a method named update_session_auth_hash.
            # This method is used to securely update the session authentication hash after a user changes their password. 
            # It ensures that the user's session remains secure by invalidating the old session key and creating a new one with the updated password. 
            # This helps protect against unauthorized access and session hijacking.
            update_session_auth_hash(request, form.user)
            # After updating the session data, show the success message.
            messages.success(request, "Password Changed Successfully")
            # Then redirect the user to the index page.
            return HttpResponseRedirect(reverse("index"))
        # If the form was invalid, the user has entered wrong data
        # In this case, we will show the error message.
        messages.error(request, "Unable to change password! Please enter valid data")
        # Then, we will render the change-password.html file
        return render(request, "user/change-password.html", {"form": form})
    # When the user sends the get request, we will shoe the ChangePasswordForm
    # This form takes request.user.
    # Using this request.user, we are passing the currently logged in user information to this form.
    context = {"form": ChangePasswordForm(request.user)}
    # After that render this form in the change-password.html file.
    return render(request, "user/change-password.html", context)
from django.contrib.auth import (update_session_auth_hash)

In this way, we have learnt how to create a view for change password in django.

Templates

Now, we need to create a template for this view.

Create change-password.html file in the templates folder.

I have attached change-password.html file in the resources section. Download it and copy its content and paste it in this html file.

{% extends 'mysite/base.html' %}

{% block title %} 
    <title>Change Password</title>
{% endblock title %}

{% block content %}
<div class="card p-3">
  <div class="card-body">
    <h4>Fill the following details to change your password</h4>
    {% include "components/form.html" with form_name="Change Password" %}
  </div>
</div>
{% endblock content %}

Urls

Now, lets add a url path for this view.

path("change-password/", views.change_password, name="change-password"),

[Run the development server and see the changes.]