Use LoginRequiredMixin and UserPassesTestMixin at the same time

Mil*_*vic 5 django mixins django-views python-3.x

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

from django.views.generic import TemplateView
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin

class FinanceOverview(LoginRequiredMixin, UserPassesTestMixin, TemplateMixin):
    login_url = '/login'
    redirect_field_name = 'next'

    def test_func(self):
        return self.request.user.groups.filter(name="FinanceGrp").exists()

    def get(self, request, *args, **kwargs):
        DO SOMETHING IF USER IS AUTHENTICATED AND ALSO MEMBER OF GROUP FinanceGrp
Run Code Online (Sandbox Code Playgroud)

Basically as you can see above, what I want to achieve is the following:

In my case users are always redirected to /login page when they fail the group test. How can I achieve two mixins used at the same time but at the same time both of them are clashing around variable login_url. Unfortunately UserPassesTestMixin is using the same login_url so it makes this trouble for me.

Thanks in advance

Milos

sol*_*oke 4

我认为您最好进行子类化AccessMixin,然后自己执行这些检查。像这样的东西:

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)
Run Code Online (Sandbox Code Playgroud)