3

我有以下型号:

class Poster(models.Model)
     user = models.OneToOneField(User, primary=True)
     userpicture = models.CharField(max_length = 128 =True)

class Posts(models.Model)
     poster = models.ForeignKey(Poster, related_name = 'post_owner')
     url = models.CharField(max_length = 128)
     time = models.DateTimeField(auto_now_add=True)

class Comment(models.Model):
     user = models.ForeignKey(Poster)
     post = models.ForeignKey(Posts)
     time = models.DateTimeField(auto_now_add=True)
     comment = models.CharField(max_length=140)

发帖人可以发帖,其他发帖人可以对该帖发表评论。有点像博客的运作方式。我想让帖子所有者可以选择删除他自己的评论和其他发帖者在他的帖子上的评论。

我该怎么做呢?

我目前正在使用 Django Tastypie。这是我目前的资源:

class DeleteComment(ModelResource):
     class Meta:
          queryset = Comment.objects.all()
          allowed_methods = ['delete']
          resource_name = 'comment-delete'
          excludes = ['id', 'comment', 'post', 'time']
          authorization = Authorization()
          authentication = BasicAuthentication()
          include_resource_uri = False
          always_return_data = True

但是,这有效!这允许任何用户删除任何评论,即使它不是他们自己的,这不好!如何?

只需向myapp.com:8000/v1/posts/comment-delete/ 8发送DELETE请求,它就会删除ID8的Comment对象。这是设置失败的地方。

我需要一种方法,以便只有帖子的帖子所有者才能删除他的评论和其他人在他的帖子上的评论。

4

2 回答 2

3

最好通过Authorization强制执行。

您需要实现delete_detail返回 True 或 False 的方法,例如:

def delete_detail(self, object_list, bundle):
    return bundle.obj.user == bundle.request.user
于 2014-01-21T10:20:39.587 回答
2

美味食谱中所述。也许你可以做这样的事情:

class DeleteComment(ModelResource):

    def obj_delete(self, bundle, **kwargs):
         # get post id
         comment = Comment.objects.get(pk=bundle.data.id) # or or whatever way you can get the id
         # delete all comments with that post id
         Comment.objects.filter(post=comment.post).delete()
         return super(DeleteComment, self).obj_delete(bundle, user=bundle.request.user)

    def apply_authorization_limits(self, request, object_list):
        return object_list.filter(user=request.user)
于 2013-08-16T19:50:03.877 回答