我想在一个宁静的项目中使用django-guardian管理我的对象权限(使用django-rest-framework)。
我想要的是什么:
我正在尝试使用此代码管理这些案例:
view.py
class ModelNameViewSet(viewsets.ModelViewSet):
"""
This viewset automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions.
Additionally we also provide an extra `highlight` action.
"""
queryset = ModelName.objects.all()
serializer_class = ModelNameSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly, ModelNamePermission)
def create(self, request, *args, **kwargs):
assign_perm("change_modelname", request.user, self)
assign_perm("delete_modelname", request.user, self)
return super().create(request, *args, **kwargs)
permissions.py
class ModelNamePermission(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to edit it.
"""
def has_permission(self, request, view):
if request.method in ['GET']:
return request.user.has_perm('view_modelname')
if request.method in ['POST']:
return request.user.has_perm('add_modelname')
if request.method in ['PUT', 'PATCH']:
return request.user.has_perm('change_modelname')
if request.method in ['DELETE']:
return request.user.has_perm('delete_modelname')
return False
def has_object_permission(self, request, view, obj):
if request.method in ['GET']:
return request.user.has_perm('view_modelname', obj)
if request.method in ['POST']:
return request.user.has_perm('add_modelname', obj)
if request.method in ['PUT', 'PATCH']:
return request.user.has_perm('change_modelname', obj)
if request.method in ['DELETE']:
return request.user.has_perm('delete_modelname', obj)
return False
我遇到的第一个问题是我在这一行中有错误:
assign_perm("change_modelname", request.user, self)
错误:
error: 'ModelNameViewSet' object has no attribute '_meta'
我认为其余的代码不起作用,但至少你可以看到我想要做的事情。
我没有看到任何具体情况的例子。
编辑: 另一件事就是这段代码:
request.user.has_perm('view_coachingrequest')
总是返回true。但我从未将此权限设置为我的用户(仅限管理员用户使用,也许这就是原因)。
答案 0 :(得分:1)
视图集的create
方法将返回一个新创建的模型实例。您正在尝试将权限分配给视图集对象本身。您的create
方法的代码应如下所示:
def create(self, request, *args, **kwargs):
instance = super().create(request, *args, **kwargs)
assign_perm("change_modelname", request.user, instance)
assign_perm("delete_modelname", request.user, instance)
return instance
这将创建模型实例,然后在返回之前为其分配所需的权限。