I want to add a delete confirmation modal after clicking on a delete button on a table, generated by a number of objects from a Django view:
...
{% for i in items %}
<tr>
<td>{{ i.name }}</td>
<td><a href="#" data-bs-toggle="modal" data-bs-target="#modal-delete-item">Delete</a></td>
</tr>
{% endfor %}
....
What I have in the modal is something like this:
<div id="modal-delete-item" tabindex="-1" role="dialog" aria-hidden="true">
....
<button href="{% url 'remove_quote_item' i.pk %}" type="button" data-bs-dismiss="modal">Oui, je confirme.</button>
....
</div>
How can I use the "i" variable in the modal since I am outside the loop, can I use anything to reference that variable into the modal? Or probably use javascript to perform that action? Or is there something I can do with jinja itself?
Thanks!
CodePudding user response:
Best Practice
Use Ajax to send a request to the server with the id number you want to delete.
Bad Practice
It is Bad Practice but you can solve this issue.
{% for i in items %}
<tr>
<td>{{ i.name }}</td>
<td><a href="#" data-bs-toggle="modal" data-bs-target="#modal-delete-item-{{ i.id }}">Delete</a></td>
</tr>
...........
<div id="modal-delete-item-{{ i.id }}" tabindex="-1" role="dialog" aria-hidden="true">
....
<button href="{% url 'remove_quote_item' i.id %}" type="button" data-bs-dismiss="modal">Oui, je confirme.</button>
....
</div>
.........
{% endfor %}
CodePudding user response:
- Use ajax to send request to server with id as data.
- in delete function of view.py, return 0 if record with given id is deleted from database or return 1 if not deleted or any other error occurs.
- create a hidden div element above the table, if response is 0 then remove that row from table using and show that div element both using javascript.