Search code examples
djangodjango-urlsdjango-permissions

Django: Applying permissions in the URL dispatcher?


In my Django application, I have certain permissions which users need in order to access certain views (using django.contrib.auth). This works fine, using the @permission_required decorator on my view functions.

However, some of my URLs resolve to views which I did not write, such as the built-in django.contrib.auth.views.password_change, as in the following urls.py:

urlpatterns = patterns(
 (r'^$', "users.views.index"),
 (r'^password_change/$', 'django.contrib.auth.views.password_change'))

In this instance, I have nowhere to apply my @permission_required decorator -- or do I? Is there any way to apply a permissions restriction at the URL dispatcher level?


Solution

  • It's possible to import the login required function and apply it to the generic view:

    from django.contrib.auth.decorators import login_required
    from django.views.generic.simple import direct_to_template
    urlpatterns = patterns('',
        (r'^foo/$', login_required(direct_to_template), {'template': 'foo_index.html'}),
        )
    

    as mention here.