9

I have a dashboard app in Django 1.10. I want to restrict access to this app's views to admin user only, if user is not logged in then redirect him to admin's login page.

This is where I want to apply some kind of logic so that only admin user can see links that starts with /dashboard/

url(r'^dashboard/', include('demo.dashboard.urls', namespace='dashboard'))

ujjwalwahi
  • 342
  • 1
  • 4
  • 13

3 Answers3

14

You have to decorate the individual views with either the @login_required decorator, or else the @staff_member_required decorator. Probably the latter, as the docs state:

If you are writing custom views for Django’s admin (or need the same authorization check that the built-in views use), you may find the django.contrib.admin.views.decorators.staff_member_required() decorator a useful alternative to login_required().

YellowShark
  • 2,169
  • 17
  • 17
  • My dashboard has many views, approx 20-25, do I need to apply decorator on each view. Isn't there a way, so that I can apply decorator at one place? – ujjwalwahi Mar 07 '17 at 21:38
  • It's more pythonic to declare them individually. We have about 40 or 50 custom admin views and that's how we treat them. They also have unique permission levels, so each view is decorated with the `@staff_member_required` decorator, along with `@superuser_required` or else `@permission_required('some_model.some_permission')`. Much easier, and I'd contend safer. – YellowShark Mar 07 '17 at 21:50
  • Thanks for the advice. – ujjwalwahi Mar 07 '17 at 22:04
  • One more thought: check out [this example of applying a single decorator to many functions](http://stackoverflow.com/a/30564033/844976), I think that might be exactly what you're looking for. I suspect that opinions on tinkering with `globals()` might be mixed, but I say "go for it". My opinion is that this is why we use Python - because we can make it bend to do whatever we want, like in that example. – YellowShark Mar 07 '17 at 22:20
9

You should use user_passes_test decorator:

def check_admin(user):
   return user.is_superuser

@user_passes_test(check_admin)
def my_view(request):
    ...
adlr0
  • 758
  • 9
  • 13
afilardo
  • 527
  • 2
  • 16
0

I'm not sure about Django 1.10, but in Django 3.0 you can use the request to check if the user is the superuser aka admin. Just do:

def yourviewname(request):
    if request.user.is_superuser:
        #whatever_you_want_the_admin_to_see
    else:
        #forbidden

You can also use decorators that come with django like @staff_member_required or @login_required

afilardo
  • 527
  • 2
  • 16
Yuvraj
  • 1