Я пытаюсь создать диалоговое окно подтверждения удаления, используя модальные окна начальной загрузки 5 в моем проекте Django.
{% extends 'base.html' %}
{% block content %}
<div class = "col-md-6 offset-md-3">
{% if messages %}
{% for message in messages %}
<div class = "alert alert-success alert-dismissible fade show" role = "alert">
{{ message }}
<button type = "button" class = "btn-close" data-bs-dismiss = "alert" aria-label = "Close"></button>
</div>
{% endfor %}
{% endif %}
</div>
<h1>Service Overview</h1>
<br/>
<div class = "d-grid gap-2 justify-content-md-end">
<a class = "btn btn-primary" href = "{% url 'add_service' %}">Add service</a>
<br/>
</div>
<table class = "table table-hover table-bordered">
<thead class = "table-secondary">
<tr>
<th class = "text-center" scope = "col">#</th>
<th scope = "col">Name</th>
<th scope = "col">Description</th>
<th class = "text-center" scope = "col">Cost</th>
<th class = "text-center" scope = "col">Created at</th>
<th class = "text-center" scope = "col">Updated at</th>
<th class = "text-center" scope = "col">Status</th>
<th class = "text-center" scope = "col">Actions</th>
</tr>
</thead>
<tbody>
{% for service in services %}
<tr>
<td class = "text-center">{{ service.id }}</td>
<td>{{ service.name }}</td>
<td>{{ service.description}}</td>
<td class = "text-center">{{ service.cost }} AED</td>
<td class = "text-center">{{ service.created_date }}</td>
<td class = "text-center">{{ service.updated_date }}</td>
{% if service.status == "ACTIVE" %}
<td class = "text-center">
<span class = "badge text-bg-success" style = "font-size:0.7em;">{{ service.status }}</span>
</td>
{% elif service.status == "INACTIVE"%}
<td class = "text-center">
<span class = "badge text-bg-danger" style = "font-size:0.7em;">{{ service.status }}</span>
</td>
{% endif %}
<td class = "text-center">
<!--Update-->
<a href = "{% url 'service_record' service.id %}" class = "text-decoration-none">
<button type = "button" class = "btn btn-warning btn-sm" data-bs-toggle = "tooltip" title = "Update service">
<i class = "bi bi-pencil-fill"></i>
</button>
</a>
<!--Delete modal-->
<!-- Button trigger modal -->
<button type = "button" class = "btn btn-danger btn-sm" data-bs-toggle = "modal" data-bs-target = "#DeleteDialogueModal">
<i class = "bi bi-trash"></i>
</button>
<!-- Modal -->
<div class = "modal fade" id = "DeleteDialogueModal" tabindex = "-1" aria-labelledby = "modal-title" aria-hidden = "true">
<div class = "modal-dialog" role = "document">
<div class = "modal-content">
<div class = "modal-header">
<h1 class = "modal-title fs-5" id = "modal-title">Delete service: {{ service.name }}</h1>
<button type = "button" class = "btn-close" data-bs-dismiss = "modal" aria-label = "Close"></button>
</div>
<div class = "modal-body">
<p>Are you sure to delete the service {{ service.name }} ?</p>
</div>
<div class = "modal-footer">
<button type = "button" class = "btn btn-secondary" data-bs-dismiss = "modal">Go back</button>
<a class = "btn btn-danger" href = "{% url 'delete_service' service.id %}">Yes, delete</a>
</div>
</div>
</div>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock content %}
{% block javascripts %}
<script>
// Alert when trying to delete a product
const myModal = document.getElementById('myModal')
const myInput = document.getElementById('myInput')
myModal.addEventListener('shown.bs.modal', () => {
myInput.focus()
})
</script>
{% endblock javascripts %}
Когда я нажимаю кнопку «Корзина», диалоговое окно открывается, как и ожидалось, но кажется, что идентификатор принимается неправильно. Модальное тело всегда содержит имя первого элемента в базе данных, а URL-адрес также указывает только на первый идентификатор в базе данных.
Например, я нажимаю на корзину в строке 9, но URL содержит 7. Я заметил, что после нажатия первая строка (ID 7) становится серой. Скриншот
Проблема, с которой вы столкнулись, заключается в том, что вы создаете n
диалоги для n
сервисов, и все они имеют одинаковый идентификатор, поэтому обычно, когда он хочет его открыть, открывается первый диалог.
Для этого есть два решения: первое — самое простое, но не очень хорошее по производительности, а второе — элегантное и его гораздо проще поддерживать.
Первое решение Измените диалог id
для каждого диалога, например
<div class = "modal fade" id = "DeleteDialogueModal_{{service.id}}" tabindex = "-1" aria-labelledby = "modal-title" aria-hidden = "true">
и измените кнопку корзины на
<button type = "button" class = "btn btn-danger btn-sm" data-bs-toggle = "modal" data-bs-target = "#DeleteDialogueModal_{{service.id}}">
<i class = "bi bi-trash"></i>
</button>
Таким образом, у вас будет n диалогов, каждый из которых будет иметь отдельный идентификатор и будет переключаться соответствующей кнопкой.
Второе решение Второе решение — создать один диалог, и вы меняете его содержимое с помощью Javascript в зависимости от нажатой кнопки, что-то вроде
function confirm_delete(id,name)
{
$("#model-title").html("Delete " + name);
$("#model-body").html("Are you sure you want to delete " + name + "?");
$("#modal").modal();
}
Также обновите элемент привязки, указав идентификатор службы.
наконец в вашем шаблоне на кнопке удаления
<button type = "button" class = "btn btn-danger btn-sm" data-bs-toggle = "modal" onclick = "confirm_delete({{service.id}},'{{service.name}}')">
<i class = "bi bi-trash"></i>
</button>
Первое решение работает отлично. Спасибо