我使用的是基于类的视图,其中我希望确保每个视图都可以由登录用户和一种类型的用户访问(有两组用户--每个组具有不同的权限)。
我是根据附带任务的文档实现的(我使用Django 1.7.7) https://docs.djangoproject.com/en/1.7/topics/class-based-views/intro/#decorating-the-class,但是使用两个参数会引发一个错误“method_decorator()正好带了一个参数(2给定)”。
因此-如何在基于类的视图中验证这两个因素(登录和权限)?
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)谢谢!
发布于 2015-04-16 11:40:51
在您的示例中,对于未登录的用户,permission_required将重定向到登录页面,因此根本不需要使用login_required。
@method_decorator(permission_required('patient.session.can_add_patient')
def dispatch(self, *args, **kwargs):
...如果您确实需要使用多个装饰器,那么可以在Django 1.9+中使用一个列表
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):
...还可以通过装饰类本身来缩短代码:
@method_decorator(decorators, name="dispatch")
class PatientCreate(CreateView):
model = Patient
fields = '__all__'在Django 1.8和更早版本中,您不能将列表传递给method_decorator或装饰类,所以必须将装饰器堆叠起来
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之前运行。
https://stackoverflow.com/questions/29673549
复制相似问题