温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2021-08-26 17:53:23 来源:亿速云 阅读:150 作者:chen 栏目:大数据

本篇内容介绍了“django2.2.6中check_password验证失败的解决办法”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

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.WeiboOAuth3',
    # 'social_core.backends.qq.QQOAuth3',
    # 'social_core.backends.weixin.WeixinOAuth3',
    # 'social_core.backends.github.GithubOAuth3',
    # 'social_core.backends.gitlab.GitLabOAuth3',
    # '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()

“django2.2.6中check_password验证失败的解决办法”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI