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 就会生效了!

posted @ 2020-06-25 16:43  上海-悠悠  阅读(1468)  评论(1编辑  收藏  举报