Django UserPassesTestMixin confusion/questions?

Django UserPassesTestMixin confusion/questions?

我目前正在开发一个管理仪表板,其中仅包含公司管理员的特定视图,这些视图被标记为 Business 用户。

该应用程序将有大约 10 次浏览,我有几个关于 UserPassesTestMixin

的问题

基本上我所有的观点都会包括这个,

def test_func(self):
    return self.request.user.user_type == 'Business'

为了确保用户是 Business 用户,我以这种方式保护视图。

我自己无法解决的几个问题是:

现在重复 10 次,有没有更简洁的方法来做到这一点,而不是 def test_func 在每个 CBV 中?

出现的另一个问题是,如果用户没有通过测试,它会重定向到登录页面,我也不太喜欢这样。这些视图都返回 json。如果用户没有通过测试,我只想将他们发送到

JsonResponse({'message': 'Only company administrators have access to this view'})

仅当用户未通过测试时,我如何才能更改该重定向?请记住,这些视图也继承自 LoginRequiredMixin,如果用户未登录,我想保持原始重定向到登录页面。

非常感谢对此的任何帮助。 Django 的这一面对我来说是相当新鲜的东西!

Now with that being repeated say 10 times, is there a cleaner way to do this, rather than having def test_func in every CBV?

,你可以简单地制作一个实现检查的mixin:

from django.contrib.auth.mixins import UserPassesTestMixin

class <b>BusinessUserMixin</b>(LoginRequiredMixin, UserPassesTestMixin):
    
    def test_func(self):
        return self.request.user.user_type == 'Business'

    def <b>handle_no_permission</b>(self):
        return JsonResponse(
            {'message': 'Only company administrators have access to this view'}
        )

然后在视图中使用这个 mixin,例如:

class MyView<sub>1</sub>(<b>BusinessUserMixin</b>, ListView):
    # …
    pass

class MyView<sub>2</sub>(<b>BusinessUserMixin</b>, DetailView):
    # …
    pass

class MyView<sub>3</sub>(<b>BusinessUserMixin</b>, CreateView):
    # …
    pass

if the user doesn't pass test, it redirects to the login page, which I don't really like either. These views are all returning json. If the user does not pass test, I would like to just send them to something like.

您也可以覆盖handle_no_permission方法,当测试失败时,视图将return此方法的结果作为结果。