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.
2
Answers
// Delete Data
========= Output ==============
Probably you should change this line:
To:
Generally in function are you querying objects using className, so it returns multiple object and overrides only one. In
e.currentTarget
you have element that you clicked, so it does not select it via random way.Basically I am not sure if the forloop assign is working correctly, the javascript does it own magic in forloops (for example – it makes them asynchrous) so I would not be suprised it does not work as expected and the value you are getting into
pk
is not that you want.