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.
In this example, the latter two views will always raise a 404.
This is broken in Django 1.3.
To fix it, replace the DecoratedURLPattern class with this:
def resolve(self, *args, **kwargs):
result = RegexURLPattern.resolve(self, *args, **kwargs)
result.func = self._decorate_with(result.func)
This snippet works great, and allows you to enforce some precondition for a large number of URLs in one go (when using the fix from comment 3.).
If you add
**kwargs to decorated_patterns, it also works with named patterns.
In my opinion, this is extremely useful, and the snippet is greatly underrated.
Thanks for sharing this!
if you want to user included url files, like so
- decorated_patterns('', control_access,
modify decorated_patterns to be:
def decorated_patterns(prefix, func, *args):
result = patterns(prefix, *args)
for p in result:
if isinstance(p, RegexURLPattern):
p.__class__ = DecoratedURLPattern
p._decorate_with = func
elif isinstance(p, RegexURLResolver):
for pp in p._get_url_patterns():
if isinstance(pp, RegexURLPattern):
pp.__class__ = DecoratedURLPattern
pp._decorate_with = func
Why don't you use directly decorators in urls?
from foo.views import contact, imprint, add, edit
urlpatterns = patterns('',
# unprotected views
# protected views