Search code examples
pythondjangodjango-1.9

creating admin restricted urls


so in my urls.py (outside django default admin section ) i want to restrict some urls only to admin so if i have this for logged users

  from django.contrib.auth.decorators import login_required

    urlpatterns = [
        url(r'^a1$',login_required( views.admin_area1 ), name='a1'),
        url(r'^a2$', login_required(views.admin_area2) , name='a2'),
        url(r'^a3', login_required(views.admin_area3) , name='a3'),
    ]

is there enyway torestrict these links to logged admins not just any logged user ? there is but according to this i can use user_passes_test but i have to use it in view


Solution

  • You can use the decorator returned by user_passes_test(lambda u: u.is_superuser) in the same way that you use login_required:

    urlpatterns = [
        url(r'^a1$', user_passes_test(lambda u: u.is_superuser)(views.admin_area1), name='a1'),
    ]
    

    If you want to restrict access to admins, then it might be more accurate to use the staff_member_required decorator (which checks the is_staff flag) instead of checking the is_superuser flag.

    from django.contrib.admin.views.decorators import staff_member_required
    
    urlpatterns = [
        url(r'^a1$', staff_member_required(views.admin_area1), name='a1'),
        ...
    ]