首页 > 解决方案 > 使用 LoginRequiredMixin 在 dispatch 方法中执行代码

问题描述

class HomeView(LoginRequiredMixin, TemplateView):
    template_name = 'home.html'

    # Variant 1
    def dispatch(self, request, *args, **kwargs):

        # Do some other checks after making sure the user is logged in
        # This does not work because the LoginRequiredMixin
        # will be executed after calling the super method

        return super().dispatch(self, request, *args, **kwargs)

    # Variant 2
    def dispatch(self, request, *args, **kwargs):
        response = super().dispatch(self, request, *args, **kwargs)

        # Do some other checks after making sure the user is logged in
        # This does not work because this part will be also executed
        # if the user is not logged in

        return response

用户使用基于类的视图和 LoginRequiredMixin 登录后,如何在调度方法中执行代码?

标签: pythondjango

解决方案


您应该将UserPassesTestMixintest_func()包含您的逻辑的方法一起使用。您根本不需要覆盖dispatch

class HomeView(UserPassesTestMixin, TemplateView):
    ...
    def test_func(self):
        return self.request.user.is_authenticated and my_custom_logic(self.request.user)

推荐阅读