Categories
Python Answers

How to use permission_required decorators on Python Django class-based views?

Spread the love

To use permission_required decorators on Python Django class-based views, we add the views.

And then we use the method_decorator to add the permissions required.

For instance, we write

urlpatterns = [
    path('view/',login_required(ViewSpaceIndex.as_view(..)),
    #...
]

to register the views.

Then we add

from django.utils.decorators import method_decorator

@method_decorator(login_required, name='dispatch')
class ViewSpaceIndex(TemplateView):
    template_name = 'secret.html'

to apply the method_decorator decorator and use the login_required function we created to let us enforce login on the ViewSpaceIndex view.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *