I've created a comment system for blog posts in Django (the comments are stored in a Comments
model) in which the author of the post or comment can delete a comment by clicking on the delete link below the comment, which results in a modal pop up asking for confirmation.
{% for comment in comments %}
<!-- Display comment -->
<a href="#" onclick="getCommentId(this)" data-id="{{ comment.id }}" data-toggle="modal" data-target="#exampleModalCenter">delete</a>
{% endfor %}
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Confirm Delete</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Are you sure you want to delete the comment?
</div>
<div class="modal-footer">
<form id="confirm-delete-form" action="" method="POST">
{% csrf_token %}
<button id="confirm-delete-btn" class="btn btn-danger" type="submit">Yes, Delete</button>
</form>
<button class="btn btn-secondary" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
Corresponding views.py
and urls.py
sections:
class CommentDeleteView(DeleteView):
model = Comments
success_url = '/'
path('comment/<int:pk>/delete/', CommentDeleteView.as_view(), name='comment-delete')
I'm dynamically setting the action
attribute of the form
in jquery when delete is clicked to pass the unique comment id:
function getCommentId(comment) {
var comment_id = $(comment).data("id");
var url = "{% url 'comment-delete' " + comment_id + " %}"
$("#confirm-delete-form").attr('action', url)
}
But when I click on 'Yes, Delete' button, I get:
It can be seen that the url
template tag hasn't been resolved & the current path has been prepended to it.
I've already tried this, same result.
Note: I tried hardcoding the comment id in the url
template tag like this & it works.
<form id="confirm-delete-form" action="{% url 'comment-delete' 2 %}" method="POST">
{% csrf_token %}
<button id="confirm-delete-btn" class="btn btn-danger" type="submit">Yes, Delete</button>
</form>