Django: Applying permissions in the URL dispatcher?

kdt picture kdt · Aug 11, 2010 · Viewed 10.7k times · Source

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?

Answer

jozxyqk picture jozxyqk · Jul 15, 2015

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'),
]