1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Ajax View

from django.http import HttpResponse
from django.utils import simplejson as json
from django.views.generic import View


class AjaxDeleteView(View):

    def post(self, request):
        pk = request.POST.get("pk", None)

        if pk:
            obj_to_delete = get_object_or_404(Model, pk=pk)
            obj_to_delete.delete()
            return HttpResponse(json.dumps("success"),
                mimetype="application/json")

# urls.py

from someapp.views import AjaxDeleteView

url(r"^delete/", AjaxDeleteView.as_view(), name="ajax_delete_view"),

# Template with jQuery
    ... HTML ...
    <a class="ajax_delete" data-pk="{{ object.pk }}" href="{% url ajax_delete_view %}">Delete</a>

    $(document).on("click", "a.ajax_delete", function(e) {
        e.preventDefault();
        var post_data = {pk: $(this).attr("data-pk"),
            result = $.ajax({
                url: "{% url ajax_delete_view %}",
                data: post_data,
                type: "POST",
                success: function(data, textStatus, jqXHR) {
                    $(this).remove(); //remove the item from the DOM
                },
                error: function(data, textStatus, jqXHR) {
                    alert("ERROR"); // obviously display a better error
                }
            });
    });