您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在基于Django类的视图上使用Permission_required装饰器

如何在基于Django类的视图上使用Permission_required装饰器

CBV文档中列出了一些策略:

在你的urls.py路线中添加装饰器,例如,login_@R_419_1117@(ViewSpaceIndex.as_view(..))

dispatch用以下方法装饰你的CBV 方法method_decorator

from django.utils.decorators import method_decorator

@method_decorator(login_@R_419_1117@, name='dispatch')
class ViewSpaceIndex(TemplateView):
    template_name = 'secret.html'

在Django 1.9之前,你不能method_decorator在该类上使用它,因此你必须重写该dispatch方法

class ViewSpaceIndex(TemplateView):

    @method_decorator(login_@R_419_1117@)
    def dispatch(self, *args, **kwargs):
        return super(ViewSpaceIndex, self).dispatch(*args, **kwargs)

使用Django 1.9+中提供的django.contrib.auth.mixins.Login@R_419_1117@Mixin这样的访问混合器,并在此处的其他答案中对此进行了概述:

from django.contrib.auth.mixins import Login@R_419_1117@Mixin

class MyView(Login@R_419_1117@Mixin, View):

    login_url = '/login/'
    redirect_field_name = 'redirect_to'

TypeError文档中解释了你获得a的原因:

注意:method_decorator将 args和* kwargs作为参数传递给类中经过修饰的方法。如果你的方法不接受一组兼容的参数,它将引发TypeError异常。

Go 2022/1/1 18:23:48 有427人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶