我有多个视图都从基本视图继承。所有视图都需要login_required装饰器。我想将它添加为方法装饰器来分派基本视图,然后不必将装饰器添加到每个子视图。我无法做到这一点。
这通常不可能吗?我错过了什么?我不知道的是什么?
以下是我的代码的一个细分版本:
class CoreView(CoreMixin,TemplateView):
pass
class BaseView(CoreView):
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(BaseView, self).dispatch(request, *args, **kwargs)
class MyView(BaseView):
def dispatch(self, request, *args, **kwargs):
"Do Stuff"
我试图做我的研究,但找不到答案。
BTW:我目前正在使用django 1.8和python 2.7。
答案 0 :(得分:2)
没有“直接”方式,但您可以在Python: Decorating a class method that is intended to be overwritten when inherited中找到一些解决方案。
唯一适合你的方法是使用cast(cast((SUM (GoodReadCount)-SUM (NoReadCount))*100.00/SUM (GoodReadCount) as decimal(4,1)) as varchar(10)) + '%'
中的钩子,如:
dispatch
答案 1 :(得分:1)
您的答案在文档中。对于基于类的视图,有mixins。如果您错过了permission required也是如此。
答案 2 :(得分:0)
试试:
def login_required_class(decorator):
def decorate(cls):
for attr in cls.__dict__:
if callable(getattr(cls, attr)):
setattr(cls, attr, decorator(getattr(cls, attr)))
return cls
return decorate
@login_required_class(login_required)
class CoreView(CoreMixin,TemplateView):
pass
@login_required_class(login_required)
class BaseView(CoreView):
def dispatch(self, request, *args, **kwargs):
return super(BaseView, self).dispatch(request, *args, **kwargs)
@login_required_class(login_required)
class MyView(BaseView):
def dispatch(self, request, *args, **kwargs):
"Do Stuff"