python - 使用 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 登录后,如何在调度方法中执行代码?
解决方案
您应该将UserPassesTestMixin与test_func()
包含您的逻辑的方法一起使用。您根本不需要覆盖dispatch
。
class HomeView(UserPassesTestMixin, TemplateView):
...
def test_func(self):
return self.request.user.is_authenticated and my_custom_logic(self.request.user)
推荐阅读
- python - 如何在 Qt Creator 中单击按钮运行 python 程序并在 Qlabel 上显示结果
- python - 数据库行列选择问题
得到这个奇怪的回报 - reactjs - 我如何使用 history.push 代替 Link 用于反应中的嵌套路由
- php - 无论如何动态安排使用 PHP 运行 cron 作业
- node.js - 使用 mongodb 和 node js 添加“添加到购物车”功能
- java - 如何编写伪代码并绘制用于读取文本文件的跟踪表
- python - 如何使用 python 对 excel 文件的列进行样式化?(宽度、颜色等)
- android - What is navigation.json in Android Studio 4.1?
- html - 设置网站背景是google map iframe代码
- html - 更改 scss 中的悬停行为