Django 2 by Example
上QQ阅读APP看书,第一时间看更新

Changing password views

We also need 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:

# 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 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. Let's create a template for each view.

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 %}

The password_change_form.html template includes the form to change the password. Now, create another file in the same directory and name it password_change_done.html. 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_done.html template only contains the success message to be displayed when the user has successfully changed their password.

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.