Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django check if superuser in class-based view

Tags:

python

django

I am converting my project from function-based view to class-based view. In a view function, I can check if a user is a superuser using request.user.is_superuser() function. I can check if a user is logged in by inheriting LoginRequiredMixin in a View class, I want to know if there is any similar way that can be used for checking if the user is a superuser in a View class. I want a Django app only accessible by the superusers of the site.

like image 968
Shafquat Avatar asked Oct 20 '25 17:10

Shafquat


1 Answers

You can create your own :

from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin

class SuperUserRequiredMixin(LoginRequiredMixin, UserPassesTestMixin):

    def test_func(self):
        return self.request.user.is_superuser

and then instead of using LoginRequiredMixin in your ClassBasedView you use your SuperUserRequiredMixin

Now your view will only allow logged-in superuser.

like image 145
taha maatof Avatar answered Oct 23 '25 06:10

taha maatof



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!