2024-05-17 11:35:24 发布
网友
如何为基于类的视图实现@user_passes_test(lambda u: u.is_superuser)decorator?我以前在基于函数的视图中使用过这个,我有一个解决方法,但是感觉不自然。
@user_passes_test(lambda u: u.is_superuser)
这不应该包含在分派方法中吗?
我使用了这个代码片段中的@view\u decorator:http://djangosnippets.org/snippets/2505/来包装我的普通函数decorators。
基于@Chris Pratt的答案,您可能希望在多个视图类中执行此操作,因此将其转换为mixin是有意义的。
class SuperuserRequiredMixin(object): @method_decorator(user_passes_test(lambda u: u.is_superuser)) def dispatch(self, *args, **kwargs): return super(SuperuserRequiredMixin, self).dispatch(*args, **kwargs)
用法
class MyView(SuperuserRequiredMixin, View): def get(self, request): ...
为了防止意外的MRO错误,请确保mixin是第一个继承的类。
您可以用同样的方法实现一个LoginRequiredMixin,或者您在应用程序中使用的任何其他常见测试。
LoginRequiredMixin
编辑:Django 1.9添加AccessMixin、LoginRequiredMixin、PermissionRequiredMixin和userPasseTestMixin
对类的dispatch方法使用@method_decorator:
dispatch
@method_decorator
from django.views.generic import View from django.utils.decorators import method_decorator from django.contrib.auth.decorators import user_passes_test class MyView(View): @method_decorator(user_passes_test(lambda u: u.is_superuser)) def dispatch(self, *args, **kwargs): return super(MyView, self).dispatch(*args, **kwargs)
我使用了这个代码片段中的@view\u decorator:http://djangosnippets.org/snippets/2505/来包装我的普通函数decorators。
基于@Chris Pratt的答案,您可能希望在多个视图类中执行此操作,因此将其转换为mixin是有意义的。
用法
为了防止意外的MRO错误,请确保mixin是第一个继承的类。
您可以用同样的方法实现一个
LoginRequiredMixin
,或者您在应用程序中使用的任何其他常见测试。编辑:Django 1.9添加AccessMixin、LoginRequiredMixin、PermissionRequiredMixin和userPasseTestMixin
对类的
dispatch
方法使用@method_decorator
:相关问题 更多 >
编程相关推荐