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.
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
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