-
Install pip install django-login-required-middleware
-
Add login_required.middleware.LoginRequiredMiddleware
to MIDDLEWARE
after
django.contrib.auth.middleware.AuthenticationMiddleware
-
(Optional) To ignore authentication in a view uses decorato @login_not_required
for FBV or LoginNotRequiredMixin
for CBV:
from login_required import login_not_required
@login_not_required
def my_view(request):
return HttpResponse()
or
from login_required import LoginNotRequiredMixin
class MyView(LoginNotRequiredMixin, View):
def get(self, request, *args, **kwargs):
return HttpResponse()
-
(Optional) Add LOGIN_REQUIRED_IGNORE_PATHS
setting.
Any requests which match these paths will be ignored. This setting should be a list filled with
regex paths (settings.LOGIN_URL
always included).
Example:
LOGIN_REQUIRED_IGNORE_PATHS = [
r'/accounts/logout/$',
r'/accounts/signup/$',
r'/admin/$',
r'/about/$'
]
-
(Optional) Add LOGIN_REQUIRED_IGNORE_VIEW_NAMES
setting.
Any requests which match these url name will be ignored. This setting should be a list filled with
url names.
Example:
LOGIN_REQUIRED_IGNORE_VIEW_NAMES = [
'home',
'admin:index',
'admin:login',
'namespace:url_name',
]
-
(Optional) Add LOGIN_REQUIRED_REDIRECT_FIELD_NAME
setting.
This will be passed to Django's redirect_to_login(). Default is 'next'.
Example:
LOGIN_REQUIRED_REDIRECT_FIELD_NAME = 'next_url'