gpt4 book ai didi

Django Rest Framework 所有者权限

转载 作者:太空宇宙 更新时间:2023-11-03 13:12:59 25 4
gpt4 key购买 nike

我使用 Django Rest Framework,在我的一个 View 集类中,我有 partial_update 方法 (PATCH) 来更新我的用户配置文件。我想为一个用户创建权限只能更新他的个人资料

class ProfileViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows profiles to be viewed, added,
deleted or edited
"""
queryset = Profile.objects.all()
# serializer_class = ProfileSerializer
permission_classes = (IsAuthenticated,)
http_method_names = ['get', 'patch']

def get_queryset(self):
user = self.request.user
return self.queryset.filter(user=user)

def get_serializer_class(self):
if self.action == 'list':
return ListingMyProfileSerializer
if self.action == 'retrieve':
return ListingMyProfileSerializer
if self.action == 'update':
return ProfileSerializer
return ProfileSerializer

def get_permissions(self):
# Your logic should be all here
if self.request.method == 'GET':
self.permission_classes = (IsAuthenticated,)
if self.request.method == 'PATCH':
self.permission_classes = (IsAuthenticated, IsOwnerOrReject)
return super(ProfileViewSet, self).get_permissions()

def partial_update(self, request, pk=None):
...
...

现在一个用户可以更新他的个人资料和任何其他个人资料。我试图创建一个权限类:IsOwnerOrReject 但我不知道我必须做什么。

最佳答案

您可以添加一个自定义权限来检查它是否是他自己的个人资料。像这样。

# permissions.py
from rest_framework import permissions
class OwnProfilePermission(permissions.BasePermission):
"""
Object-level permission to only allow updating his own profile
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True

# obj here is a UserProfile instance
return obj.user == request.user


# views.py
class ProfileViewSet(viewsets.ModelViewSet):
permission_classes = (IsAuthenticated, OwnProfilePermission,)

更新:您可以删除 def get_permissions(self): 部分。

您可以查看 documentation了解更多信息。

关于Django Rest Framework 所有者权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38718454/

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