This recipe is an old one but a good one. In some Django projects you will want to force a user to login for all or almost all pages. Stop copy pasting that login_required decorator on all your views! Using this middleware you very easily can force authentication on all pages you want.
To accomplish this we will create a new Django Middleware class called LoginRequiredMiddleware. Simply copy-paste the code below in a middleware.py file in one of your Django applications.
from django.http import HttpResponseRedirect
from django.conf import settings
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]
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\
if not request.user.is_authenticated():
path = request.path_info.lstrip('/')
if not any(m.match(path) for m in EXEMPT_URLS):
Installing the middleware
To install the middleware you simply add it to the list of middleware in your project’s settings file. We will talk about Django’s Middleware in a later article but for now just now that this kind of middleware sits perfectly at the bottom of the default middleware list:
MIDDLEWARE_CLASSES = [
Configure any URLs to exclude
By default this middleware will redirect all requests from unauthenticated users to the LOGIN_URL. If you want to exclude any URLs from this (such as an about page or registration page) you can specify a setting called LOGIN_EXEMPT_URLS:
LOGIN_EXEMPT_URLS = (
In the example above we exclude the ‘homepage’ of our application at /, the about page at /about and the registration page at /register. There is no need to specify the url of your login page as this is done automatically by the middleware.
And that’s it! All requests that come from an unauthenticated user to an URL that’s not in your LOGIN_EXEMPT_URLS setting will be redirected to your login view.