• Home
  • Django
  • Differences between decorator for functions and decorator for view methods

Differences between decorator for functions and decorator for view methods

linkaiyi
Follow

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
Object has 0 attachments

Was this article helpful?

This article is viewed 9 times!

Recent Viewed Articles

0 Comments

Leave a Comment

Support