首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >@method_decorator与login_required和permission_required

@method_decorator与login_required和permission_required
EN

Stack Overflow用户
提问于 2015-04-16 11:37:30
回答 1查看 13.1K关注 0票数 9

我使用的是基于类的视图,其中我希望确保每个视图都可以由登录用户和一种类型的用户访问(有两组用户--每个组具有不同的权限)。

我是根据附带任务的文档实现的(我使用Django 1.7.7) https://docs.djangoproject.com/en/1.7/topics/class-based-views/intro/#decorating-the-class,但是使用两个参数会引发一个错误“method_decorator()正好带了一个参数(2给定)”。

因此-如何在基于类的视图中验证这两个因素(登录和权限)?

代码语言:javascript
复制
class PatientCreate(CreateView):
    model = Patient
    fields = '__all__'

    @method_decorator(login_required, permission_required('patient.session.can_add_patient'))
    def dispatch(self, *args, **kwargs):
        return super(PatientCreate, self).dispatch(*args, **kwargs)

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-04-16 11:40:51

在您的示例中,对于未登录的用户,permission_required将重定向到登录页面,因此根本不需要使用login_required

代码语言:javascript
复制
@method_decorator(permission_required('patient.session.can_add_patient')
def dispatch(self, *args, **kwargs):
    ...

如果您确实需要使用多个装饰器,那么可以在Django 1.9+中使用一个列表

代码语言:javascript
复制
decorators = [other_decorator, permission_required('patient.session.can_add_patient')] 

class PatientCreate(CreateView):
    model = Patient
    fields = '__all__'

    @method_decorator(decorators)
    def dispatch(self, *args, **kwargs):
        ...

还可以通过装饰类本身来缩短代码:

代码语言:javascript
复制
@method_decorator(decorators, name="dispatch")
class PatientCreate(CreateView):
    model = Patient
    fields = '__all__'

在Django 1.8和更早版本中,您不能将列表传递给method_decorator或装饰类,所以必须将装饰器堆叠起来

代码语言:javascript
复制
class PatientCreate(CreateView):
    model = Patient
    fields = '__all__'

    @method_decorator(other_decorator)
    @method_decorator(permission_required('patient.session.can_add_patient'))
    def dispatch(self, *args, **kwargs):
        ...

装饰者将按照传递给method_decorator的顺序处理请求。因此,对于上面的示例,other_decorator将在permission_required之前运行。

票数 18
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29673549

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档