【问题标题】:How to decorate different http method in a single class based view如何在基于单个类的视图中装饰不同的 http 方法
【发布时间】:2012-12-19 10:54:58
【问题描述】:

例如,我有一个基于类的视图,它允许 GET 和 POST 方法,如下所示,

class ViewOne(View):
    def post(self, request, *args, **kwargs):
        ...
    def get(self, request, *args, **kwargs):
        ...
    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(ViewOne, self).dispatch(*args, **kwargs)

现在,GET 和 POST 都是 login_required。但是如果我只希望 POST 是 login_required 呢?

【问题讨论】:

    标签: django django-class-based-views


    【解决方案1】:

    嗯...它不起作用吗?

    class ViewOne(View):
        @method_decorator(login_required)
        def post(self, request, *args, **kwargs):
            ...
        def get(self, request, *args, **kwargs):
            ...    
    

    【讨论】:

      【解决方案2】:

      为什么不创建两个类,也使用django-braces ;)

      class ViewOne(View):
          def get(self, request, *args, **kwargs):
          ...
      
      class ViewTwo(LoginRequiredMixin, ViewOne):
          def post(self, request, *args, **kwargs):
          ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-20
        • 2017-03-08
        • 2015-06-23
        • 2015-03-25
        • 1970-01-01
        相关资源
        最近更新 更多