Search code examples
djangodjango-viewsdecorator

How can perform a task from superuser in django


I am trying to perform an action from superuser accept/reject the task, but after login from superuser it show the error. even if i logged in from non superuser if show the same error

  403 Forbidden 

i am trying first time perform action from superuser i don't know how can i fix this issue

View.py

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

class Approval(LoginRequiredMixin, UserPassesTestMixin, TemplateView):
    def test_func(self):
        if self.request.user == User.is_superuser:
           return True
        else:
           return False

    template_name = 'approve.html'

    def get(self, request, *args, **kwargs):
        return render(request, self.template_name)

    def post(self, request):
        

Urls.py

urlpatterns = [
        path('approve',Approval.as_view(), name='approve')
]

Solution

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