Django: How can I apply the login_required decorator to my entire site (excluding static media)?

前端 未结 10 2002
日久生厌
日久生厌 2020-12-24 07:21

The example provides a snippet for an application level view, but what if I have lots of different (and some non-application) entries in my \"urls.py\" file, including templ

10条回答
  •  佛祖请我去吃肉
    2020-12-24 07:51

    Here's a slightly shorter middleware.

    from django.contrib.auth.decorators import login_required
    
    class LoginRequiredMiddleware(object):
        def process_view(self, request, view_func, view_args, view_kwargs):
            if not getattr(view_func, 'login_required', True):
                return None
            return login_required(view_func)(request, *view_args, **view_kwargs)
    

    You'll have to set "login_required" to False on each view you don't need to be logged in to see:

    Function-views:

    def someview(request, *args, **kwargs):
        # body of view
    someview.login_required = False
    

    Class-based views:

    class SomeView(View):
        login_required = False
        # body of view
    
    #or
    
    class SomeView(View):
        # body of view
    someview = SomeView.as_view()
    someview.login_required = False
    

    This means you'll have to do something about the login-views, but I always end up writing my own auth-backend anyway.

提交回复
热议问题