我使用Django Rest Framework,在我的一个viewset类中,我有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但我不确切知道我必须做什么.
谢谢你的帮助:D
解决了:
permissions.py类:
class IsUpdateProfile(permissions.BasePermission):
def has_permission(self, request, view):
# can write custom code
print view.kwargs
try:
user_profile = Profile.objects.get(
pk=view.kwargs['pk'])
except:
return False
if request.user.profile == user_profile:
return True
return False
views.py:
class ProfileViewSet(viewsets.ModelViewSet):
queryset = Profile.objects.all()
# serializer_class = ProfileSerializer
permission_classes = (IsAuthenticated,)
http_method_names = ['get', 'patch', 'delete']
...
def get_permissions(self):
...
if self.request.method == 'PATCH':
self.permission_classes = (IsAuthenticated, IsUpdateProfile)
return super(ProfileViewSet, self).get_permissions()
def partial_update(self, request, pk=None):
...
最佳答案 IsOwnerOrReject是将用户与当前登录用户匹配的权限类,否则拒绝.
在您的情况下,您必须定义自定义权限类.哪个检查用户登录其他配置文件您想要应用的权限.你可以这样做:
class IsUpdateProfile(permissions.BasePermission):
def has_permission(self, request, view):
#### can write custom code
user = User.objects.get(pk=view.kwargs['id']) // get user from user table.
if request.user == user:
return True
## if have more condition then apply
if more_condition:
return True
return False