Django實戰(21):使用內置的Amin管理用戶


到目前為止,我們開發的所有功能都是匿名訪問的,這顯然不夠安全。通常我們會要求注冊的用戶通過用戶名和密碼登錄,只有登錄后的用戶才可以管理產品。套用專業的說法就是:第一步是認證,驗證用戶是否是他所宣稱的那個人;第二步是授權,驗證用戶是否擁有執行某種操作的權限。

Django已經提供了一個django.contrib.auth應用來處理登錄、登出和權限驗證,同時還提供了django.contrib.admin應用可以進行用戶管理(admin應用還有很多其他的功能)。所以我們只需要將這些app插入到我們的站點,就可以實現登錄和用戶管理的大部分功能。

本節先介紹如何進行用戶管理。

我們前面已經介紹過在Django中使用session,方法是打開'django.contrib.sessions'應用。該app是django.contrib.auth的基礎,同時從該節我們也知道了如何在Django中加入應用,所以讓我們快速行動起來:

首先在depot/settings.py中,打開MIDDLEWARE_CLASSES中的CommonMiddleware、SessionMiddleware和AuthenticationMiddleware:

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

 

同樣在在depot/settings.py中,打開INSTALLED_APPS中的auth、contenttypes、sessions和admin應用:

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    #'django.contrib.sites',
    #'django.contrib.messages',
    #'django.contrib.staticfiles',
    
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'depot.depotapp',
    'django-groundwork',
    'djangorestframework',
)

 

在depot/urls.py中,在頭部增加:

from django.contrib import admin
admin.autodiscover()

然后增加admin的urlpattern:

(r'^admin/', include(admin.site.urls)),

最后運行$python manage.py syncdb,以創建需要的數據庫表。在此過程中會詢問你創建一個管理員賬號。如果沒有創建,也可以手工運行$python manage.py createsuperuser再次創建:

$ python manage.py createsuperuser
Username (Leave blank to use 'holbrook'):
E-mail address: a@b.com
Password:
Password (again):
Superuser created successfully.
holbrook-wongdemacbook-pro:depot holbrook$ python manage.py syncdb
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table auth_message

You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (Leave blank to use 'holbrook'):
E-mail address: wanghaikuo@gmail.com
Password:
Password (again):
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
No fixtures found.

此時訪問http://localhost:8000/admin/,用剛才創建的用戶名和密碼登錄,就可以看到Django內置的管理界面,其中就有用戶管理的功能。如果你對英文界面很不爽,只需要在depot/settings.py中設置LANGUAGE_CODE = 'zh-CN',就可以看到中文的管理界面了。

你可以創建幾個用戶,在下一節中會用到。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM