There are two ways to control access to a view:
- By using a decorator on a function-based view or class-based view:
@login_required(MyView.as_view())
- 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)
- 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 ...