user3541631
user3541631

Reputation: 4008

Django Delete CBV with confirmation pop-up and multiple success url

In my case, an instance Model can be delete from:

By default, when a delete view is called:

--

So I want to know how to do Ajax calls on delete, how to have conditional success urls in delete, based of where I am before the action.

Upvotes: 2

Views: 3070

Answers (1)

ikkuh
ikkuh

Reputation: 4603

For the DetailView you can simply use a form as follows:

<form action="{% url "app:delete" object.id %}" method="post">
  {% csrf_token %}

  <button onclick="return confirm('Are you sure?');">Delete</button>
</form>

Clicking on the button will open a confirm dialog. If the users clicks OK the form will be submitted. This will delete the object and redirect to the same way the confirm_delete page would have redirected.

For the ListView can simply send a POST request to the DeleteView and on success reload the current page to update the ListView. How you send your AJAX request depends on whether you use any libraries, but with jQuery it could be done as follows:

$.ajax('{% url "app:delete" object.id %}', {
    method: 'POST',
    success: function() {
        window.location.reload();
    },
});

Note: don't forget to include the csrf_token for the AJAX request to work. See the docs for more information.

Upvotes: 9

Related Questions