本文介绍了两种装饰基于类视图的方法有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个继承自ListView的视图,并试图将视图限制为登录的用户。

I'm writing a view that inherits from ListView, and am trying to restrict the view to logged-in users.

说,使用URLconf中的login_required进行装饰每个实例都应用装饰器,如果你希望每个视图的实例被装饰,你需要采取不同的方法 - 这种方法是在视图代码中装饰调度方法。

https://docs.djangoproject.com/en/dev/topics/class-based-views/#decorating-in-urlconf says that decorating with login_required in the URLconf "applies the decorator on a per-instance basis. If you want every instance of a view to be decorated, you need to take a different approach" -that approach being to decorate the dispatch method in the view code.

我以为我知道一个类和一个实例之间的区别,但是这个短语不对我来说意味着什么有人可以澄清吗?除了在URLconf中有一个装饰器,而不是在类定义中,两种方法之间有什么区别?

I thought I knew the difference between a class and an instance but this phrase doesn't mean anything to me. Could someone clarify? Apart from having a decorator in the URLconf as opposed to in your class definition, what are the differences between the two approaches?

上面的链接似乎回答了这个问题:由于基于类的视图不是函数,根据您是否使用as_view或创建子类,装饰它们的工作方式不同。

The paragraph above that link seems to answer the question: "Since class-based views aren't functions, decorating them works differently depending on if you're using as_view or creating a subclass."

真的吗我似乎可以用我的ListView子类使用URLconf方法。

Really?? I seem to be able to use the URLconf approach with my subclass of ListView.

推荐答案

想象你有以下类的视图:

Imagine you have the following class based view:

class PostListView(ListView):
     model = Post

ProtectedPostListView = login_required(PostListView.as_view())

和您的urls.py:

and your urls.py:

url(r'posts$', ProtectedPostListView)

如果你使用这种方法,那么你将失去子类 ProtectedPostListView 的能力,例如

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

class MyNewView(ProtectedPostListView):
    #IMPOSSIBLE

这是因为 .as_view()返回一个函数,应用 login_required 装饰器后,您将留下一个函数,因此子类不是

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.

另一方面,如果你使用第二种方法,即使用方法装饰器子类化是可能的。
eg

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

这篇关于两种装饰基于类视图的方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 02:48