Tuesday, October 15, 2019

Integrating Django authentication views for password change

It is required for our users to be able to change their password after they log in to our site. We will integrate Django authentication views for password change. Open the urls.py file of the account application and add the following URL patterns to it:

from django.urls import path
from django.contrib.auth import views as auth_views
from . import views

urlpatterns = [

    path('login/', auth_views.LoginView.as_view(),name='login'),
    path('logout/', auth_views.LogoutView.as_view(),name='logout'),
    path('', views.dashboard, name='dashboard'),
   
    # change password urls
    path('password_change/',auth_views.PasswordChangeView.as_view(),name='password_change'),
    path('password_change/done',auth_views.PasswordChangeDoneView.as_view(),name='password_change_done'),

   
    ]

The code added above means that PasswordChangeView view will handle the form to change the password, and the PasswordChangeDoneView view will display a success message after the user has successfully changed his password.

Now we'll create a template for each view. First add a new file inside the templates/registration/ directory of your account application and name it password_change_form.html. Add the following
code to it:

{% extends "base.html" %}

{% block title %}Change you password{% endblock %}

{% block content %}
  <h1>Change you password</h1>
  <p>Use the form below to change your password.</p>
  <form action="." method="post">
    {{ form.as_p }}
    <p><input type="submit" value="Change"></p>
    {% csrf_token %}
  </form>
{% endblock %}






Now, create another file, password_change_done.html, in the same directory . Add the following code to it:

{% extends "base.html" %}

{% block title %}Password changed{% endblock %}

{% block content %}
  <h1>Password changed</h1>
  <p>Your password has been successfully changed.</p>
{% endblock %}

The password_change_form.html template includes the form to change the password. The password_change_done.html template only contains the success message to be displayed when the user has successfully changed their password.

Now open http://127.0.0.1:8000/account/password_change/ in your browser. If your user is not logged in, the browser will redirect you to the login page. After you are successfully authenticated, you will see the following change password page:







Fill in the form with your current password and your new password, and click on the CHANGE button. You will see the following success page:


Log out and log in again using your new password to verify that everything works as expected. In the next post we'll work with password resetting views.
Share:

0 comments:

Post a Comment