Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 520
kdt Avatar asked Aug 11 '10 17:08

kdt


1 Answers

A decorator is a fancy word for a function that wraps another function. login_required is a wrapper function for a view while permission_required constructs a wrapper for your view. In other words, login_required is itself a decorator and permission_required(perm) constructs a decorator.

from django.conf.urls import url
from django.contrib.auth.decorators import login_required, permission_required

urlpatterns = [
    url(r'^public/', myview),

    url(r'^users_only/', 
        login_required(myview)),

    url(r'^users_with_perms/',
        permission_required('myapp.view_mymodel', login_url='login')(myview)),

    url(r'^login_page/', myloginview, name='login'),
]
like image 99
jozxyqk Avatar answered Oct 30 '22 02:10

jozxyqk