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 settings.py file:

INSTALLED_APPS = [
    # ...
    'tasks',
    # ...
]

Step 2: Model and Database Setup:

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

# tasks/models.py

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 manage.py makemigrations
python manage.py migrate

Step 3: Creating Django Views:

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

# tasks/views.py

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': task.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 urls.py file of the tasks app.

# tasks/urls.py

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 urls.py.

# myproject/urls.py

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

urlpatterns = [
    path('admin/', admin.site.urls),
    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>
<html>
<head>
    <title>Task Manager</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h1>Task Manager</h1>
    <div>
        <input type="text" id="taskInput" placeholder="Enter task">
        <button id="addTaskBtn">Add Task</button>
    </div>
    <ul id="taskList">
        <!-- Tasks will be displayed here -->
    </ul>
    <script>
        // AJAX logic will go here
    </script>
</body>
</html>

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) ... -->

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

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

        // Load tasks on page load
        loadTasks();

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

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

Step 7: Run Server and Test the Functionality:

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

Conclusion

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)