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

前端 未结 10 2012
日久生厌
日久生厌 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:46

    Some of the previous answers are either outdated (older version of Django), or introduce poor programming practices (hardcoding URLs, not using routes). Here's my take that is more DRY and sustainable/maintainable (adapted from Mehmet's answer above).

    To highlight the improvements here, this relies on giving URLs route names (which are much more reliable than using hard-coded URLs/URIs that change and have trailing/leading slashes).

    from django.utils.deprecation import MiddlewareMixin
    from django.urls import resolve, reverse
    from django.http import HttpResponseRedirect
    from my_project import settings
    
    class LoginRequiredMiddleware(MiddlewareMixin):
        """
        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 by setting a tuple of routes to ignore
        """
        def process_request(self, request):
            assert hasattr(request, 'user'), """
            The Login Required middleware needs to be after AuthenticationMiddleware.
            Also make sure to include the template context_processor:
            'django.contrib.auth.context_processors.auth'."""
    
            if not request.user.is_authenticated:
                current_route_name = resolve(request.path_info).url_name
    
                if not current_route_name in settings.AUTH_EXEMPT_ROUTES:
                    return HttpResponseRedirect(reverse(settings.AUTH_LOGIN_ROUTE))
    

    And in the settings.py file, you can define the following:

    AUTH_EXEMPT_ROUTES = ('register', 'login', 'forgot-password')
    AUTH_LOGIN_ROUTE = 'register'
    

提交回复
热议问题