Django, redirect all non-authenticated users to landing page

前端 未结 8 1376
挽巷
挽巷 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-31 00:09

    Maybe too late but in django 1.9+ it's too easy. Django introduced Login Required mixin for generic classes and this a great example here by William S. Vincent

    simply in your view add LoginRequiredMixin as parent class

    from django.contrib.auth.mixins import LoginRequiredMixin
    
    class BlogUpdateView(LoginRequiredMixin, UpdateView):
    model = Post
    template_name = 'post_edit.html'
    fields = ['title', 'body']
    

    Also you can use login_required decorator for method request

    0 讨论(0)
  • 2021-01-31 00:12

    This can be done with middleware.

    I've found a really nifty djangosnippet that does exactly what you are asking for. You can find it here, and it looks like:

    from django.http import HttpResponseRedirect
    from django.conf import settings
    from re import compile
    
    EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))]
    if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
        EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS]
    
    class LoginRequiredMiddleware:
        """
        Middleware that requires a user to be authenticated to view any page other
        than LOGIN_URL. Exemptions to this requirement can optionally be specified
        in settings via a list of regular expressions in LOGIN_EXEMPT_URLS (which
        you can copy from your urls.py).
    
        Requires authentication middleware and template context processors to be
        loaded. You'll get an error if they aren't.
        """
        def process_request(self, request):
    
            assert hasattr(request, 'user'), "The Login Required middleware\
     requires authentication middleware to be installed. Edit your\
     MIDDLEWARE_CLASSES setting to insert\
     'django.contrib.auth.middlware.AuthenticationMiddleware'. If that doesn't\
     work, ensure your TEMPLATE_CONTEXT_PROCESSORS setting includes\
     'django.core.context_processors.auth'."
    
            if not request.user.is_authenticated():
                path = request.path_info.lstrip('/')
                if not any(m.match(path) for m in EXEMPT_URLS):
                    return HttpResponseRedirect(settings.LOGIN_URL)
    

    All you have to do is to save the file as middleware.py and include the class in you're settings.py, i.e.

    MIDDLEWARE_CLASSES += ('projectname.common.middleware.RequireLoginMiddleware',)
    

    You can also define a LOGIN_URL in settings.py, so that you'll be redirected to your custom login page. The default LOGIN_URL is '/accounts/login/'.

    0 讨论(0)
提交回复
热议问题