Django, redirect all non-authenticated users to landing page

There is a simpler way to do this, just add the "login_url" parameter to @login_required and if the user is not login he will be redirected to the login page. You can find it here

from django.contrib.auth.decorators import login_required

@login_required(login_url='/accounts/login/')
def my_view(request):
    ...

You can use Middleware.

Something like this will check user auth every request:

class AuthRequiredMiddleware(object):
    def process_request(self, request):
        if not request.user.is_authenticated():
            return HttpResponseRedirect(reverse('landing_page')) # or http response
        return None

Docs: process_request

Also, don't forget to enable it in settings.py

MIDDLEWARE_CLASSES = (
    ...
    'path.to.your.AuthRequiredMiddleware',
)

Tags:

Python

Django