python測試開發django-74.auth認證之is_active


前言

在 django 的 User 表里面有個 is_active 字段可以判斷用戶是否是激活狀態。
使用 authenticate 校驗登錄的時候 is_active 是不生效的。

authenticate 登錄

create_user 創建新用戶的時候 is_active 默認是1,也就是True

D:\code202003\MyDjango>python manage.py shell
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth.models import User
>>> from django.contrib.auth import authenticate
>>> user=User.objects.create_user(username="test",password="test")
>>> user
<User: test>
>>> user.is_active
True

當修改用戶的 is_active 狀態,改成 False 時

>>> a=authenticate(username="test",password="test")
>>> a.is_active=False
>>> a.save()
>>> a.is_active
False

再次用 authenticate 校驗登錄狀態

>>> from django.contrib.auth.models import User
>>> from django.contrib.auth import authenticate
>>> a=authenticate(username="test",password="test")
>>> a

此時賬號密碼驗證不通過,這樣就跟輸錯密碼是一樣的了,無法知道用戶is_active狀態

不檢測用戶的活躍狀態

django的默認配置會檢測用戶是否是活躍狀態(is_active),不活躍則返回None(默認配置)

AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend']

需在 settings.py 文件里加上下面的配置

# 不會檢測用戶的活躍狀態
AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.AllowAllUsersModelBackend']

is_active

加上配置后,重新打開shell

D:\code202003\MyDjango>python manage.py shell
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth.models import User
>>> from django.contrib.auth import authenticate
>>> a=authenticate(username="test",password="test")
>>> a
<User: test>
>>> a.is_active
False

這樣 is_active 就會生效了!


免責聲明!

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



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