【问题标题】:Method Decorator in class based view is not working基于类的视图中的方法装饰器不起作用
【发布时间】:2016-02-06 09:55:29
【问题描述】:

我仅在使用方法装饰器的 POST 方法上使用基于类的视图和应用权限类。直到昨天它还在工作,但突然停止了。我找不到问题。

class OfferCreateListView(ListCreateAPIView):
    serializer_class = OfferSerializer
    queryset = Offers.objects.filter(user__isnull=True)

    @method_decorator(permission_classes((IsAuthenticated,)))
    @method_decorator(authentication_classes((BasicAuthentication, SessionAuthentication, TokenAuthentication,)))
    def post(self, request, *args, **kwargs):
        return super(OfferCreateListView, self).post(request, *args, **kwargs)

我在哪里做错了。有什么设置可以让它工作吗??

【问题讨论】:

  • “突然间停止了”不是很具有描述性...会发生什么?错误?结果无效?
  • @Sayse 不知道...但我可以在未经身份验证的情况下发帖..

标签: python django django-rest-framework decorator django-class-based-views


【解决方案1】:

permission_classesauthentication_classes 装饰器是为基于函数的视图设计的。我没有一直遵循其余的框架代码,但我很惊讶它直到昨天才起作用——我不打算将装饰器与基于类的视图一起使用。

相反,设置类的属性。由于您只想将权限类应用于发布请求,因此听起来您想要IsAuthenticatedOrReadOnly

class OfferCreateListView(ListCreateAPIView):
    permission_classes = (IsAuthenticatedOrReadOnly,)
    authentication_classes = (BasicAuthentication, SessionAuthentication, TokenAuthentication,)
    serializer_class = OfferSerializer
    queryset = Offers.objects.filter(user__isnull=True)

【讨论】:

  • 我想申请 POST 方法而不是 GET 方法...这就是我使用方法装饰器的原因
  • 抱歉,我第一次阅读您的问题时没有发现这一点。在这种情况下,我认为您需要 IsAuthenticatedOrReadOnly 权限类。
猜你喜欢
  • 2014-10-20
  • 2017-03-08
  • 2023-03-14
  • 2023-02-07
  • 2020-07-07
  • 1970-01-01
  • 1970-01-01
  • 2015-06-23
相关资源
最近更新 更多