Menu Close

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

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.

Posted in Python, Python Answers