如何在 Django 中使用引导模式对表数据进行删除确认?

Posted

技术标签:

【中文标题】如何在 Django 中使用引导模式对表数据进行删除确认?【英文标题】:How to do Delete confirmation for a table data with bootstrap Modal in Django? 【发布时间】:2020-04-21 07:23:28 【问题描述】:

我有一个表格来显示我的应用中的操作列表。我可以删除该表中的任何操作。所以,我在每一行都添加了一个删除按钮。此删除按钮将触发“删除确认”引导模式。

<table class="table table-hover">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col" class="th-lg">Name</th>
    </tr>
  </thead>
  % for action in actions_list %
  <tbody>
    <tr class="test">
      <th scope="row" class="align-middle"> forloop.counter </th>
      <td class="align-middle">
        action.action_name
      </td>
      <td class="align-middle">
        action.id
      </td>
      <td>
        <div class="row justify-content-end">
          <button
            id="edit"
            type="button"
            class="btn btn-sm btn-dark col col-lg-2"
            style="color: rgb(255,0,0,0)"
          >
            <i class="lni-pencil"></i>
          </button>
          <button
            id="trash"
            type="button"
            class="btn btn-sm btn-dark col col-lg-2"
            style="color: rgb(255,0,0,0)"
            data-toggle="modal"
            data-target="#modalConfirmDelete"
          >
            <i class="lni-trash"></i>
          </button>
        </div>
      </td>
    </tr>
  </tbody>
  % endfor %
</table>

以下是“删除确认”引导模式的代码。它将有“是”和“否”按钮。 如果我单击“是”,则该特定操作 ID 将被传递到 URL,并且该特定操作 ID 将被删除。

% block modalcontent %

<!--Modal: modalConfirmDelete-->
<div
  class="modal fade"
  id="modalConfirmDelete"
  tabindex="-1"
  role="dialog"
  aria-labelledby="exampleModalLabel"
  aria-hidden="true"
>
  <div class="modal-dialog modal-sm modal-notify modal-danger" role="document">
    <!--Content-->
    <div class="modal-content text-center">
      <!--Header-->
      <div class="modal-header d-flex justify-content-center">
        <p class="heading">Are you sure?</p>
      </div>

      <!--Body-->
      <div class="modal-body">
        <i class="fas fa-times fa-4x animated rotateIn"></i>
      </div>

      <!--Footer-->
      <div class="modal-footer flex-center">
        <form action="% url 'delete_action' aid=action.id %">
          % csrf_token %
          <button class="btn  btn-outline-danger">Yes</button>
        </form>

        <a
          type="button"
          class="btn  btn-danger waves-effect"
          data-dismiss="modal"
          >No</a
        >
      </div>
    </div>
    <!--/.Content-->
  </div>
</div>
% endblock %

在上面的代码中,我使用 form 标记进行删除操作,然后该操作 id URL 将触发。

以下是删除操作的 URL,

re_path(r'^delete_action/(?P<aid>\d+)/',
            views.delete_action, name='delete_action')

我面临的问题: 我需要我没有得到的模态中的 action.id 值!

请帮我解决这个问题。在此先感谢:)

【问题讨论】:

【参考方案1】:

试试这个

 In your delete link

    <a href="% url 'your-delete-url' pk=your.id %" class="confirm-delete" title="Delete" data-toggle="modal" data-target="#confirmDeleteModal" id="deleteButtonyour.id">

你的模态

<div class="modal fade" id="confirmDeleteModal" tabindex="-1" caller-id="" role="dialog" aria-labelledby="confirmDeleteModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-body confirm-delete">
        This action is permanent!
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-danger" data-dismiss="modal" id="confirmDeleteButtonModal">Delete</button>
      </div>
    </div>
  </div>
</div>


<script type="text/javascript">
  $(document).on('click', '.confirm-delete', function () 
        $("#confirmDeleteModal").attr("caller-id", $(this).attr("id"));
      );

    $(document).on('click', '#confirmDeleteButtonModal', function () 
      var caller = $("#confirmDeleteButtonModal").closest(".modal").attr("caller-id");
      window.location = $("#".concat(caller)).attr("href");
    );
</script>

【讨论】:

【参考方案2】:

有关 Gorkali 答案的更多解释,您可以在这里查看:https://elennion.wordpress.com/2018/10/08/bootstrap-4-delete-confirmation-modal-for-list-of-items/

这就是我如何解决它,基于上述答案,使用纯 JavaScript,并添加更多功能:

my_template.html:

<a href="% url 'report_generate' %" 
        class="btn btn-primary" id="generate_report.id"
        data-toggle="modal" data-target="#confirmModal" 
        data-message="If you proceed, the existing report will be overwritten."
        data-buttontext="Proceed">
    Regenerate
</a>
<a href="% url 'report_generate'" 
        class="btn btn-primary" id="finalize_report.id"
        data-toggle="modal" data-target="#confirmModal" 
        data-message="If you proceed, the existing report will be finalized. After that, it can no longer be edited."
        data-buttontext="Finalize Report">
    Finalize
</a>

% include "includes/confirm_modal.html" %

包含文件confirm_modal.html:

<div class="modal fade" id="confirmModal" tabindex="-1" caller-id="" role="dialog" aria-labelledby="confirmModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-body" id="modal-message">
                Do you wish to proceed?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" data-dismiss="modal" id="confirmButtonModal">Confirm</button>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    document.addEventListener('DOMContentLoaded', () => 
        var buttons = document.querySelectorAll("[data-target='#confirmModal']");
        for (const button of buttons) 
            button.addEventListener("click", function(event) 
                // find the modal and add the caller-id as an attribute
                var modal = document.getElementById("confirmModal");
                modal.setAttribute("caller-id", this.getAttribute("id"));

                // extract texts from calling element and replace the modals texts with it
                if ("message" in this.dataset) 
                    document.getElementById("modal-message").innerHTML = this.dataset.message;
                ;
                if ("buttontext" in this.dataset) 
                    document.getElementById("confirmButtonModal").innerHTML = this.dataset.buttontext;
                ;
            )
        

        document.getElementById("confirmButtonModal").onclick = () => 
            // when the Confirm Button in the modal is clicked
            var button_clicked = event.target
            var caller_id = button_clicked.closest("#confirmModal").getAttribute("caller-id");
            var caller = document.getElementById(caller_id);
            // open the url that was specified for the caller
            window.location = caller.getAttribute("href");
        ;
    );
</script>

【讨论】:

【参考方案3】:

删除链接:

<a href="javascript:void(0)" data-toggle="modal"
                               class="confirm-delete"
                               data-url="% url 'account:delete_address' pk=address.id %"
                               data-target="#deleteItemModal"
                               data-message="Êtes-vous sûr de supprimer l'article ?"
                               >
                                <i class="far fa-trash-alt"></i>
                                <span>Supprimer</span>
                            </a>

模态:

   <!-- Modal -->
<div id="container_delete">
<div class="modal fade"  id="deleteItemModal" tabindex="-1"  role="dialog"
     aria-labelledby="deleteItemModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document"> </div>
    <div class="modal-content">

      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>

      <div class="modal-body confirm-delete text-center" >
          <div class="alert" id="delete_item_alert"></div>
          <div id="modal-message"></div>
          <hr>
          <form action="" method="post" id="form_confirm_modal">
              % csrf_token %
            <button type="button" class="btn btn-danger" data-dismiss="modal" id="confirmButtonModal">Oui</button>
            <button type="button" class="btn btn-primary" data-dismiss="modal">Non</button>
          </form>
          <input type="hidden" id="address_suppress"/>
      </div>

      </div>

    </div>
</div>

<script type="text/javascript">

    document.addEventListener('DOMContentLoaded', () => 
        let form_confirm = document.querySelector('#form_confirm_modal')
        let buttons = document.querySelectorAll("[data-target='#deleteItemModal']");
            buttons.forEach(button => 
                button.addEventListener("click", () => 

                     // extract texts from calling element and replace the modals texts with it
                    if (button.dataset.message) 
                        document.getElementById("modal-message").innerHTML = button.dataset.message;
                    
                    // extract url from calling element and replace the modals texts with it
                    if (button.dataset.url) 
                        form_confirm.action = button.dataset.url;
                    

                )
            );
       let confirmModal = document.getElementById("confirmButtonModal")
        confirmModal.addEventListener('click', () => 
            form_confirm.submit();

        );
    );
</script>

观看次数:

class DeleteAddressView(DeleteView, SuccessMessageMixin):
    template_name = 'account/address.html'
    success_message = 'Adresse supprimée'
    # model = Address

    def get_object(self, queryset=None):
        _id = int(self.kwargs.get('pk'))
        address = get_object_or_404(Address, pk=_id)
        return address

    def get_success_url(self):
        pk = self.request.user.id
        return reverse_lazy('account:address', args=(pk,))

【讨论】:

【参考方案4】:

如果你们中有人遇到这种情况,我有一个快速解决办法。

主要思想是使用 Javascript 更改表单的操作 URL

views.py

class DeleteAddressView(DeleteView):
    success_url = reverse_lazy("home")

我会尽量在这里提供最低限度的解决方案:

my link in the list for delete item will be:

<a
  href="% url 'item-delete' item.id %"
  class="dropdown-item text-danger"
  data-toggle="modal"
  data-target="#delete-item-modal"
  id="delete-item"
>
  Remove
</a>

modal that popup will be:

<div class="modal fade" id="delete-item-modal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                <p>Are you sure, You want to remove this item?</p>
            </div>
            <div class="justify-content-between mb-2 mr-2 text-right">
                <form method="post"
                      id="item-delete-form"
                >
                    <button type="button" class="btn btn-secondary mr-1" data-dismiss="modal">Cancel</button>
                    % csrf_token %
                    <button type="submit" class="btn btn-danger" id="confirm-delete-item-button">Delete</button>
                </form>
            </div>
        </div>
    </div>
</div>

现在我们必须使用项目的 a href 值更改表单操作 URL

<script>
    $(document).on('click', '#delete-item', () => 
        document.getElementById("item-delete-form").action = document.querySelector('#delete-item').href
    );
</script>

我知道这对于您的问题来说为时已晚,但对其他人可能会有所帮助。这是从列表中删除项目而不将页面重定向到确认页面的最简单方法。

注意:前端框架 bootstrap 用于显示模式,因此在继续此解决方案之前,您必须检查 bootstrap 是否正常工作。

【讨论】:

以上是关于如何在 Django 中使用引导模式对表数据进行删除确认?的主要内容,如果未能解决你的问题,请参考以下文章

如何在数据表中使用引导模式在弹出窗口中打开数据

在引导模式中提交 Django 表单

如何在不刷新页面的情况下使用 django-crispy-forms 实现引导模式表单

django登录表单和表单验证在引导模式中使用ajax

django:引导模式不显示

如何在 django 项目中使用引导样式