from rest_framework.permissions import BasePermission, SAFE_METHODS class IsOwnerOrReadOnly(BasePermission): """ 只有作者本人可以修改,其他人只能查看 """ message = "You must be the owner to update" def safe_methods_or_owner(self, request, func): if request.method in SAFE_METHODS: return True return func() def has_permission(self, request, view): return self.safe_methods_or_owner( request, lambda: request.user.is_authenticated ) def has_object_permission(self, request, view, obj): return self.safe_methods_or_owner( request, lambda: obj.author == request.user # 验证当前评论的作者和当前登录的用户是否为同一个人 )