Django帶有一個用戶認證系統。它處理用戶賬號、組、權限以及基於cookie的用戶會話。用戶可以直接是使用Django自帶的用戶表。
模型類位置from django.contrib.contrib.auth.models import User
from django.contrib.auth.models import user
user = User.objcets.create_user(username=’用戶名’, password=’密碼’, email=’郵箱’, …)
from django.contrib.auth.models import user
user = User.objcets.create_superuser(username=’用戶名’, password=’密碼’, email=’郵箱’, …)
創建完可在auth_user表中查看:
例:
from django.contrib.auth.models import User
try:
user = User.objcects.get(username=’用戶名’)
user.is_active = False # 記當前用戶無效
user.save()
print(“刪除失敗”)
except:
print(“刪除失敗”)
# 如果用戶名密碼校驗成功返回對於user對象,否則返回None
from django.contrib.auth import authenticate
user = authenticate(username=username, password=password)
from django.contrib.auth.models import User
try:
user = User.objects.get(username=’aaa’)
user.set_password(‘123’)
user.save()
return HttpResponse(‘密碼修改成功’)
except:
return HttpResponse(‘密碼修改失敗’)
from django.contrib.auth.models import login
def login_view(request):
user = authenticate(username=username, password=password)
login(request, user)
from django.contrib.auth.decorators import login_required
@login_required
def index_view(request):
# 該視圖必須為用戶登錄狀態下才可訪問
# 當前登錄用戶可通過rquest.user獲取
login_user = request.user
…
from django.contrib.auth.models import logout
def login_view(request):
logout(request)
方法一:通過建立新表,跟內建表做1對1
方法二:繼承內建的抽象user模型類
步驟:
注意:此操作要在第一次migrate前進行