Django自定义用户模型下登录认证authenticate始终返回NULL问题求助
Django自定义认证后端不生效问题解决方案
核心问题1:自定义authenticate方法缺少request参数
Django调用认证后端的authenticate方法时,会默认将当前请求对象request作为第一个参数传入,你现有的方法定义没有接收该参数,导致参数匹配失败,方法无法被正常触发,自然返回None。
修改backend.py中的方法定义即可:
# 新增request参数,即使不用也要保留占位 def authenticate(self, request, username, password): if username is not None and password is not None: user = AdminUsers.objects.get(username=username) hashed_password = user.password is_check = bcrypt.checkpw(password.encode('utf8'),hashed_password.encode('utf8')) if is_check: return user return None
核心问题2:settings中AUTHENTICATION_BACKENDS路径配置错误
请确认你的配置路径完全匹配认证类的实际位置,假设你的应用名为myapp,认证类放在myapp/backend.py文件中,配置必须写为:
AUTHENTICATION_BACKENDS = [ 'myapp.backend.CustomAuthentication', ]
注意拼写不要出错:不要把backend写成backends,不要遗漏应用名前缀。
其他问题修正
views.py中的判断逻辑错误
authenticate方法返回的是用户对象而非布尔值,你写的if is_check==True:永远不会成立,修改为判断返回值不为空即可:
is_check = authenticate(username=username,password=password) if is_check is not None: # 登录成功逻辑
get_user方法异常捕获缺失
现有get_user方法查询不到用户时会抛出DoesNotExist异常而非返回None,补充异常捕获:
def get_user(self, id): try: return AdminUsers.objects.get(id=id) except AdminUsers.DoesNotExist: return None
自定义用户模型缺少必要字段
Django默认认证逻辑会校验用户的is_active状态,建议在AdminUsers模型中补充该字段:
class AdminUsers(AbstractBaseUser): # 原有字段保留 is_active = models.BooleanField(default=True)
内容的提问来源于stack exchange,提问作者anonymous
相关产品推荐
相关产品推荐

