Nicholas Dill
Nicholas Dill

Reputation: 465

Button in html that deletes an instance of a Django model

If I have a list of instances, and each instance has a button or checkbox. When you press it, it calls delete() on the instance. How would you implement this in Django?

Upvotes: 1

Views: 342

Answers (1)

qasimalbaqali
qasimalbaqali

Reputation: 2131

You'll need to create a function view that would query that exact instance that you want to delete. I have an example from my app that would query the selected comment on a post and deletes it when the user presses a delete button.

def delete_comment(request, comment_id):
    comment = get_object_or_404(Comment, id=comment_id)
    slug = slugify(comment.post.slug)
    if request.user.is_staff or comment.user == request.user:
        Comment.objects.get(id=comment_id).delete()
        messages.success(request, "Your comment was successfully deleted.")
    return HttpResponseRedirect(reverse("main.views.post", args=(slug,)))

So let me explain how does this function view work. I have a model called Comment, and that Comment model has a foriegnkey to the Post model. So each post has some comments. A user now commented on a post, and he decided to delete it. There is a delete button that redirects him to the delete_comment function view. The view tried to get the comment id, if it exists it continues, if it doesn't it returns a 404. Then it checks if the comment was made by the same user that is trying to delete it, or if the user is a staff member. Then we get the comment id, and make it the same as our function parameter comment_id so we can use that in the urls.py, as you can see we get the exact comment id and we use the delete() function to it, and that deletes the comment!

And ofcourse you'll need a url for that which would look like the following for the delete_comment view

url(r"^delete_comment/(?P<comment_id>\d+)/$", views.delete_comment, name="delete_comment"),

And here is how you write the delete button to hook it up with the view and the url

<a href="{% url "main.views.delete_comment" comment.id %}">delete</a>

As you can see the url contains where the delete function view is, and it's using the argument of the comments.id to be used in the view and the url. It's easy to implement, hope this example gave you a starting point/idea on how to start.

Upvotes: 1

Related Questions