catherine
catherine

Reputation: 22808

How to put customize decorator in TemplateView

I'm starting to convert my function based view to class based view. This is my first time of using class based view, so I really don't know the correct way.

FBV's codes:

@auth_check
def thank_you(request):
    return render(request, 'thank_you.html')

CBV's codes:

class ThankYouView(TemplateView):
    template_name = "thank_you.html"

Where I would put the auth_check decorator? I try to put it in the top of the class but I got an error. Then I create def inside the class and put the decorator at the top of it but still I got an error.

Upvotes: 2

Views: 841

Answers (1)

Ngenator
Ngenator

Reputation: 11259

https://docs.djangoproject.com/en/dev/topics/class-based-views/intro/#decorating-the-class

With class based views, you decorate the dispatch method.

from django.utils.decorators import method_decorator

class ThankYouView(TemplateView):
    template_name = "thank_you.html"

    @method_decorator(auth_check)
    def dispatch(self, *args, **kwargs):
        return super(ThankYouView, self).dispatch(*args, **kwargs)

Upvotes: 3

Related Questions