首页 > 解决方案 > 为什么“本机”视图和 ModelViewSet 之间的请求对象不一样?

问题描述

我正在使用 Django Rest Framework (DRF) 构建 API,并通过社交应用启用身份验证/注册。

为了通过他们的社交账户对用户进行身份验证,我使用了 Django rest-framework Social Oauth2,它就像一个魅力。为了确保我的用户已登录,我在应用程序的 views.py 中创建了一个非常简单的视图:

def index(request):
    return HttpResponse("is_anonymous: %s" % request.user.is_anonymous)

浏览器中的结果如下(表示用户已登录):

is_anonymous: 假

现在,当我使用 DRF 构建 API 时,我可能需要在我的一个视图集中检索当前用户的一些数据(来自 request.user),但在以下代码中,结果不是我所期望的:

class HelloViewSet(viewsets.ModelViewSet):
    queryset = Hello.objects.all()
    serializer_class = HelloSerializer

    # This is just a random ViewSet, what is
    # important is the custom view below

    @action(detail=False)
    def test(self, request):
        return Response(request.user.is_anonymous)

这里的结果显示用户没有登录:

真的

所以第一个视图显示 request.user.is_anonymous = False,第二个视图显示 request.user.is_anonymous = True。两个视图都在同一个应用程序的同一个文件views.py 中。

我在这里想念什么?我们不应该在 API REST 中获取用户实例吗?

标签: djangodjango-rest-framework

解决方案


As neverwalkaloner mentioned in the in the comments, the problem was that I didn't pass any access_token in the header via Authorization: Bearer <token>, so of course the server wasn't able to identify the "logged" user that was making the request. Using curl (or Postman) I could add this token for checking purpose and it worked.


推荐阅读