gpt4 book ai didi

对 POST 的 Django Rest Framework 对象级权限

转载 作者:行者123 更新时间:2023-12-04 04:25:19 26 4
gpt4 key购买 nike

我想确保 request.user 只能发出 POST 请求来创建他们是作者的论坛主题。使用 PUT 和 DELETE,我可以通过使用 has_object_permission 来实现这一点。但是使用 POST 我无法做到这一点,我猜是因为尚未创建对象。

class TopicPermission(IsAuthenticatedOrReadOnly):
"""
Any user should be able to read topics but only authenticated
users should be able to create new topics. An owner or moderator
should be able to update a discussion or delete.
"""
def has_object_permission(self, request, view, obj):
if request.method in SAFE_METHODS:
return True

# Instance must have an attribute named `author` or moderator
return obj.author == request.user or request.user.forum_moderator

我将如何验证 request.user == obj.author在 POST 请求中?

最佳答案

我最终在 View 集中而不是序列化程序中进行验证:

class TopicViewSet(viewsets.ModelViewSet):
permission_classes = (TopicPermission, )
queryset = Topic.objects.all()
serializer_class = TopicSerializer

def create(self, request, *args, **kwargs):
"""
verify that the POST has the request user as the obj.author
"""
if request.data["author"] == str(request.user.id):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=201, headers=headers)
else:
return Response(status=403)

关于对 POST 的 Django Rest Framework 对象级权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29867290/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com