Deleting objects in django tastypie

烂漫一生 提交于 2019-12-04 01:42:35

问题


I have the following models:

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)

A poster can make a post and other posters can comment on that post. Kind of like how a blog works. I would like to make it so that the post owner has the option to delete his own comments and the comments of other posters on his post.

How can I go about doing this?

I'm currently using Django Tastypie. Here is my current resource:

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

This works however! this allows any user to delete any comment even if its not their own which is not good! How?

By simply sending a DELETE request to: myapp.com:8000/v1/posts/comment-delete/8/ it deletes the Comment object that has an id of 8. This is where the setup is failing.

I need a way so that only the post owner of the post can delete his comments and the comments of others on his post.


回答1:


This is best enforced with Authorization.

You need to implement the delete_detail method to return True or False, for example:

def delete_detail(self, object_list, bundle):
    return bundle.obj.user == bundle.request.user



回答2:


As explained in the tastyie cookbook. Maybe you can do something like this:

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)


来源:https://stackoverflow.com/questions/18280672/deleting-objects-in-django-tastypie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!