栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

  1. 在你的

    urls.py
    路线中添加装饰器,例如,
    login_required(ViewSpaceIndex.as_view(..))

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

from django.utils.decorators import method_decorator@method_decorator(login_required, name='dispatch')class ViewSpaceIndex(TemplateView):    template_name = 'secret.html'

在Django 1.9之前,你不能

method_decorator
在该类上使用它,因此你必须重写该
dispatch
方法:

class ViewSpaceIndex(TemplateView):    @method_decorator(login_required)    def dispatch(self, *args, **kwargs):        return super(ViewSpaceIndex, self).dispatch(*args, **kwargs)

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

from django.contrib.auth.mixins import LoginRequiredMixinclass MyView(LoginRequiredMixin, View):    login_url = '/login/'    redirect_field_name = 'redirect_to'

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

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/372828.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号