Django, redirect all non-authenticated users to landing page

前端 未结 8 1386
挽巷
挽巷 2021-01-30 23:08

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_a

8条回答
  •  攒了一身酷
    2021-01-30 23:55

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

提交回复
热议问题