max max - 3 months ago 19
Python Question

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

Answer

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 would be more accurate to use the staff_member_required decorator instead of checking is_superuser.

from django.contrib.admin.views.decorators import staff_member_required

urlpatterns = [
    url(r'^a1$', staff_member_required(views.admin_area1), name='a1'),
    ...
]