[英]how to use different decorator from parent class in child class in django?
I have 2 class based views MyFirstView
and MySecondView
.我有 2 个基于 class 的视图
MyFirstView
和MySecondView
。 I want these 2 views to use different decorators from each other.我希望这 2 个视图使用彼此不同的装饰器。 I have been googling for the solution almost an hour now but still can't find any answers to this.
我已经在谷歌上搜索了将近一个小时的解决方案,但仍然找不到任何答案。 So I'm here asking for help.
所以我在这里寻求帮助。
@method_decorator(my_first_decorator, name="dispatch")
class MyFirstView(UpdateView):
# some attributes
# some methods
@method_decorator(my_second_decorator, name="dispatch")
class MySecondView(MyFirstView):
# some attributes
I have been trying to give the different decorator to the views like showed above but for some reason MySecondView
still using MyFirstView
's decorator.我一直在尝试为上面显示的视图提供不同的装饰器,但由于某种原因
MySecondView
仍在使用MyFirstView
的装饰器。
I also tried to override the dispatch method but without any success.我也试图覆盖 dispatch 方法但没有成功。
class MyFirstView(UpdateView):
@method_decorator(my_first_decorator)
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
# some attributes
# some methods
class MySecondView(MyFirstView):
@method_decorator(my_second_decorator)
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
# some attributes
The second approach seems right, but you have to skip one parent in the MRO:第二种方法似乎是正确的,但是您必须在 MRO 中跳过一个父级:
class MySecondView(MyFirstView):
@method_decorator(my_second_decorator)
def dispatch(self, *args, **kwargs):
return super(MyFirstView, self).dispatch(*args, **kwargs)
This way, the super
calls the plain undecorated original implementation instead of the tainted one from its direct super class.这样,
super
调用普通的未修饰的原始实现,而不是来自其直接 super class 的受污染的实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.