Solution details

There are two ways to control access to a view:

  1. By using a decorator on a function-based view or class-based view:
@login_required(MyView.as_view()) 
  1. By overriding the dispatch method of a class-based view through a mixin:
from django.utils.decorators import method_decorator 
 
class LoginRequiredMixin: 
    @method_decorator(login_required) 
    def dispatch(self, request, *args, **kwargs): 
        return super().dispatch(request, *args, **kwargs) 
  1. We really don't need the decorator here. It is recommended to use the more explicit form as follows:
class LoginRequiredMixin: 
 
    def dispatch(self, request, *args, **kwargs): 
        if not request.user.is_authenticated(): 
            raise PermissionDenied 
        return super().dispatch(request, *args, **kwargs) 

When ...

Get Django Design Patterns and Best Practices - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.