Django, redirect all non-authenticated users to landing page

django, python

Solution

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',
)

Problem

I have a django website with many urls and views. Now I have asked to redirect all non-authenticated users to a certain landing page. So, all views must check if `user.is_authenticated()` and return to a new set of landing pages. Can it be done in a pretty way, instead of messing with my `views.py`/`urls.py` that much?

Original source

Related problems