Django, redirect all non-authenticated users to landing page

前端 未结 8 1391
挽巷
挽巷 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

    As of Django 1.10, the custom middleware classes must implement the new style syntax. You can use the following class to verify that the user is logged in while trying to access any views.

    from django.shortcuts import HttpResponseRedirect
    
    
    class AuthRequiredMiddleware(object):
        def __init__(self, get_response):
            self.get_response = get_response
    
        def __call__(self, request):
            # Code to be executed for each request before
            # the view (and later middleware) are called.
    
            response = self.get_response(request)
            if not request.user.is_authenticated: # in Django > 3 this is a boolean
                return HttpResponseRedirect('login')
            
            # Code to be executed for each request/response after
            # the view is called.
    
            return response
    

提交回复
热议问题