I have a few restricted areas on the site, for which I would like to specify login_required
decorator. However I would like to do that once per inclusion in main urls.py, not per individual url in included urls.py
So instead of:
/private/urls.py:
(r'^profile/$', login_required(profile)),
I'd do something along the lines:
/urls.py
urlpatterns = patterns('',
...
(r'^private/', login_required(include('private'))),
)
Except that it doesn't work, unfortunately.
login_required
is meant for wrapping view callable, not include(), and looking at source code:http://code.djangoproject.com/browser/django/tags/releases/1.1.1/django/conf/urls/defaults.py#L9
-- I don't think there is an easy way to use default (or even custom)
login_required
with include() to achieve what you want to achieve.Writing this, I think that the reasonable approach would be to use some "login required middleware", like this one: http://www.djangosnippets.org/snippets/1179/ and forget about decorating urls in urls.py.
An alternative:
A slightly more complex version, that supports multiple decorators:
It is doable, and in fact I just found two snippets for this.
Solution #1
The first snippet by cotton substitutes
RegexURLPattern
andRegexURLResolver
with custom implementations that inject given decorator duringresolve
call.You need to use it like this:
(Note that
include
parameter can't be a string with this method.)Solution #2
Another solution by sjzabel, which I ended up using myself, is applied outside
patterns
call so it can be used with strings and has a slightly different syntax. The idea is the same, though.Call it like this:
Both work fine but I prefer the latter syntax.
you can use decorate_url
see here
http://github.com/vorujack/decorate_url
you can install it by pip
example show on github