天天看點

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
           
python測試開發django-74.auth認證之is_active

再次用 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']
# 不會檢測使用者的活躍狀态
AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.AllowAllUsersModelBackend']
           

is_active

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