我想安排权限,例如每个用户都可以编辑自己的个人资料。只有超级用户才能编辑所有个人资料我需要添加 permissions.py ?谢谢。
views.py
class UserViewSet(mixins.ListModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
generics.GenericAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = [IsAuthenticated]
authentication_classes = (JSONWebTokenAuthentication, )
permissions.py
class IsOwnerOrReadOnly(BasePermission):
message = '!!'
my_safe_method = ['GET', 'PUT']
def has_permission(self, request, view):
if request.method in self.my_safe_method:
return True
return False
def has_object_permission(self, request, view, obj):
# member .0 Membership.objects.get(user=request.user)
# member.is_active
if request.method in SAFE_METHODS:
return True
return obj.user == request.user
答案 0 :(得分:1)
写下你自己的许可
class IsObjectOwner(BasePermission):
message = "You must be the owner of this object."
my_safe_methods = ['GET', 'PUT', 'PATCH', 'DELETE']
def has_permission(self, request, view):
if request.method in self.my_safe_methods:
return True
return False
def has_object_permission(self, request, view, obj):
if request.user.is_superuser:
return obj
else:
return obj == request.user
然后在view
中添加permission_classes
class UserDetailView(RetrieveUpdateDestroyAPIView):
permission_classes = [IsObjectOwner, permissions.IsAuthenticated]