Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Django allow only admin user to access views

Tags:

django

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'))

like image 918
ujjwalwahi Avatar asked Mar 07 '17 21:03

ujjwalwahi


People also ask

How do I restrict access to parts of Django admin?

Django admin allows access to users marked as is_staff=True . To disable a user from being able to access the admin, you should set is_staff=False . This holds true even if the user is a superuser. is_superuser=True .

Does Django have view permissions?

The Django admin site uses permissions as follows: Access to view objects is limited to users with the “view” or “change” permission for that type of object. Access to view the “add” form and add an object is limited to users with the “add” permission for that type of object.

How can we set restrictions on views in Django?

Restrict access to unauthenticated users in Django Views. To simply restrict access to a view based on if the user is authenticated (logged in) or not does not require you to dive deep into the permission system at all, you can simply do it with Decorators, Mixins or the user is_authenticated property.


1 Answers

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().

like image 101
YellowShark Avatar answered Sep 22 '22 10:09

YellowShark