django - 在测试期间,当使用正确的用户输入进行测试时,我得到“无效的凭据”
问题描述
我只使用电话号码作为登录的唯一字段。即使提供了正确的用户输入,身份验证似乎也无法正常工作。
配置 AUTH 后端时出错:
File "C:\Users\UBITEK\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf\__init__.py", line 161, in __init__
raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
@csrf_exempt
@api_view(["POST"])
@permission_classes((AllowAny,))
def logins(request):
phone_number = request.data.get("phone_number")
if phone_number is None:
return Response({'error': 'Please provide your phone number'},
status=HTTP_400_BAD_REQUEST)
user = authenticate(phone_number=phone_number)
if not user:
return Response({'error': 'Invalid Credentials'},
status=HTTP_404_NOT_FOUND)
token, _ = Token.objects.get_or_create(user=user)
return Response({'token': token.key},
status=HTTP_200_OK)
后端.py
from django.contrib.auth.backends import ModelBackend
from .models import User
class LoginBackend(ModelBackend):
def authenticate(self, request, **kwargs):
phone_number= kwargs['phone_number']
user = User.objects.get(phone_number=phone_number)
if user:
return user
else:
return None
设置.py
from .backends import LoginBackend
from django.contrib.auth.backends import ModelBackend
AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend',
'findr.backends.LoginBackend']
解决方案
关于对您问题的评论,我建议您编写自己的django
身份验证后端:
https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#writing-an-authentication-backend
你必须告诉 Django 如何对某人进行身份验证:
- 和?
username
_password
- 和?
phone_number
_password
这必须是明确的(并且不要忘记将此新后端添加到您的settings.py
文件中!)。
推荐阅读
- excel - 宏在运行时错误462之前只运行一次excel vba:远程服务器不存在或不可用
- assembly - 远调用将错误的 IP 推入堆栈
- javascript - 从异步函数中获取数据
- android - 我如何使递减值停在零
- javascript - 验证反应式表单元素的总和
- makefile - 未生成 Makefile 可执行文件
- appium - Appium - PageFactory initElements 不工作
- c - 如何将结构指针数组中的结构直接复制到c中的另一个结构
- php - 获取 Woocommerce 自定义电子邮件内容的自定义电子邮件占位符值
- dht - 在 holochain-rust 中,获取并显示所有用户列表的最佳方式是什么?