django user_passes_test装饰者

时间:2011-11-10 16:17:45

标签: python django

如何为基于类的视图实现@user_passes_test(lambda u: u.is_superuser)装饰器?我之前使用过这个基于功能的视图,我有一个解决方法,但感觉不自然。

这不应该由调度方法涵盖吗?

4 个答案:

答案 0 :(得分:35)

您在班级的@method_decorator方法中使用dispatch

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)

答案 1 :(得分:22)

基于@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或您在应用中使用的任何其他常见测试。

编辑: Django 1.9添加了AccessMixin,LoginRequiredMixin,PermissionRequiredMixin和UserPassesTestMixin

答案 2 :(得分:1)

我使用了这段代码中的@view_decorator:http://djangosnippets.org/snippets/2505/来包装我的普通函数装饰器。

答案 3 :(得分:1)

您应该查看django-braces及其UserPassesTestMixin

相关问题