[Solved]-Django: Applying permissions in the URL dispatcher?

10👍

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

18👍

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

-1👍

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

-2👍

I have a little hack about the Django URL resolver, you may apply a decorator at URL dispatch level:

from django_url_decr import url_decr
from django.contrib.auth.decorators import login_required

urlpatterns = patterns(''
                       url_decr(r'^users/',
                                include('users.urls'),
                                decr=login_required))

Leave a comment