记录一个关于django2.0与django1.x的区别

​ 在django2.0之后的版本,django内置的user验证登录的时候使用authenticate(username=username, password=password)来验证登录,会出现authenticate(request, username=username, password=password)

的返回值一直为None

​ 为了避免这一情况,需要在settings中加入配置

1
2
3
AUTHENTICATION_BACKENDS = [  
"django.contrib.auth.backends.AllowAllUsersModelBackend"
]

​ 这是因为authenticate函数增加了对is_active的验证

1
2
3
4
5
6
7
8
9
10
11
12
def (self, request, username=None, password=None, **kwargs):
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
try:
user = UserModel._default_manager.get_by_natural_key(username)
except UserModel.DoesNotExist:

# difference between an existing and a nonexistent user (#20760).
UserModel().set_password(password)
else:
if user.check_password(password) and self.user_can_authenticate(user): # 在这里
return user
1
2
3
4
5
6
7
def user_can_authenticate(self, user):
"""
Reject users with is_active=False. Custom user models that don't have
that attribute are allowed.
"""
is_active = getattr(user, 'is_active', None)
return is_active or is_active is None

​ 而AllowAllUsersModelBackend重写了user_can_authenticate方法

1
2
3
class AllowAllUsersModelBackend(ModelBackend):
def user_can_authenticate(self, user):
return True