Web框架之Django_10 重要组件(Auth模块)
閱讀目錄
-
一、auth模塊介紹
-
二、auth模塊常用方法
create_superuser()
create_user()
authenticate()
login(HttpRequest, user)
logout(request)
is_authenticated()
login_requierd()
check_password(password)
set_password(password)
User對象的屬性 -
三、擴展默認的auth_user表
一、auth模塊介紹
Auth模塊是Django自帶的用戶認證模塊:
我們在開發(fā)一個網(wǎng)站的時候,無可避免的需要設計實現(xiàn)網(wǎng)站的用戶系統(tǒng)。此時我們需要實現(xiàn)包括用戶注冊、用戶登錄、用戶認證、注銷、修改密碼等功能,這還真是個麻煩的事情呢。
Django作為一個完美主義者的終極框架,當然也會想到用戶的這些痛點。它內(nèi)置了強大的用戶認證系統(tǒng)–auth,它默認使用 auth_user 表來存
二、auth模塊常用方法
from django.contrib import authcreate_superuser()
auth 提供的一個創(chuàng)建新的超級用戶的方法,需要提供必要參數(shù)(username、password)等。
用法:
from django.contrib.auth.models import Useruser = User.objects.create_superuser(username='用戶名',password='密碼',email='郵箱',...)還可以在菜單欄tool中Run manage.py Task下進行命令行創(chuàng)建超級用戶:createsuperuser然后根據(jù)提示創(chuàng)建即可
create_user()
auth 提供的一個創(chuàng)建新用戶的方法,需要提供必要參數(shù)(username、password)等,該方法和創(chuàng)建超級用戶一樣,只不過用戶權限會有差別
用法:
from django.contrib.auth.models import Useruser = User.objects.create_user(username='用戶名',password='密碼',email='郵箱',...)tip:Run manage.py Task下無法創(chuàng)建普通用戶
authenticate()
提供了用戶認證功能,即驗證用戶名以及密碼是否正確,一般需要username 、password兩個關鍵字參數(shù)。
如果認證成功(用戶名和密碼正確有效),便會返回一個 User 對象。
authenticate()會在該 User 對象上設置一個屬性來標識后端已經(jīng)認證了該用戶,且該信息在后續(xù)的登錄過程中是需要的。
用法:
user = authenticate(username='usernamer',password='password') # 用戶名和密碼都要傳才行login(HttpRequest, user)
該函數(shù)接受一個HttpResponse對象,以及一個經(jīng)過認證的User對象
該函數(shù)實現(xiàn)一個用戶登錄的功能,本質上會在后端為該用戶生成相關的session數(shù)據(jù)
用法:
-------------------------------------------------------------------- 注:如果你對python感興趣,我這有個學習Python基地,里面有很多學習資料,感興趣的+Q群:895817687 --------------------------------------------------------------------urls.py url(r'^login/', views.my_login),views.py from django.contrib.auth import authenticate,logindef my_login(request):if request.method == 'POST':# 獲取前端賬號密碼username = request.POST['username']password = request.POST['password']# 用戶認證user = authenticate(username=username, password=password)# 用戶認證成功if user:# 實現(xiàn)用戶登錄功能,為該用戶創(chuàng)建生成session數(shù)據(jù)login(request, user) # 這里只要執(zhí)行了login(request, user),在后端任何地方都可以通過request.user拿到當前登錄的用戶對象return render(request, 'index.html')# 認證不成功,說明用戶名密碼錯誤else:return HttpResponse('用戶名或密碼錯誤,登錄失敗')return render(request, 'login.html')login.html <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>登錄</title> </head> <body> <form action="" method="post">{% csrf_token %}<p>用戶名:<input type="text" name="username"></p><p>密碼:<input type="password" name="password"></p><p><input type="submit"></p> </form> </body> </html>index.html <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>主頁面</title> </head> <body> <h1>我是登錄后才能看到的頁面</h1> </body> </html>logout(request)
該函數(shù)接受一個HttpRequest對象,無返回值。
當調用該函數(shù)時,當前請求的session信息會全部清除。該用戶即使沒有登錄,使用該函數(shù)也不會報錯。
用法:
from django.contrib.auth import logout def my_logout(request):logout(request)return redirect('/home/')def my_home(request):return render(request, 'home.html')is_authenticated()
用來判斷當前請求是否通過了認證。返回一個布爾值
用法:
def my_view(request):if not request.user.is_authenticated():return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))login_requierd()
auth 給我們提供的一個裝飾器工具,用來快捷的給某個視圖添加登錄校驗。
用法:
from django.contrib.auth.decorators import login_required@login_requireddef my_view(request):...若用戶沒有登錄,則會跳轉到django默認的 登錄URL '/accounts/login/ ’ 并傳遞當前訪問url的絕對路徑 (登陸成功后,會重定向到該路徑)。
如果需要自定義登錄的URL,則需要在settings.py文件中通過LOGIN_URL進行修改。
示例:
# 局部配置# @login_required(login_url='/auth_login/') # 全局配置 # auth自動跳轉LOGIN_URL = '/auth_login/' # settings.py配置實例:
# 導入用戶認證模塊和login函數(shù) from django.contrib.auth import authenticate,logindef my_login(request):if request.method == 'POST':# 獲取前端賬號密碼username = request.POST['username']password = request.POST['password']next_url = request.GET.get('next') # 獲取到跳轉過來的原頁面的url# 用戶認證user = authenticate(username=username, password=password)# 用戶認證成功if user:# 實現(xiàn)用戶登錄功能,為該用戶創(chuàng)建生成session數(shù)據(jù)login(request, user)return redirect(next_url) # 登錄成功自動跳轉到原來的頁面# 認證不成功,說明用戶名密碼錯誤else:return HttpResponse('用戶名或密碼錯誤,登錄失敗')return render(request, 'login.html')from django.contrib.auth.decorators import login_required # Django登錄驗證裝飾器在跳轉到登陸頁面時候會自動在頁面末尾拼接一個?next=當前url @login_required def my_home(request):return render(request, 'home.html')check_password(password)
auth 提供的一個檢查密碼是否正確的方法,需要提供當前請求用戶的密碼。
密碼正確返回True,否則返回False。
用法:
ok = user.check_password('密碼')set_password(password)
auth 提供的一個修改密碼的方法,接收 要設置的新密碼 作為參數(shù)。
注意:設置完一定要調用用戶對象的save方法!!!
用法:
user.set_password(password='')user.save(修改密碼示例:
修改密碼
User對象的屬性
User對象屬性:username, password
is_staff : 用戶是否擁有網(wǎng)站的管理權限.
is_active : 是否允許用戶登錄, 設置為 False,可以在不刪除用戶的前提下禁止用戶登錄。
三、擴展默認的auth_user表
這內(nèi)置的認證系統(tǒng)這么好用,但是auth_user表字段都是固定的那幾個,我在項目中沒法拿來直接使用啊!
比如,我想要加一個存儲用戶手機號的字段,怎么辦?
聰明的你可能會想到新建另外一張表然后通過一對一和內(nèi)置的auth_user表關聯(lián),這樣雖然能滿足要求但是有沒有更好的實現(xiàn)方式呢?
答案是當然有了。
我們可以通過繼承內(nèi)置的 AbstractUser 類,來定義一個自己的Model類。
這樣既能根據(jù)項目需求靈活的設計用戶表,又能使用Django強大的認證系統(tǒng)了。
# app01下models.py文件中from django.db import models from django.contrib.auth.models import User,AbstractUser # 讓拓展的auth_user表:userinfo繼承AbstractUser,這樣userinfo表擁有了原來auth_user表的所有屬性(字段) class Userinfo(AbstractUser):phone = models.CharField(max_length=32)avatar = models.CharField(max_length=32)需要注意:
按上面的方式擴展了內(nèi)置的auth_user表之后,一定要在settings.py中告訴Django,我現(xiàn)在使用我新定義的UserInfo表來做用戶認證。寫法如下:
#引用Django自帶的User表,繼承使用時需要設置AUTH_USER_MODEL = "app名.UserInfo"再次注意:
一旦我們指定了新的認證系統(tǒng)所使用的表,我們就需要重新在數(shù)據(jù)庫中創(chuàng)建該表,而不能繼續(xù)使用原來默認的auth_user表了。
示例:
這里需要注意:如果在設置完做數(shù)據(jù)庫遷移命令migrate的時候報錯:
django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency users.0001_initial on database ‘default’
解決方法是:刪除數(shù)據(jù)庫中 除了auth_user的其他表,然后重新來一次
總結
以上是生活随笔為你收集整理的Web框架之Django_10 重要组件(Auth模块)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Web框架之Django_08 重要组件
- 下一篇: Django框架深入了解_01(Djan