gpt4 book ai didi

python - Django 自定义后端导致登录错误

转载 作者:太空宇宙 更新时间:2023-11-03 21:14:32 26 4
gpt4 key购买 nike

编写了自定义 django 后端,单击登录按钮后,它调用身份验证并失败并出现错误:

'dict' object has no attribute 'backend'

我将字符串推送到身份验证后端

AUTHENTICATION_BACKENDS = [
'app_auth.auth_backend.AuthBackend'
]

可能会出现什么问题?

堆栈跟踪:

Internal Server Error: /sign-in/
Traceback (most recent call last):
File "C:\django-proj\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\django-proj\env\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\django-proj\env\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\django-proj\app_auth\views.py", line 12, in sign_in
user = authenticate(request, username=username, password=password)
File "C:\django-proj\env\lib\site-packages\django\contrib\auth\__init__.py", line 73, in authenticate
user = backend.authenticate(request, **credentials)
File "C:\django-proj\app_auth\auth_backend.py", line 24, in authenticate
user.backend = 'app_auth.auth_backend.AuthBackend'
AttributeError: 'dict' object has no attribute 'backend'
[21/Feb/2019 22:53:20] "POST /sign-in/ HTTP/1.1" 500 78995
[21/Feb/2019 23:15:25] "GET /sign-in/ HTTP/1.1" 200 1274

验证功能

from django.conf import settings
from django.contrib.auth.hashers import check_password
from django.contrib.auth.models import User
from services.db.users import get_user, get_user_by_id

class AuthBackend():
def authenticate(self, request, username=None, password=None):
user = get_user(username=username)
return user

def get_user(self, user_id):
return get_user_by_id(id=user_id)

get_userget_user_by_id 返回 stub 数据

user = {
'name': 'user-name',
'backend': 'app_auth.auth_backend.AuthBackend'
}


def get_user(username):
return user


def get_user_by_id(id):
return user

最佳答案

该错误表明您正在验证的第 24 行中设置user.backend = 'app_auth.auth_backend.AuthBackend',并且该字典没有该属性。

您访问该字段的方式不正确。如果 user 是一个字典,并且您想要设置名为 backend 的属性的值,那么第 24 行应该是:

user['backend'] = 'app_auth.auth_backend.AuthBackend'

关于python - Django 自定义后端导致登录错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54815594/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com