0

I want to update and delete post and it is happening but now I want users to Update and delete a post only created by them. Strating from delete this is my delete function

def delete_post(request , id):
        post=Post.objects.get(pk=id)
        if request.user==post.user: '''I think this if is not true even when the post is created by the same user who is requesting to delete it.'''
            post.delete()
            print("ok")  
        return redirect("home")

Now when click on delete post it returns to home page but the post remains same.it doesn't delete the post.

Jnilj
  • 51
  • 5
  • Are you checking correctly ? Does ```Post``` model has a ```user``` ? Could you post Post model. – Ram Aug 15 '21 at 17:13
  • See https://stackoverflow.com/questions/1227121/compare-object-instances-for-equality-by-their-attributes – jarmod Aug 15 '21 at 17:14
  • @jarmod, What's the relation between the question and the link you provided ? – Lars Aug 15 '21 at 17:17
  • @PrOgRaMmEr I'm assuming that both request.user and post.user are (likely) distinct objects representing the same user. They're not equal, unless the underlying User class correctly implements `__eq__` (for example to define equality based on user ID). – jarmod Aug 15 '21 at 17:20
  • yes post model have user user = models.ForeignKey(Author, on_delete=models.CASCADE) – Jnilj Aug 15 '21 at 17:20

2 Answers2

0

Try this in more cleaner way

@login_required
def delete_post(request , id):
    try:
        Post.objects.filter(pk=id, user=request.user).delete()
    except Exception:
        raise NotFoundError('The post you are trying to delte not found')
    return redirect("home")

No one can delete another user created post this way

  • @JyotiJha If it works, please accept the answer and make an upvote, thank you –  Aug 15 '21 at 17:36
0

If request.user is not the post.owner, then it will not delete the post, but it will make a redirect to the home view.

Normally one should not create, update or remove items with a GET request, since GET requests are supposed to be safe and only retrieve data. You thus should limit this view to a POST request (or perhaps a POST or DELETE request).

You can work with the get_object_or_404(…) function [Django-doc] to return a HTTP 404 response in case the object does not exist, or is not owned by the current user:

from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST

@login_required
@require_POST
def delete_post(request , id):
    post = get_object_or_404(Post, pk=id, owner=request.user).delete()
    return redirect('home')

Note: You can limit views to a view to authenticated users with the @login_required decorator [Django-doc].


Note: You can limit views to POST requests with the @require_POST decorator [Django-doc].

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555