[Django]-Superuser authenticate in class based view

3👍

You can work with a UserPassesTestMixin mixin [Django-doc]:

from django.contrib.auth.mixins import UserPassesTestMixin

class AddPostView(UserPassesTestMixin, CreateView):
    # …
    
    def test_func(self):
        return self.request.user.is_superuser
    
    # …

You can encapsulate this in a mixin:

from django.contrib.auth.mixins import UserPassesTestMixin

class AdminRequiredMixin(UserPassesTestMixin):
    def test_func(self):
        return self.request.user.is_superuser

and then use this mixin:

class AddPostView(AdminRequiredMixin, CreateView):
    # …
    
    def test_func(self):
        return self.request.user.is_superuser
    
    # …

Mixins should be put before the actual view in the inheritance hierarchy: otherwise these appear after the view in the method resolution order (MRO), and thus likely will not override the behavior (correctly).

2👍

class AddPostView(CreateView,LoginRequiredMixin):
    model = Post
    template_name = 'MainSite/add_post.html'
    fields = '__all__'
    def dispatch(self, request, *args, **kwargs):
        if request.user.is_anonymous:
           return redirect_to_login(self.request.get_full_path(), self.get_login_url(), self.get_redirect_field_name())
        elif request.user.is_superuser:
            return render(.....)
        else
            return super(AddPostView, self).dispatch(request, *args, **kwargs)
👤Akram

1👍

Use method_decorator and user_passes_test to achieve this

from django.views.generic import View
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import user_passes_test

class AddPostView(View):
    @method_decorator(user_passes_test(lambda u: u.is_superuser))
    def post(self, *args, **kwargs):
        pass

Leave a comment