views:

82

answers:

2

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?

+3  A: 

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.

Hoff
@Hoff: How would you use `permission_required` in the same way? Specifically how would you pass it the permission name argument?
Manoj Govindan
@Manoj: check out this section of the documentation: http://docs.djangoproject.com/en/dev/topics/auth/#limiting-access-to-generic-views the idea is to write a thin wrapper (with permission_required decorator) around the generic view, and point your urlconf to that wrapper...
Hoff
@Hoff: That is what I did in my answer. Just wanted to know if there was any other way to go about it. Thanks.
Manoj Govindan
A: 

One approach would be to wrap the views you did not write.

from django.contrib.auth.views import password_change

@permission_required('my_perm')
def wrapper(*args, **kwargs):
    return password_change(*args, **kwargs)

#URLs
urlpatterns = patterns(
  (r'^$', "users.views.index"),
  (r'^password_change/$', 'wrapper'))
Manoj Govindan