What is the difference between the two class-based presentation methods?

I am writing a view that inherits from ListView and am trying to restrict the viewing to registered users.

https://docs.djangoproject.com/en/dev/topics/class-based-views/#decorating-in-urlconf says that decoration using login_required in URLconf "applies a decorator for each instance. If you want each instance view that you want to decorate, you need to use a different approach, "- this approach is to decorate the sending method in the view code.

I thought I knew the difference between a class and an instance, but this phrase means nothing to me. Can anyone clarify? Besides having a decorator in URLconf, as opposed to defining your class, what are the differences between the two approaches?

The link above seems to answer the question: "Since class-based views are not functions, their layout works differently depending on whether you use as_view or create a subclass."

In fact?? It seems I can use the URLconf approach with my subclass of ListView.

+5
source share
1 answer

Imagine you have the following view based on a class:

class PostListView(ListView):
     model = Post

ProtectedPostListView = login_required(PostListView.as_view())

and your urls.py:

url(r'posts$', ProtectedPostListView)

If you use this approach, you lose the ability to subclass ProtectedPostListVieweg

class MyNewView(ProtectedPostListView):
    #IMPOSSIBLE

, .as_view() , login_required , .

, , , .

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
+5

All Articles