One thing I wanted for a while was the ability to basically apply something like @login_required to a bunch of urlpatterns in one go, instead of having to decorate each and every view manually. I finally spent some time looking through the Django source, and I came up with the following:
from django.core.urlresolvers import RegexURLPattern from django.conf.urls.defaults import patterns class DecoratedURLPattern(RegexURLPattern): def resolve(self, *args, **kwargs): result = RegexURLPattern.resolve(self, *args, **kwargs) if result: result = list(result) result = self._decorate_with(result) return result def decorated_patterns(prefix, func, *args): result = patterns(prefix, *args) if func: for p in result: if isinstance(p, RegexURLPattern): p.__class__ = DecoratedURLPattern p._decorate_with = func return result def control_access(view_func): def _checklogin(request, *args, **kwargs): raise Http404() return _checklogin urlpatterns = patterns('views', # unprotected views (r'^public/contact/$', 'contact'), (r'^public/imprint/$', 'imprint'), ) + decorated_patterns('views', control_access, (r'^admin/add/$', 'add'), (r'^admin/edit/$', 'edit'), )
In this example, the latter two views will always raise a 404.
So far it seems to work quite nicely.