python-3.x 未调用权限类方法def has_object_permission

dsf9zpds  于 8个月前  发布在  Python
关注(0)|答案(1)|浏览(87)

问题是任何用户都可以删除其他用户创建的评论,即使我创建并添加了自定义的permission.py文件,我也检查了def has_object_permission方法没有运行,我试图在终端上打印“print statement”。我希望只有评论的所有者可以删除它自己的评论和帖子的所有者可以删除任何人的评论。我的观点:

class CommentPostApiView(generics.ListCreateAPIView, generics.DestroyAPIView,generics.GenericAPIView):
    serializer_class = serializers.CommentPostSerializer
    authentication_classes = (TokenAuthentication,)
    permission_classes = [IsAuthenticated, IsCommentOwnerOrPostOwner]
    def get_queryset(self):
        post_id = self.kwargs.get('post_id')
        return models.CommentPost.objects.filter(post__pk=post_id, reply_to_comment__isnull=True)

    @transaction.atomic
    def create(self, request, *args, **kwargs):
        post_id = self.kwargs.get('post_id')
        parent_comment_id = self.kwargs.get('parent_comment_id')
        user = self.request.user
        content = request.data.get('content')

        try:
            post = models.PicPost.objects.select_for_update().get(pk=post_id)

            if parent_comment_id is not None:
                reply_to_comment = models.CommentPost.objects.select_for_update().get(pk=parent_comment_id)
                comment_post = models.CommentPost(post=post, commenter=user, content=content, reply_to_comment=reply_to_comment)
            else:
                comment_post = models.CommentPost(post=post, commenter=user, content=content)
            
            comment_post.save()
            models.PicPost.objects.filter(pk=post_id).update(comments_count=F('comments_count')+1)
        except models.PicPost.DoesNotExist:
            raise ValidationError("Post does not exist.")
        except models.CommentPost.DoesNotExist:
            raise ValidationError("Parent comment does not exist.")

        return Response({"detail": "Comment added successfully."}, status=status.HTTP_201_CREATED)
    
    @transaction.atomic
    def destroy(self, request, *args, **kwargs):
        comment_id = self.kwargs.get('parent_comment_id')

        try:
            comment = models.CommentPost.objects.select_for_update().get(pk=comment_id)
            post_id = comment.post.id
            comment.delete()
            models.PicPost.objects.filter(pk=post_id).update(comments_count=F('comments_count')-1)
        except models.CommentPost.DoesNotExist:
            raise ValidationError("This comment does not exists")
        return Response({"detail": "Comment deleted successfully."}, status=status.HTTP_201_CREATED)
**Custom Permission file**
class IsCommentOwnerOrPostOwner(permissions.BasePermission):
    """Allow owners of comment, reply or post to delete them"""

    def has_object_permission(self, request, view, obj):
        print("Checking permissions for user:", request.user)
        print("Comment owner:", obj.commenter)
        print("Post owner:", obj.post.user)
        return request.user == obj.commenter or obj.post.user == request.user
**urls.py**
path('post-comment/<int:post_id>/', views.CommentPostApiView.as_view(), name='add_top_level_comment'),
    path('post-comment/<int:post_id>/<int:parent_comment_id>/', views.CommentPostApiView.as_view(), name='add_reply_to_comment'),
flmtquvp

flmtquvp1#

来自Django REST框架文档

DjangoObject酒店

这个权限类绑定到Django的标准[object permissions framework][objectpermissions],它允许对模型进行每个对象的权限。为了使用该权限类,您还需要添加一个支持对象级权限的权限后台,例如django-guardian

相关问题