[英]How do I set permissions for POST requests in Django REST Framework?
I've got two Django models that are linked like this: 我有两个像这样链接的Django模型:
class ParentModel(models.Model):
creator = models.ForeignKey(User, related_name='objects')
name = models.CharField(max_length=40)
class ChildModel(models.Model):
parent = models.ForeignKey(ParentModel, related_name='child_objects')
name = models.CharField(max_length=40)
Now, when making ViewSet for child model, I want it to be created only if its parent was created by the same user that is creating child instance. 现在,在为子模型创建ViewSet时,我希望仅在其父项由创建子实例的同一用户创建时才创建它。 The permission class that I'm including into my
ChildViewSet(viewsets.ModelViewSet)
looks like this: 我包含在我的
ChildViewSet(viewsets.ModelViewSet)
的权限类如下所示:
class IsOwner(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True
return obj.parent.creator == request.user
This seems to work just fine when i use PATCH
method, but POST
methods don't seem to notice this permission class even when I explicitly set return False
for POST
method. 这似乎当我使用工作得很好
PATCH
方法,但POST
好像方法不当时我明确地设置此权限类察觉return False
为POST
方法。
What am I doing wrong and how to fix it? 我做错了什么以及如何解决?
Thanks to wim for providing me with a hint to an answer! 感谢wim为我提供答案的提示!
The reason why my permission didn't work with POST
requests is, indeed, that the object has not yet been created and so I should use has_permission
in my permission class. 我的权限不适用于
POST
请求的原因确实是该对象尚未创建,因此我应该在我的权限类中使用has_permission
。 Here's the code that worked for me: 这是适合我的代码:
def has_permission(self, request, view):
user_id = getattr(request.user, 'id')
parent_id = request.data['parent']
if parent_id is not None:
parent_obj = ParentModel.objects.get(id=parent_id)
serialized = ParentSerializer(association)
return user_id == serialized.data['creator']
return False
It's hard to know for sure without seeing your urls and views, but please look at the default methods implemented in BasePermission
which you inherit: 如果没有看到您的网址和视图,很难确定,但请查看您继承的
BasePermission
中实现的默认方法:
def has_permission(self, request, view):
"""
Return `True` if permission is granted, `False` otherwise.
"""
return True
def has_object_permission(self, request, view, obj):
"""
Return `True` if permission is granted, `False` otherwise.
"""
return True
For PATCH
you're working with an object which already exists, and you go into the custom method that you've overridden - OK! 对于
PATCH
你正在处理一个已经存在的对象,然后你进入你已经覆盖的自定义方法 - 好的! For POST
, you may be hooking into the other one, because you're creating a new object. 对于
POST
,您可能会挂钩到另一个,因为您正在创建一个新对象。
So, try implementing has_permission
in your derived class. 因此,尝试在派生类中实现
has_permission
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.