前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >django2.2.6 check_password 验证失败解决办法

django2.2.6 check_password 验证失败解决办法

作者头像
KEVINGUO_CN
发布2020-03-17 14:08:06
9060
发布2020-03-17 14:08:06
举报
文章被收录于专栏:全栈全栈全栈全栈

python3.6, django 2.2.6 AUTHENTICATION_BACKENDS 里添加自定义认证 CustomBackend(邮箱、手机号等),

用 python manage.py createsuperuser 创建的超级管理员登录时密码一直验证失败(False)

# .\apps\users\backends\other.py

代码语言:javascript
复制
#!/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

Copy

# settings.py

代码语言:javascript
复制
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',
)

Copy

删库重建无数次都不行,突然想到用 shell 重新设置密码一次,果然就登录上去了。

代码语言:javascript
复制
(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() 
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-11-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档