2

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

Community
  • 1
  • 1
max
  • 3,614
  • 9
  • 59
  • 107
  • 1
    user_passes_test is the best way. BTW, don't mind me saying, if you want to be a good coder, develop a practice of reading docs instead of SO. – Swakeert Jain Aug 30 '16 at 15:14
  • @SwakeertJain the problem with `user_passes_test ` is that i have to use it in the views which i don't like , thanks for the advice i do read docs but sometimes you want to get result fast and docs are huge withouth good examples – max Aug 30 '16 at 15:16

1 Answers1

7

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'),
    ...
]
Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • thanx , i dont want to use django admin and i'm writing my own admin so i guess `staff_member_required` is what i want – max Aug 30 '16 at 16:04