Integrate Django REST API with DataTables

mahabub.devs3
Mahabubur Rahman
Published on Nov, 23 2024 2 min read 0 comments
image

To integrate Django REST API with DataTables, you can use the djangorestframework-datatables package. This package provides seamless integration between Django REST framework and DataTables, handling searching, filtering, ordering, and pagination.

Steps to Integrate Django REST API with DataTables

1. Install the Package:

pip install djangorestframework-datatables

2. Update Your Settings

Add 'rest_framework_datatables' to your INSTALLED_APPS and configure the REST framework settings:

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
        'rest_framework_datatables.renderers.DatatablesRenderer',
    ),
    'DEFAULT_FILTER_BACKENDS': (
        'rest_framework_datatables.filters.DatatablesFilterBackend',
    ),
    'DEFAULT_PAGINATION_CLASS': 'rest_framework_datatables.pagination.DatatablesPageNumberPagination',
    'PAGE_SIZE': 50,
}

3. Create a Model: Open products/models.py and define your Product model:

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    stock = models.IntegerField()
    is_on_sale = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

4. Create a Serializer: Define a serializer for your model. Open products/serializers.py and define your ProductSerializer serializer:

from rest_framework import serializers
from .models import Product

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = '__all__'

4. Create a View: Create a viewset that uses your serializer. Open products/views.py and define your ProductViewSet serializer:

from rest_framework import viewsets
from .models import YourModel
from .serializers import ProductSerializer

class ProductViewSet(viewsets.ModelViewSet):
    queryset = YourModel.objects.all()
    serializer_class = ProductSerializer

5. Configure URLs: Add the view to your URLs:

from django.urls import path, include
from rest_framework_datatables import views

from products.views import *

from rest_framework.routers import DefaultRouter


router = DefaultRouter()
router.register(r'products', ProductViewSet, basename='product_api')

urlpatterns = [

	path('admin/', admin.site.urls),
    path('api/v1/', include(router.urls)),
]

6. Create the DataTables HTML: Create an HTML table and initialize DataTables with the API endpoint:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>DataTable Example</title>
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css">
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>
</head>
<body>
    <table id="yourmodel-table" class="display">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
				<th>Price</th>                
                <th>Description</th>
            </tr>
        </thead>
    </table>
    <script>
        $(document).ready(function() {
            $('#yourmodel-table').DataTable({
                "processing": true,
                "serverSide": true,
                "ajax": {
                    "url": "api/v1/products/?format=datatables",
                    "type": "GET"
                },
                "columns": [
                    { "data": "id" },
                    { "data": "name" },
                    { "data": "price"}
                    { "data": "description" }
                ]
            });
        });
    </script>
</body>
</html>

This setup will allow you to integrate DataTables with your Django REST API, providing features like searching, filtering, ordering, and pagination without modifying your existing API code

0 Comments