使用django-rest-framework设置对象级权限 [英] Set object-level permission with django-rest-framework

查看:276
本文介绍了使用django-rest-framework设置对象级权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用django-rest-framework最干净,最规范地管理django-guardian对象级权限。

Trying to manage django-guardian object-level permissions with django-rest-framework the most cleanly and canon possible.

我想分配读取权限(模块.view_object),然后发送给执行POST时发出请求的用户。

I want to assign a read permission (module.view_object) of an object to to the user making the request when performing a POST.

基于类的视图:

class ObjectList(ListCreateAPIView):
  queryset = Object.objects.all()
  serializer_class = ObjectSerializer
  filter_backends = (DjangoObjectPermissionsFilter,)
  # MyObjectPermissions inherit from DjangoObjectPermissions and just 
  # add the 'view_model' permission
  permission_classes = (MyObjectPermissions,)

  def perform_create(self, serializer):
    serializer.save(owner=self.request.user)

django-rest-fram ework文档,为了将用户传递给序列化程序,我已经重载了 perform_create

As described in the django-rest-framework documentation, I've overloaded perform_create in order to pass the user to the serializer.

但是,如何在序列化程序中分配权限(使用guardian.shortcuts.assign_perm)。除了覆盖 save 方法以手动分配权限之外,没有其他方法吗?

But how do I assign the permission (using guardian.shortcuts.assign_perm) in the serializer. Is there no other way but to override the save method to assign the permission manually? Isn't there some kind of standard mechanism to manage a common behavior as this one?

推荐答案

您可以在其中分配权限吗? ViewSet perform_create()方法。

You can assign the permission in the perform_create() method of the ViewSet.

这篇关于使用django-rest-framework设置对象级权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆