Reputation: 342
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'))
Upvotes: 9
Views: 17051
Reputation: 1
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
Upvotes: 0
Reputation: 527
You should use user_passes_test decorator:
def check_admin(user):
return user.is_superuser
@user_passes_test(check_admin)
def my_view(request):
...
Upvotes: 9
Reputation: 2269
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 tologin_required()
.
Upvotes: 15