如何在单个基于类的视图中修饰不同的http方法

时间:2012-12-19 10:54:59

标签: django django-class-based-views

例如,我有一个基于类的视图,它允许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怎么办?

1 个答案:

答案 0 :(得分:1)

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

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

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