Is it possible to decorate include(...) in django urls with login_required?

Viewed 15733

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.

6 Answers

I know this is a very old question so for anyone who is wondering about the same, there is a very simple solution now.

Install django-decorator-include via pip install django-decorator-include.

Here is how to use it:

from django.contrib.auth.decorators import login_required
from decorator_include import decorator_include


urlpatterns = [
    path(r'^private/', decorator_include(login_required, 'private')),
]

Here is the link to the GitHub documentation.

And here is the link to Pypi.org

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.

Related