[Answered ]-How can perform a task from superuser in django

1👍

You check if the user is a superuser with:

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

class Approval(LoginRequiredMixin, UserPassesTestMixin, TemplateView):
    template_name = 'approve.html'
    
    def test_func(self):
        return self.request.user.is_superuser

    def get(self, request, *args, **kwargs):
        return render(request, self.template_name, {'all_saloon': all_saloon})

The all_saloon is however strange: it means that if it is a list or QuerySet it will each time work with the same data, and thus if later a new Saloon is constructed, it will not take that into account.

You can alter the handle_no_permission function to determine what to do in case the test fails:

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

class Approval(LoginRequiredMixin, UserPassesTestMixin, TemplateView):
    template_name = 'approve.html'
    
    def test_func(self):
        return self.request.user.is_superuser
    
    def handle_no_permission(self):
        return redirect('name-of-some-view')
    
    def get(self, request, *args, **kwargs):
        return render(request, self.template_name, {'all_saloon': all_saloon})

Likely you want to work with a ListView [Django-doc] instead.

Leave a comment