views:

51

answers:

2

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 templates? How can I apply this login required decorator to each of them?

(r'^foo/(?P<slug>[-\w]+)/$', 'bugs.views.bug_detail'),
(r'^$', 'django.views.generic.simple.direct_to_template', {'template':'homepage.html'}),
+2  A: 

Use middleware.

http://www.djangobook.com/en/2.0/chapter17/ and http://docs.djangoproject.com/en/1.2/topics/http/middleware/#topics-http-middleware

I'm assuming this didn't change a whole lot in 1.2

Middleware allows you to create a class with methods who will process every request at various times/conditions, as you define.

for example process_request(request) would fire before your view, and you can force authentication and authorization at this point.

andyortlieb
You should elaborate.
Byron Whitlock
I'm not that familiar with using custom middleware. Can you point out a django 1.2 compatible snippet that handles this?
meder
I came across this snippet: http://djangosnippets.org/snippets/1179/Though it was posted in 2008. Can anyone skim through and see if it would be usable?
meder
Yes, that snippet should work fine.
sdolan
A: 

Dropped this into a middleware.py file in my project root:

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)

Then appended projectname.middleware.LoginRequiredMiddleware to my MIDDLEWARE_CLASSES in settings.py.

meder