python3.6, django 2.2.6 AUTHENTICATION_BACKENDS 里添加自定义认证 CustomBackend(邮箱、手机号等),
用 python manage.py createsuperuser 创建的超级管理员登录时密码一直验证失败(False)
# .\apps\users\backends\other.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: yinzhuoqun
@site: http://zhuoqun.info/
@email: yin@zhuoqun.info
@time: 2019/10/16 18:06
"""
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from django.contrib.auth.hashers import check_password
from apps.users.models import UserProfile
User = get_user_model()
# 用户名之外的唯一值字段也能用来登录,setting 里要有对应的配置 AUTHENTICATION_BACKENDS
class CustomBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
try:
# 邮箱、用户名、手机号码 登录
user = UserProfile.objects.get(Q(username=username) | Q(email=username) | Q(phone=username))
# user_check_password = user.check_password(password)
user_check_password = check_password(password, user.password)
if user_check_password:
return user
except User.DoesNotExist:
return None
# settings.py
AUTH_USER_MODEL = 'users.UserProfile' # 重载系统的用户,让 UserProfile 生效
# AUTH 方法(支持邮箱、手机号等登录), 验证从上到下
AUTHENTICATION_BACKENDS = (
'apps.users.backends.other.CustomBackend',
# 'social_core.backends.weibo.WeiboOAuth2',
# 'social_core.backends.qq.QQOAuth2',
# 'social_core.backends.weixin.WeixinOAuth2',
# 'social_core.backends.github.GithubOAuth2',
# 'social_core.backends.gitlab.GitLabOAuth2',
# 'django.contrib.auth.backends.ModelBackend',
)
删库重建无数次都不行,突然想到用 shell 重新设置密码一次,果然就登录上去了。(这段代码也是修改超级管理密码的过程)
(tracbug) .\tracbug>python manage.py shell
Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth import get_user_model
>>> User = get_user_model()
>>> user = User.objects.get(username="yinzhuoqun")
>>> user
<UserProfile: Yinzhuoqun>
>>> user.username
'yinzhuoqun'
>>> user.set_password("xxxxxxxx")
>>> user.save()