Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit a view to superuser only?

Tags:

django

view.py

@login_required @permission_required('is_superuser') def score_reset(request):    pass 

url.py

url(r'^score-reset/$', score_reset, name='score-reset'),     

I have the following code and to my surprise I still hit the function, despite being logged in with a non superuser. I was expecting to get a permission denied.

What am I missing?

like image 452
Houman Avatar asked Apr 14 '13 10:04

Houman


People also ask

How do I restrict access in Django?

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 superuser permissions?

A Django superuser, is its name implies, means it's a user with 'super' permissions. By extension, this means a superuser has access to any page in the Django admin, as well as permissions to Create, Read, Update and Delete any type of model record available in the Django admin.


1 Answers

is_superuser isn't a permission, it's an attribute on the user model. Django already has another decorator you can make use of called user_passes_test to perform this check:

from django.contrib.auth.decorators import user_passes_test  @user_passes_test(lambda u: u.is_superuser) def score_reset(self,...):     ... 
  • allowing only super user login
  • Django is_staff permission decorator
like image 112
Timmy O'Mahony Avatar answered Oct 04 '22 15:10

Timmy O'Mahony