如何在 Django 中使用 Bootstrap 模态删除基于 Class 的视图的对象?

How to use a Bootstrap Modal to delete a object using Class Based Views in Django?

我在 Django 中使用 CBV 删除项目。我想要做的是,当我单击要删除的按钮时,而不是将我重定向到 post_confirm_delete 视图,我想弹出一个模式,在其中显示用户是否要删除对象和按钮的问题用于确认,另一个用于删除对象。我在 HTML:

中尝试过这个
<button class="btn" data-toggle="modal" data-target="#fm-modal-grid">Delete</button>
<div class="modal fade" id="fm-modal-grid" tabindex="-1"
     role="dialog" aria-labelledBy="fm-modal-grid"
    aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button class="close" data-dismiss="modal" aria-label="Cerrar">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-12 col-sm-6">
                            <p>Are you sure you want to delte {{post.title}}</p>
                        </div>
                    </div>
                </div>
            </div>

            <div class="modal-footer">
                <a href="{% url 'blog:post_remove' pk=post.pk %}" class="btn">Delete</a>
                <button class="btn btn-primary" data-dismiss="modal">Cancelar</button>

            </div>
        </div>
    </div>
</div>

我在视图的 delte CBV 中有这个 class:

class PostDeleteView(DeleteView, LoginRequiredMixin):
    model = Post
    success_url = reverse_lazy('post_list')
    template_name = 'blog/post_list.html'

url 文件如下所示:

urlpatterns = [
    path('',views.PostListView.as_view(),name='post_list'),
    path('article/', views.ArticleView.as_view(), name="article"),
    path('newpost/', views.CreatPostView.as_view(), name="new_post"),
    path('post/<int:pk>', views.PostDetailView.as_view(), name='post_detail'),
    path('post/<int:pk>/edit/', views.PostUpdateView.as_view(), name='post_edit'),
    path('post/<int:pk>/remove/', views.PostDeleteView.as_view(), name='post_remove'),
]

当我按下模式内的删除按钮时,它会将我重定向到我的索引,但不会删除该对象。我该怎么做?

docs

The given object will only be deleted if the request method is POST.

所以 link 是它不起作用的原因。我通过将用于删除的模式按钮放在这样的表单中来解决它:

<form action="{% url 'blog:post_remove' pk=post.pk %}" method="POST">
       {% csrf_token %}
       <button class="btn">Delete</button>
</form>

的确,您需要将按钮放在表单中才能制作 POST。

另一个解决方案是使用一些 JS 触发模式,然后当您确认删除时,您可以进行 Ajax 类型 POST 的调用。所以你没有义务将按钮放在表单中。

$.confirm({
        title: 'Deletion pop-up',
        content: 'Do you want to proceed ?',
        buttons: {
            confirm: function () {
              $.ajax({...}),
                success: function(response){...},
            }
        }
)};