Use LoginRequiredMixin and UserPassesTestMixin at the same time

前端 未结 2 476
广开言路
广开言路 2021-01-05 03:56

I want to have a TemplateView Class that uses LoginRequiredMixin and UserPassesTestMixin at the same time. Something like this:

from django.views.generic imp         


        
2条回答
  •  情话喂你
    2021-01-05 04:28

    I think you're better off subclassing AccessMixin and then performing these checks yourself. Something like this:

    from django.contrib.auth.mixins import AccessMixin
    from django.http import HttpResponseRedirect 
    
    class FinanceOverview(AccessMixin, TemplateMixin):
    
        def dispatch(self, request, *args, **kwargs):
            if not request.user.is_authenticated:
                # This will redirect to the login view
                return self.handle_no_permission()
            if not self.request.user.groups.filter(name="FinanceGrp").exists():
                # Redirect the user to somewhere else - add your URL here
                return HttpResponseRedirect(...)
    
            # Checks pass, let http method handlers process the request
            return super().dispatch(request, *args, **kwargs)
    

提交回复
热议问题