let me down slowly
let me down slowly

Reputation: 1017

Django check if superuser in class-based view

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.

Upvotes: 3

Views: 3815

Answers (2)

taha maatof
taha maatof

Reputation: 2165

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.

Upvotes: 7

chaulap
chaulap

Reputation: 449

He is an example use case of what you are trying to accomplish. You need self.request.user.is_superuser.

class ExampleClassView(LoginRequiredMixin,TemplateView):
    template_name = "core/index.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["is_super"] = self.request.user.is_superuser
        return context

Upvotes: -1

Related Questions