Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

python - how to use different decorator from parent class in child class in django?

I have 2 class based views MyFirstView and MySecondView. I want these 2 views to use different decorators from each other. 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.

I also tried to override the dispatch method but without any success.

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
question from:https://stackoverflow.com/questions/65935859/how-to-use-different-decorator-from-parent-class-in-child-class-in-django

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The second approach seems right, but you have to skip one parent in the 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...