[Django]-Django 1.10: login required middleware redirect loop

5👍

Doh! I needed to check for /login/ in process_request and ignore it.

Here’s a simplified version of what is implemented. The real version uses settings.py and regexes to define the login exempt urls. Much credit to Ryan Witt’s post on this approach.

class LoginRequiredMiddleware(MiddlewareMixin):

    def process_request(self, request):
        if not request.user.is_authenticated():
            path = request.path_info.lstrip('/')
            # If path is not root url ('') and path is not exempt from authentication
            if not path or not any(path != eu for eu in ["/login", "admin"]):
                return HttpResponseRedirect("/login/")

Leave a comment