繁体   English   中英

使用令牌 django-rest-framework 登录

[英]Login with token django-rest-framework

我正在使用 django rest 框架开展项目。 我创建了注册视图没有任何问题,但是在登录视图中我有一个问题:当我尝试登录时,响应返回“无效凭据”

视图.py:

class ObtainAuthTokenView(APIView):
    authentication_classes = []
    permission_classes = []

    def post(self, request):
        context = {}

        email = request.POST.get('username')
        password = request.POST.get('password')
        account = authenticate(email=email, password=password)
        if account:
            try:
                token = Token.objects.get(user=account)
            except Token.DoesNotExist:
                token = Token.objects.create(user=account)
            context['response'] = 'Successfully authenticated.'
            context['pk'] = account.pk
            context['email'] = email.lower()
            context['token'] = token.key
        else:
            context['response'] = 'Error'
            context['error_message'] = 'Invalid credentials'

        return Response(context)

网址.py

urlpatterns = [
    path('login', ObtainAuthTokenView.as_view(), name="login"),
]

我使用此数据发布:

{"username":"x@example.com","password":"123456"}

在我发布此数据后,响应返回“无效凭据”。 我发现收到请求后的 email 和密码可能是相等的。

那我为什么要面对这个问题?

错误是因为我使用了错误的标识符。

我写了这个:

request.POST.get()

而不是这个:

request.data.get()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM