Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I´m using CBV in Django to delete items. What I want to do is when I click the button to remove, instead of redirecting me to the post_confirm_delete view I want to pop up a modal in which I show the question if the user want to delete the object and a button for confirm and the other to delete the object. I have tried this in the 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>

And I have this in the delte CBV in the views class:

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

And the url file looks like this:

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'),
]

When I press the Delete button inside the modal, it redirect me to my index, but doesn't delete the object. How can I do this?

like image 997
Paul Miranda Avatar asked Apr 01 '19 17:04

Paul Miranda


1 Answers

By the docs

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

So the link was the reason that it did not work. I solved it by putting the modal button for delete inside a form like this:

<form action="{% url 'blog:post_remove' pk=post.pk %}" method="POST">
       {% csrf_token %}
       <button class="btn">Delete</button>
</form>
like image 184
Paul Miranda Avatar answered Oct 22 '22 12:10

Paul Miranda