且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法在Django中使用正确的用户名和密码进行身份验证?

更新时间:2022-05-06 22:20:51

首先更新您的用户模型,它没有密码。您的电子邮件字段不是charfield,我想它是EmailField,您的密码也不是charfield。请搜索正确的字段。密码必须为哈希...

First update your User model, it has no password. Your email field is not charfield I think it's EmailField and your password is not a charfield also. Please search for the correct field. Password must be hash...

backend.py

from django.conf import settings
from app_name.models import User

class AuthBackend:
    def authenticate(self, username=None, password=None):
        if '@' in username:
            kwargs = {'email': username}
        else:
            kwargs = {'username': username}
        try:
            user = User.objects.get(**kwargs)
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

通过模型创建 check_password 函数。这种检查的方式是,在将输入的密码与保存在数据库中的密码进行比较之前,必须将其加密。

Create "check_password" function via model. The way this check is, the input password must be hash before comparing it to the password that is being save in the database.

更新 settings.py

AUTHENTICATION_BACKENDS = (
    'app_name.backend.AuthBackend',
    'django.contrib.auth.backends.ModelBackend',
)