使用User authentication and permissions

這篇文章是筆記,詳細內容參見Mozilla的教程
完整的教材:Django Tutorial Part 8: User authentication and permissionshtml

1, 確認settings.py的INSTALLED_APPS和MIDDLEWARE裏面包含下面紅色的組件:django

INSTALLED_APPS = [
    ...
    'django.contrib.auth',  
    'django.contrib.contenttypes',
    ....
MIDDLEWARE = [
    ...
    'django.contrib.sessions.middleware.SessionMiddleware',
    ...
    'django.contrib.auth.middleware.AuthenticationMiddleware',  
    ....

2, 使用admin頁面建立user、group。session

3, 在主項目的urls.py文件內添加下面的內容:app

urlpatterns += [
    url('^accounts/', include('django.contrib.auth.urls')),
]

4, 上面url將爲咱們自動建立下列的url即相對應的form、views。dom

^accounts/ ^login/$ [name='login']
^accounts/ ^logout/$ [name='logout']
^accounts/ ^password_change/$ [name='password_change']
^accounts/ ^password_change/done/$ [name='password_change_done']
^accounts/ ^password_reset/$ [name='password_reset']
^accounts/ ^password_reset/done/$ [name='password_reset_done']
^accounts/ ^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$ [name='password_reset_confirm']
^accounts/ ^reset/done/$ [name='password_reset_complete']

5, 在app文件夾內的templates目錄下面建立registration目錄,並在settings.py 文件夾內添加:ide

TEMPLATES = [
    {
        ...
        'DIRS': ['./templates',],
        'APP_DIRS': True,
        ...

6, 由此咱們能夠在registration目錄下面建立下面的templates:
login.html – 當用戶登錄網站時展現的頁面
logged_out.html – 當用戶登出網站後展現的頁面
password_change_done.html – 當用戶成功更改其帳戶密碼後展現的頁面
password_change_form.html – 用於處理用戶更改其帳戶密碼時展現的頁面
password_reset_complete.html – 當用戶成功重置其帳戶密碼後展現的頁面
password_reset_confirm.html – 用於處理用戶輸入其新帳戶密碼時的頁面
password_reset_done.html – 用於提示帳戶,重置密碼鏈接已經發送到他或她的郵箱時的頁面
password_reset_email.html – 郵件模板,內含重置帳戶密碼連接
password_reset_form.html – 用於提示用戶輸入註冊時用的郵箱地址以得到重置帳戶密碼的連接
而若是要用URL tag指向這些templates,須要參考第四點中所列出的url。如指向password_reset_form.html能夠使用下面的方式:網站

<p><a href="{% url 'password_reset' %}">忘記密碼?</a></p>

7, 上面的這些templates都要咱們本身編寫。下面是編寫password_reset_email.html時要添加的內容,其餘templates不舉例:ui

{{ user.get_username }}, 你好!
你能夠點擊以下連接以重置你的密碼:
{{ protocol }}://{{ domain }}{% url "password_reset_confirm" uidb64=uid token=token %}
相關文章
相關標籤/搜索