Проблема в реализации удаления с ajax django
Я еще только знакомлюсь с AJAX, реализовал удаление комментариев, но возникли проблемы:
1)Когда я удаляю комментарий, в терминале пишет, что было два запроса, хотя должен быть один:
[25/Apr/2020 16:39:40] "DELETE /post/slug-of-post/409/comment-remove/ HTTP/1.1" 200 17319
[25/Apr/2020 16:39:40] "DELETE /post/slug-of-post/409/comment-remove/ HTTP/1.1" 200 17319
2)После добавления новых комментариев(которые добавляются тоже через ajax), если я добавляю один комментарий все происходит как в 1пункте, а если два и больше добавленных комментария, то они не исчезают, пока я не удаляю все, или не перезагружаю страницу в ручную. В терминале пишет:
arguments '{'slug': '', 'pk': 416}' not found. 1 pattern(s) tried: ['post\\/(?P<slug>[^/]+)\\/(?P<pk>[0-9]+)\\/comment\\-remove\\/$']
[25/Apr/2020 16:50:15] "DELETE /post/slug-of-post6/415/comment-remove/ HTTP/1.1" 500 23581
Уже перепробовал все, что мог. Подскажите, в чем может быть проблема?
Views.py:
@method_decorator(login_required, name='dispatch')
class DeleteComment(View):
form_class = CommentForm()
def delete(self, request, slug, pk):
comment = Comment.objects.all()
del_com = get_object_or_404(Comment, pk=pk)
if request.user.id == del_com.author.id:
del_com.delete()
else:
raise Http404()
context = {
'comment': comment,
'form_class': self.form_class
}
if request.is_ajax():
html = render_to_string('polls/includes/comments.html',
context, request=request)
return JsonResponse({'forms': html})
return render(
request, template_name=self.template_name, context=context)
urls.py:
path('post/<str:slug>/<int:pk>/comment-remove/', views.DeleteComment.as_view(),name='comment_remove'),
ajax.js:
$(document).on('submit', '.delete-comment', function(event){
event.preventDefault();
console.log($(this).serialize());
$.ajax({
type: 'DELETE',
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
success: function(response) {
$('.comment-section').html(response['forms']);
},
error: function(rs, e) {
console.log(rs.responseText);
},
});
});
button.html
{% for parent_comment_id in comments.replies.all %}
{% if request.user.id == parent_comment_id.author.id %}
<form class="delete-comment" action="{% url 'polls:comment_remove' slug=post.slug pk=parent_comment_id.pk %}">
<button type="submit" name="button">
</button>
</form>
{% endif %}
<p class="parent-p">{{ parent_comment_id.body }}</p>
{% endfor %}