如何在Django中使用bootstrap Modal对表数据进行删除确认?

camsedfj  于 2022-12-05  发布在  Go
关注(0)|答案(6)|浏览(180)

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

<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模态中的www.example.com值,但我没有得到!

请帮我解决这个问题。提前感谢:)

jw5wzhpr

jw5wzhpr1#

如果你们中的任何人正在经历这种情况,我有一个快速解决办法。
主要思想是使用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>

我知道现在回答你的问题已经太迟了,但对其他人可能会有帮助。这是从列表中删除项目而不将页面重定向到确认页面的最简单方法。
注意:前端框架引导程序用于显示模态,因此在继续此解决方案之前,您必须检查引导程序是否正常工作。

zsbz8rwp

zsbz8rwp2#

有关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>
ar5n3qh5

ar5n3qh53#

删除链接:

<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,))
li9yvcax

li9yvcax4#

试试这个

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="deleteButton{{your.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>
lb3vh1jj

lb3vh1jj5#

我从**@dipesh**得到了这个例子,但是为了对我有效,我需要改变一些东西(标签“a”和javascript)来获得正确的元素。

我的剧本

function delete_user(selected_user){
        document.getElementById("item-delete-form").action = selected_user.href
}

我在删除项目列表中的链接将是:

<a
  href="{% url 'item-delete' item.id %}"
  class="dropdown-item text-danger"
  data-toggle="modal"
  data-target="#delete-item-modal"
  onclick="delete_user(this)""
>
  Remove
</a>

我的模态

<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>
w9apscun

w9apscun6#

您也可以不使用JavaScript来实现(另请参见this问题中@lemayzeur的答案中的选项1)item.id:

# in your link to the modal
data-target="#delete-item-modal-{{item.id}}"

# in your modal
id="delete-item-modal-{{item.id}}"

相关问题