python - 类型错误 : get() takes 1 positional argument but 2 were given

标签 python django django-rest-framework

我正在构建和库存 Web 应用程序,但我遇到了这个错误。我正在尝试从 token 中获取用户名以显示自定义问候消息并显示用户以某人身份登录。

这是我的 Views.py,它以登录用户身份从 localStorage 获取 token :

class UserDetails(APIView):

    def post(self, request):
        serializer = UserAccountTokenSendSerializer(data=request.data)
        global token
        if serializer.is_valid():
            token = serializer.validated_data['token']
        return Response(serializer.data)

    def get(self):
        user_id =  Token.objects.get(key=token).user_id
        details = User.objects.get(id=user_id)
        serializer = UserDetails(details, many=False)
        return Response(serializer.data)
class UserDetails(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = (
            'username',
        )

这是我的 Urls.py:

urlpatterns = [
    path('get-user-token/', views.UserDetails.as_view()),
    path('get-user-details/', views.UserDetails.as_view()),
]

这是我得到的错误:

  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
TypeError: get() takes 1 positional argument but 2 were given
[15/Jun/2022 19:34:59] "GET /api/v1/get-user-details/ HTTP/1.1" 500 82239

最佳答案

.get(…) method [Django-doc]也接受一个 request 参数,即使你不使用它,所以:

class UserDetails(APIView):

    # …

    def get(self<strong>, request</strong>):
        # …
        pass

强烈建议不要将token设为全局变量。同一个网络服务器可以用于另一个未通过(正确)身份验证的用户。看看 Authentication section of the Django REST framework documentation有关如何验证和检查凭据的更多信息。


Note: In Django, class-based views (CBV) often have a …View suffix, to avoid a clash with the model names. Therefore you might consider renaming the view class to UserDetailsView, instead of UserDetails.

关于python - 类型错误 : get() takes 1 positional argument but 2 were given,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72637057/

相关文章:

python - 是否有使用 matplotlib 指定饼图中标题的位置?

python - 在 django 中对列表的每个元素调用方法的快速策略是什么

javascript - 想要从 componentDidMount 传递数据但它总是未定义

python - libmysqlclient.16.dylib 在哪里

django - 在 Django Rest Framework 中将数据作为数组发布

django-rest-framework - 如何将 ManyToMany 字段保存为值而不是 id

python - 尽管从带包的环境中加载了 jupyter notebook,但在 python 中找不到包

python - 使用 Seaborn 的多条形图

python - 使用healpy 和 projplot 进行 Aitoff 投影

django - 我如何告诉 grunt-usemin 忽略 Django 的静态模板标签?