django用戶認證系統——修改密碼6
阿新 • • 發佈:2018-02-25
pre pla col blog mit enter containe 因此 fault
再此之前我們已經完成了用戶登錄、註冊、註銷等功能,接下來讓我們繼續為用戶提供修改密碼的功能。該功能 Django 的 auth 應用也已經為我們提供,過程幾乎和之前的登錄功能完全一樣。
編寫修改密碼模板
修改密碼的的視圖函數默認渲染的模板名為 password_change_form.html,因此首先在 registration/ 下新建一個 password_change_form.html 文件,寫入表單代碼(幾乎和登錄頁面一樣),在此就不做過多解釋了,具體請參考 Django 用戶認證系統:登錄 部分的說明。
templates/registration/password_change_form.html
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>修改密碼</title>
<link rel="stylesheet" href="https://unpkg.com/mobi.css/dist/mobi.min.css">
<style>
.errorlist {
color: red;
}
</style>
</head>
<body>
<div class="flex-center">
<div class="container">
<div class="flex-center">
<div class="unit-1-2 unit-1-on-mobile">
<h1><a href="{% url ‘index‘ %}">Django Auth Example</a></h1>
<h3>修改密碼</h3>
<form class="form" action="{% url ‘password_change‘ %}" method="post">
{% csrf_token %}
{{ form.non_field_errors }}
{% for field in form %}
{{ field.label_tag }}
{{ field }}
{{ field.errors }}
{% if field.help_text %}
<p class="help text-small text-muted">{{ field.help_text|safe }}</p>
{% endif %}
{% endfor %}
<button type="submit" class="btn btn-primary btn-block">確認修改</button>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
此外,在首頁加一個修改密碼的按鈕,並且註意只對已登錄用戶顯示:
templates/index.html
{% if user.is_authenticated %}
<p>你已登錄,歡迎你:<a href="#">{{ user.username }}</a></p>
<button class="btn btn-default"><a href="{% url ‘logout‘ %}?next={{ request.path }}">註銷登錄</a>
</button>
<button class="btn btn-default"><a href="{% url ‘password_change‘ %}?next={{ request.path }}">修改密碼</a>
</button>
{% else %}
編寫密碼修改成功頁面模板
密碼修改成功後,Django 會把用戶跳轉到密碼修改成功頁面,該頁面渲染的模板為 password_change_done.html,因此再添加一個密碼修改成功頁面的模板:
templates/registration/password_change_done.html
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>密碼修改成功</title>
<link rel="stylesheet" href="https://unpkg.com/mobi.css/dist/mobi.min.css">
</head>
<body>
<div class="flex-center">
<div class="container">
<div>
<h1 class="logo"><a href="{% url ‘index‘ %}">Django Auth Example</a></h1>
<p>密碼修改成功!</p>
</div>
</div>
</div>
</body>
</html>
OK,修改密碼的功能就完成了。流程為已登錄用戶點擊主頁的修改密碼按鈕跳轉到修改密碼頁面,修改密碼成功後跳轉到修改成功頁面。
總結
django用戶認證系統——修改密碼6