Я использую это промежуточное программное обеспечение, которое я нашел в https://djangosnippets.org/snippets/2845/. Это даже регулярное выражение белый список по URL (LOGIN_EXEMPT_URLS
)
# -*- coding: UTF-8 -*-
# django dependencies
from django.contrib.auth.views import redirect_to_login
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.conf import settings
# python dependencies
from re import compile
#---#
EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS]
#---#
class LoginRequiredMiddleware:
"""
Middleware that requires a user to be authenticated to view any page other
than LOGIN_URL. Exemptions to this requirement can optionally be specified
in settings via a list of regular expressions in LOGIN_EXEMPT_URLS (which
you can copy from your urls.py).
Requires authentication middleware and template context processors to be
loaded. You'll get an error if they aren't.
"""
def process_request(self, request):
assert hasattr(request, 'user'), ("The Login Required middleware "
"requires authentication middleware to be installed. Edit "
"your MIDDLEWARE_CLASSES setting to insert "
"'django.contrib.auth.middlware.AuthenticationMiddleware'. "
"If that doesn't work, ensure your "
"TEMPLATE_CONTEXT_PROCESSORS setting includes "
"'django.core.context_processors.auth'.")
if not request.user.is_authenticated():
path = request.path_info.lstrip('/')
if not any(m.match(path) for m in EXEMPT_URLS):
path = request.get_full_path()
return redirect_to_login(path, settings.LOGIN_URL,
REDIRECT_FIELD_NAME)
Просто поместите его после того, как django.contrib.auth.middleware.*AuthenticationMiddleware
к вашему MIDDLEWARE_CLASSES
в настройках. Если у вас его нет, вы должны добавить его.
MIDDLEWARE_CLASSES = (
'django.middleware.security.SecurityMiddleware',
...
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'sis_tools.middleware.LoginRequiredMiddleware', # <-- HERE
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
)
Белый список работает как urls.py
, так что вы можете использовать его как это:
LOGIN_EXEMPT_URLS = (r'^about.html$', r'^legal/',)
Это позволяет пользователю посетить страницу sample.com/about.html
и все, что в разделе sample.com/legal/*
Также вы должны установить в ваших настройках LOGIN_URL
на вашу страницу входа в систему следующим образом:
LOGIN_PAGE = "/accounts/login"
Также удобно установить LOGIN_REDIRECT_URL
адрес, на который нужно перейти, если пользователь заходит на сайт на странице входа.
LOGIN_REDIRECT_URL = "/"