Home > Mobile >  superuser authenticate in class based view
superuser authenticate in class based view

Time:03-19

I am working on blog project in which I added an add post which add post now I want only the superuser can add post and that page is visible only to superuser.
1st Method
Views.py

class AddPostView(CreateView):
    model = Post
    template_name = 'MainSite/add_post.html'
    fields = '__all__'

this is my current view I am able to achieve authenticate for superuser using 2nd method
2nd Method

class AddPostView(View):
    def get(self,request):
        if request.user.is_superuser == True:
            return render(...)
        else:
            pass

How can I achieve the same result using 1st method.I tried using LoginRequiredMixin but nothing is happening . I just import LoginRequiredMixin and use it like this .

class Addpost(CreateView,LoginRequiredMixin):
    ...

Thanks in advance and advice will be helpful.

CodePudding user response:

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

CodePudding user response:

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)

CodePudding user response:

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
  • Related