What's the difference between the two methods of decorating class-based views?

混江龙づ霸主 提交于 2019-12-05 10:32:21

Imagine you have the following class based view:

class PostListView(ListView):
     model = Post

ProtectedPostListView = login_required(PostListView.as_view())

and your urls.py:

url(r'posts$', ProtectedPostListView)

If you use this approach then you lose the ability to subclass ProtectedPostListView e.g

class MyNewView(ProtectedPostListView):
    #IMPOSSIBLE

and this is because the .as_view() returns a function and after applying the login_required decorator you are left with a function, so subclassing is not possible.

On the other hand if you go with the second approach i.e use the method decorator the subclassing is possible. e.g

class PostListView(ListView):
     model = Post

     @method_decorator(login_required)
     def dispatch(self, *args, **kwargs):
         return super(PostListView, self).dispatch(*args, **kwargs)

class MyNewView(PostListView):
     #LEGAL
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!