Django AJAX CRUD Tutorial with Example – Part 1 (CREATE and READ)

Django, a high-level Python web framework, empowers developers to build dynamic and interactive web applications rapidly. When integrated with AJAX (Asynchronous JavaScript and XML), Django takes user experiences to the next level, enabling the updating and retrieval of data without the need for a full page reload. The combination of Django and AJAX Javascript is particularly useful for tasks such as refreshing a page, adding data to a database, and retrieving information from the server seamlessly. In this tutorial series, we’ll delve into creating a Django web application that performs CRUD (Create, Read, Update, Delete) operations using AJAX. In this first part, we’ll cover the CREATE and READ operations.

Django AJAX CRUD Tutorial with Task Example

Prerequisites: Before diving into this tutorial, make sure you have the following prerequisites in place:

  1. Basic understanding of Django framework.
  2. Basic knowledge of HTML, CSS, and JavaScript.
  3. Django installed on your machine. You can use pip for installation: pip install django.

Part 1: Creating and Reading Tasks with Django and AJAX

Step 1: Setting Up the Django Project:

Let’s start by creating a new Django project and a new app within the project.

# Create a new Django project
django-admin startproject myproject

# Navigate to the project directory
cd myproject

# Create a new Django app
django-admin startapp tasks

Next, let’s configure the project settings. Add 'tasks' to the INSTALLED_APPS list in the file:

    # ...
    # ...

Step 2: Model and Database Setup:

In this example, we’ll create a simple Task model with a title and completed. Open the tasks/ file and define the model:

# tasks/

from django.db import models

class Task(models.Model):
    title = models.CharField(max_length=200)
    completed = models.BooleanField(default=False)

    def __str__(self):
        return self.title

After defining the model, run the following commands to apply the migrations:

python makemigrations
python migrate

Step 3: Creating Django Views:

Now, let’s create the views that handle the AJAX requests and interact with the database.

# tasks/

from django.shortcuts import render
from django.http import JsonResponse
from .models import Task

def tasks(request):
    return render(request, 'tasks.html')

def get_tasks(request):
    tasks = Task.objects.all()
    task_list = [{'id':, 'title': task.title, 'completed': task.completed} for task in tasks]
    return JsonResponse(task_list, safe=False)

def add_task(request):
    if request.method == 'POST':
        title = request.POST.get('title')
        task = Task.objects.create(title=title)
        return JsonResponse({'status': 'success'})

Step 4: URL Configuration:

Configure the URLs in the file of the tasks app.

# tasks/

from django.urls import path
from . import views

urlpatterns = [
    path('', views.tasks, name='tasks'),
    path('get_tasks/', views.get_tasks, name='get_tasks'),
    path('add_task/', views.add_task, name='add_task'),

Also, include the tasks URLs in the project’s

# myproject/

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('', include('tasks.urls')),

Step 5: Creating the HTML Template:

Create a new HTML file named tasks.html inside the templates directory of the tasks app. This will be the main interface for our tasks.

<!-- tasks/templates/tasks.html -->

<!DOCTYPE html>
    <title>Task Manager</title>
    <script src=""></script>
    <h1>Task Manager</h1>
        <input type="text" id="taskInput" placeholder="Enter task">
        <button id="addTaskBtn">Add Task</button>
    <ul id="taskList">
        <!-- Tasks will be displayed here -->
        // AJAX logic will go here

Step 6: Adding AJAX Functionality:

Inside the <script> tag in the tasks.html file, let’s add the AJAX code to handle task creation and reading.

<!-- tasks/templates/tasks.html -->

<!-- ... (previous code) ... -->

    $(document).ready(function() {
        // Set CSRF token for AJAX requests
            headers: { "X-CSRFToken": "{{ csrf_token }}" }

        // Function to load tasks from the server
        function loadTasks() {
                url: '/get_tasks/',
                method: 'GET',
                success: function(data) {
                    data.forEach(function(task) {
                        $('#taskList').append('<li>' + task.title + '</li>');

        // Load tasks on page load

        // Function to add a new task
        $('#addTaskBtn').click(function() {
            var title = $('#taskInput').val();
                url: '/add_task/',
                method: 'POST',
                data: { title: title },
                success: function() {

Note: For styling, please refer to our github project.

Step 7: Run Server and Test the Functionality:

Start the server by following command python runserver and go to the URL – http://localhost:8000/


In Part 1 of this Django AJAX CRUD tutorial, we’ve successfully set up the foundation for our Task Management application. We’ve created the necessary models, templates, and views to handle the creation and reading of tasks using AJAX. In the next part, we’ll dive into the Update and Delete operations, completing our full CRUD functionality.

Find this tutorial on Github.

Next: Django AJAX CRUD Tutorial with Example – Part 2 (UPDATE and DELETE)