Reputation: 4008
In my case, an instance Model can be delete from:
By default, when a delete view is called:
get
function calls 'confirm_delete' template. Instead I want a pop-up/modal to appear, and if delete
is clicked in the modal will delete the object if the delete
operation is on a ListView, after delete the user will remain on ListView and the ListView content will be updated
if the delete
operation is on a DetailView, after delete the user will be redirected to the ListView or another page(depending on other rules)
--
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
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