Django Ajax DELETE Request Example Tutorial

Published On: 23/08/2022 | Category: Django


Hi Dev,

I will explain step by step tutorial django ajax delete request example. this example will help you how do i delete with jquery/ajax in django. you'll learn jquery ajax delete json response example. you'll learn how do i get data from my ajax delete to my django view. Let's see bellow example django ajax patch request example tutorial.

Now let's move on to the DELETE request. In our current scenario When you click on the delete button to delete the post with ajax delete request.

Here i explained simply step by step example of django ajax delete request example.

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2: Create a App
python3 manage.py startapp core
Step 3: Update setting.py

In this step we require to do add installed apps in our settings.py file. Add the below lines to your settings.py file:

Next, you need to add it in the settings.py file as follows:

settings.py
....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core',
]
Step 4: Create a Model

In this step we will require the database model for storing employee details data.Open the core/models.py file and add the following code:

core/models.py
from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=250)
    description = models.TextField()

Next, you need to migrate your database using the following command:

python manage.py makemigrations
python manage.py migrate

Django Admin Interface:



Step 5: Creating the Views

In this step, we need to create the views for performing fetch and delete record via ajax to the database.Open the core/views.py file and add:

core/views.py
from django.shortcuts import render, redirect, get_object_or_404
from .models import Post
from django.http import JsonResponse,HttpResponse
import json

# Listing Page
def post_view(request):
    posts = Post.objects.all()
    return render(request, 'index.html', { 'posts': posts })

# Delete Post
def delete(request,id):
    post = Post.objects.get(id=id)
    post.delete()
    return JsonResponse({'success': True, 'message': 'Delete','id':id})
Step 6: Creating the Templates

Next, open the core/templates/index.html file and the add:

core/templates/index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <div class="row">
                            <div class="col-md-12">
                                <h3>Django Ajax Delete Request Example - <span class="text-primary">Tuts-Station.com</span></h3>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <table class="table table-bordered table-hover postTable">
                            <thead>
                                <tr>
                                    <th width="150">Title</th>
                                    <th width="200">Content</th>
                                    <th width="40">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for post in posts %}
                                    <tr class="post-{{post.id}}">
                                        <td>{{ post.title }}</td>
                                        <td>{{ post.description }}</td>
                                        <td>
                                            {% csrf_token %}
                                            <button type="button" data-id={{post.id}} class="btn btn-xs btn-danger btn-flat delete-post">Delete</button>
                                        </td>
                                    </tr>
                                    {% empty %}
                                        <tr class="text-center">
                                            <td colspan="4">There are no Record Found!</td>
                                        </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
<script type="text/javascript">
    $(document).ready(function () {

        /*------------------------------------------
        --------------------------------------------
        Delete Post 
        --------------------------------------------
        --------------------------------------------*/
        $("body").on("click",".delete-post",function(e){

            if(!confirm("Do you really want to do this?")) {
               return false;
            }

            e.preventDefault();
            var id = $(this).data("id");

            $.ajax({
                url: "delete/"+id,
                type: 'DELETE',
                dataType: 'json',
                headers: {
                    "X-CSRFTOKEN": "{{ csrf_token }}"
                },
                data: {
                    id: id
                },
                success: function (response){
                    $(".postTable .post-" + id).remove();
                }
            });
            return false;
       });
    });
</script>
</html>
Step 7: Creating URLs

In this section, we’ll create the urls to access our CRUD views.Go to the urls.py core/urls.py file and update it as follows:

core/urls.py
from django.urls import path
from core import views

urlpatterns = [
    path('', views.post_view, name='index'),
    path('delete/<int:id>', views.delete, name='delete'),
]

Next, we will require the modify the urls.py your root preoject folder lets update the file.

example/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('core.urls')),
]
Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python manage.py runserver

Next, go to the http://localhost:8000/ address with a web browser.

I Hope It will help you....