【问题标题】:django rest : @api_view and @classmethod errordjango 休息:@api_view 和 @classmethod 错误
【发布时间】:2021-05-10 11:23:47
【问题描述】:

????我迫切需要@classmethod

我正在使用此代码:

from rest_framework.response import Response
class MyClass():
    @classmethod
    @api_view(['GET', 'POST', 'PUT', 'DELETE'])
    def CRUD(cls, request, id=0):
         #.....
         return Response({})

urlpatterns = [
    re_path(r'^user/(?:(?P<id>[1-9]+)/)?$', UserView.CRUD)
]

得到错误: The 'request' argument must be an instance of 'django.http.HttpRequest', not 'builtins.type'.

请帮忙;谢谢???????????????

【问题讨论】:

  • 您在何时/何地收到该错误?请发布完整的回溯。
  • @api_view 不适合基于类的视图
  • @deceze 对于所有请求,我有这个错误
  • @404pio 我该怎么办? ??????

标签: django django-rest-framework


【解决方案1】:

就像@404pio 所说的那样。您可以使用基于类的视图或基于函数的视图。你不能混合它们。

基于类的视图

from rest_framework.response import Response
from rest_framework.views import APIView

class MyClass(APIView):
   def get(self, request, id):
      # do stuff
      return Response(...)
   def post(self, request, id):
      # do stuff
      return Response(...)
   .
   .
   .
urlpatterns = [
    re_path(r'^user/(?:(?P<id>[1-9]+)/)?$', MyClass.as_view())
]

基于函数的视图

@api_view(['GET', 'POST'...])
def my_fbv(request, id):
   if request.method == 'GET':
       # do stuff

    elif request.method == 'POST':
       # do stuff
    .
    .
    .
urlpatterns = [
    re_path(r'^user/(?:(?P<id>[1-9]+)/)?$', my_module.my_fbv)
]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 2014-08-29
    • 1970-01-01
    • 2021-11-20
    相关资源
    最近更新 更多