Django認(rèn)證系統(tǒng)user對(duì)象實(shí)現(xiàn)過程解析
User對(duì)象
User對(duì)象是認(rèn)證系統(tǒng)的核心。它們通常表示與你的站點(diǎn)進(jìn)行交互的用戶,并用于啟用限制訪問、注冊(cè)用戶信息和關(guān)聯(lián)內(nèi)容給創(chuàng)建者等。在Django的認(rèn)證框架中只存在一種類型的用戶,因此諸如’superusers’或管理員’staff’用戶只是具有特殊屬性集的user對(duì)象,而不是不同類型的user對(duì)象。
創(chuàng)建users
創(chuàng)建users最直接的方法是使用create_user()輔助函數(shù):
>>> from django.contrib.auth.models import User>>> user = User.objects.create_user(’john’, ’[email protected]’, ’johnpassword’)
from django.contrib.auth.models import Userdef create_user(request): #auth_user # user = User.objects.create_user(’john’, ’[email protected]’, ’johnpassword’) #superuser python manage.py createsuperuser --username=joe [email protected] u = User.objects.get(username=’john’) u.set_password(’new password’) u.save() return HttpResponse('success-----%s'%u)
創(chuàng)建成功后見數(shù)據(jù)庫auth_user表
創(chuàng)建superusers
使用createsuperuser命令創(chuàng)建superusers:
$ python manage.py createsuperuser --username=joe [email protected]
或者
$ python manage.py createsuperuser
接下來依次輸入用戶密碼即可成功后見auth_user表
修改密碼
>>> from django.contrib.auth.models import User>>> u = User.objects.get(username=’john’)>>> u.set_password(’new password’)>>> u.save()
成功后見auth_user表,密碼已經(jīng)改變
認(rèn)證Users
authenticate(**credentials)[source]
認(rèn)證一個(gè)給定用戶名和密碼,請(qǐng)使用authenticate()。它以關(guān)鍵字參數(shù)形式接收憑證,對(duì)于默認(rèn)的配置它是username和password,如果密碼對(duì)于給定的用戶名有效它將返回一個(gè)User對(duì)象。如果密碼無效,authenticate()返回None。例子:
from django.contrib.auth import authenticateuser = authenticate(username=’john’, password=’secret’)if user is not None: # the password verified for the user if user.is_active: print() else: print()else: # the authentication system was unable to verify the username and password print()
def auth(request): user = authenticate(username=’john’, password=’new password’)#john # user = authenticate(username=’john’, password=’johnpassword’)#None print(user) if user is not None: # the password verified for the user if user.is_active: print('驗(yàn)證成功,已激活') else: print('驗(yàn)證成功,未激活') else: # the authentication system was unable to verify the username and password print('沒有此用戶') return HttpResponse(user)
john
驗(yàn)證成功,已激活
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 使用css實(shí)現(xiàn)全兼容tooltip提示框2. SpringBoot快速集成jxls-poi(自定義模板,支持本地文件導(dǎo)出,在線文件導(dǎo)出)3. 使用ProcessBuilder調(diào)用外部命令,并返回大量結(jié)果4. 通過工廠模式返回Spring Bean方法解析5. JSP實(shí)現(xiàn)客戶信息管理系統(tǒng)6. 關(guān)于Mysql-connector-java驅(qū)動(dòng)版本問題總結(jié)7. python中HTMLParser模塊知識(shí)點(diǎn)總結(jié)8. CSS自定義滾動(dòng)條樣式案例詳解9. python 批量下載bilibili視頻的gui程序10. python:刪除離群值操作(每一行為一類數(shù)據(jù))
