I am currently having some issue in deleting element with ajax in a Django Application. I have some pictures, each of them displayed in a bootstrap card. Basically, my code is kind of working, but I couldn't figure out why, for example, when I display the pictures in the card, in the first one of the list the Delete button doesn't work and, when I have multiple pictures, the delete button works but delete the first picture on the list and not the right one. I may have some mistake in fetching the IDs, but so far I couldn't find where the issue is. I post some code
views.py
def delete_uploaded_picture(request, pk):
picture = Picture.objects.get(id=pk)
if request.headers.get('x-requested-with') == 'XMLHttpRequest':
picture.delete()
return JsonResponse({})
js
const deleteForms = document.getElementsByClassName('delete_form')
deleteForms.forEach(deleteForm => deleteForm.addEventListener('click', (e)=>{
e.preventDefault();
let pk = deleteForm.getAttribute('data-pk')
const cardDiv = document.getElementById('card_div'+pk)
const clickedBtn = document.getElementById('clicked_btn'+pk)
$.ajax({
type: 'POST',
url: $("#my-url-div").data('url'),
data: {
'csrfmiddlewaretoken': csrftoken,
'pk': pk,
},
success: function(response){
$('#card_div'+pk).hide();
handleAlerts('success', 'Immagine Rimossa')
},
error: function(error){
handleAlerts('danger', 'Ops qualcosa è andato storto!')
}
})
}))
html
<div class="form-group mt-2">
<div class="row">
{% if question.picture_set.all %}
{% for pic in question.picture_set.all %}
<div class="col-lg-4 col-md-6" id="card_div{{pic.id}}">
<form action="" method="post" class="delete_form" data-pk="{{pic.id}}">
<div class="card picture_card" id="my-url-div" data-url="{% url 'main:delete_uploaded_picture' pk=pic.id %}">
<img class="card-img-top img-fluid" src="{{ pic.picture.url }}" alt="">
<div class="card-body">
<button type="button" class="btn btn-danger btn-sm waves-effect waves-light delete_picture" id="clicked_btn{{pic.id}}">Elimina</button>
</div>
</div>
</form>
</div>
{% endfor %}
{% endif %}
</div>
</div>
I inspected the html and the IDs are right in the card, so it's something else.
