django user_passes_test decorator

后端 未结 4 1749
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 04:39

How do I implement the @user_passes_test(lambda u: u.is_superuser) decorator for class based views? I have used this before for function based views, and I have

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-13 05:22

    You use @method_decorator on the dispatch method of the class:

    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)
    

提交回复
热议问题