I am currently utilizing a bootstrap modal to display a list of object instances and execute CRUD operations. To achieve this, I enclosed the entire list within a form and utilized buttons with names and values to pass on the id of each individual object instance to the view. My objective is to manipulate (CRUD) one object instance at a time. Interestingly, the view functions as expected when deleting objects without the use of JavaScript. However, once I introduce e.preventDefault();
into the code, the request no longer captures the id of the selected object.
What could be causing this unexpected behavior?
To provide more context, the template structure is as follows:
<form
action="{% url 'delete_habit' %}"
method="POST"
id="deleteForm">{% csrf_token %}
<div class="row">
<div class="col-12 pb-3">
<table class="modal-table border" id="habitsTable">
<tbody>
{% for habit in habits %}
<tr class="border js-row-{{habit.id}}">
<td class="border">
<img src="{% static 'img/bars_icon.svg' %}">
</td>
<td class="text-left border px-3">{{habit.name}}</td>
<td class="border">
<button
id="delete-{{habit.id}}"
type="submit"
value="{{habit.id}}"
name="habit_id"
class="btn">
<img src="{% static 'img/minus_icon.svg' %}">
</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</form>
The associated view function is as follows:
def delete_habit(request):
habit_id = request.POST.get('habit_id') --> this fails when e.preventDefault()
data = {'habit_deleted': int(habit_id)}
habit_to_delete = Habit.objects.filter(id=int(habit_id)).filter(
user=request.user)
habit_to_delete.delete()
return JsonResponse(data)
Here is the relevant JavaScript snippet:
var deleteForm = document.getElementById('deleteForm');
if (deleteForm !== null){
deleteForm.addEventListener('submit', function(e){
var formData = new FormData(deleteForm);
e.preventDefault();
var request = new XMLHttpRequest();
request.open(deleteForm.method, deleteForm.action, true);
var cookies = parse_cookies();
request.setRequestHeader('X-CSRFToken', cookies['csrftoken']);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
var data = JSON.parse(this.response);
removeRow("js-row-" + data.habit_deleted);
};
};
request.send(formData);
});
};
The inclusion of e.preventDefault()
appears to be causing the issue, as it prevents the successful retrieval of the selected habit's id during the request process.