How to use Datatables in Django?

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


Hi Dev,

Here, I will show you how to works how to create datatable in django. we will help you to give example of how to use datatables with django. this example will help you django datatables ajax example. I’m going to show you about django datatables server side example. Let's get started with django datatables example.

jQuery Datatables provides us with quick search, pagination, ordering, sorting and etc. Datatables is basically jQuery plugins that allow you to add advanced interaction controls to your HTML tables data. Datatables also provide ajax for data searching and getting. you can give a very quick layout for search and sorting using Datatables. You can also implement Datatables in your django application.

Here i explained simply step by step example of how to create datatable in django.

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

Now we'll create a single app called core to store a list of post names. We're keeping things intentionally basic. Stop the local server with Control+c and use the startapp command to create this new app.

python3 manage.py startapp core
Step 3: Update setting.py

Next, then update INSTALLED_APPS within our settings.py file to notify Django about the app.

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 now go for the models we will We'll call our single model Post and it will have just two fields: title and description. And finally set __str__ to display the name of the post.

core/models.py
from django.db import models

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

    def __str__(self):
        return self.title

Ok, all set. We can engender a migrations file for this change, then integrate it to our database via migrate.

python manage.py makemigrations
python manage.py migrate
Step 5: Creating the Views

In this step, we need to configure our two views. The index page will just be a template. second view is fetch the data into database in for datatables open the core/views.py file and add:

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

# Create your views here.
def index(request):
    return render(request, 'index.html')

def load_data(request):
    object_list = Post.objects.all()
    json = serializers.serialize('json', object_list)
    return HttpResponse(json, content_type='application/json')
Step 6: Creating the Templates

Next, then with your text editor create new templates files: core/templates/index.html file and the add:

core/templates/index.html
<!DOCTYPE html>
<html>
<head>
    <title>How To use DataTables With Django? - Tuts-Station.com</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.11.4/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
    <script src="https://cdn.datatables.net/1.11.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.4/js/dataTables.bootstrap5.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">
                    <h2>How To use DataTables With Django? - <span class="text-primary">Tuts-Station.com</span></h2>
                </div>
                <div class="card-body">
                    <table class="table table-bordered data-table">
                        <thead>
                            <tr>
                                <th width="20">ID</th>
                                <th width="400">Title</th>
                                <th>Description</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="ajaxModel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="modelHeading"></h4>
            </div>
            <div class="modal-body">
                <form id="productForm" name="productForm" class="form-horizontal">
                   <input type="hidden" name="product_id" id="product_id">
                    <div class="form-group">
                        <label for="name" class="col-sm-2 control-label">Name</label>
                        <div class="col-sm-12">
                            <input type="text" class="form-control" id="name" name="name" placeholder="Enter Name" value="" maxlength="50" required="">
                        </div>
                    </div>
       
                    <div class="form-group">
                        <label class="col-sm-2 control-label">Details</label>
                        <div class="col-sm-12">
                            <textarea id="detail" name="detail" required="" placeholder="Enter Details" class="form-control"></textarea>
                        </div>
                    </div>
        
                    <div class="col-sm-offset-2 col-sm-10">
                     <button type="submit" class="btn btn-primary" id="saveBtn" value="create">Save changes
                     </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

</body>
     
<script type="text/javascript">
    $(document).ready(function() {

        /*------------------------------------------
        --------------------------------------------
        Post Listing Page 
        --------------------------------------------
        --------------------------------------------*/
        $('.data-table').dataTable({
            processing: true,
            serverSide: false,
            ordering:  true,
            columnDefs: [
                {
                    "render": function ( data, type, row ) {
                        return "<button class='btn btn-danger btn-delete' data-pk='" + row.pk + "'>" + 'Delete' + "</button>";
                    },
                    "targets": 3
                }
            ],
            ajax: {
                url: "{% url 'load_data' %}",
                dataSrc: "",
            },
            columns: [
                { data: "pk" },
                { data: "fields.title" },
                { data: "fields.description" },
            ]
        });
    });
</script>
</html>
Step 7: Creating URLs

In this section, we need a urls.py file within the core app however Django doesn't create one for us with the startapp command. Create core/urls.py with your text editor and within this file we'll import yet-to-be-created function for each--index and load_data--and set a path for each. Note as well that we set an optional URL name for each.

Here's what it looks like:

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

urlpatterns = [
    path('', views.index,name='index'),
    path('fetch/', views.load_data,name='load_data'),
]

Next, we require to add a URL path for our core app which can be done by importing include and setting a path for it.

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.

Our basic datatable is now complete! i hope it will help you....