Skip to main content

Django Backend for DataTables from datatables.net

Project description

PyPI Version PyPI Downloads

Description

Provides powerful backend for DataTables.

Installation

Install DataTables Node packages

Manual Installation

Install DataTables JavaScript library in your Django project. Optionally install additional DataTables NPM packages depending on CSS framework you use (i.e. BootStrap5 and Responsive Bootstrap5). DataTables requires jQuery and is automatically installed, however if you wish to use a specific version of jQuery, you can install that too.

Standard Installation

If you do not already have a directory convention on where to install JS packages, you can create a vendor directory in the root directory of Django, then create a sub-directory node_packages, and create package.json with following content.

{
  "name": "custom-libraries",
  "description": "Node packages used in the project",
  "version": "1.0.0",
  "scripts": {
    "build": "npm-run-all copy",
    "copy": "npm-run-all make_vendor copy_vendor",
    "make_vendor": "npm-run-all --parallel make-*",
    "make-css": "if not exist \"../../public/static/vendor/css\" mkdir \"../../public/static/vendor/css\"",
    "make-js": "if not exist \"../../public/static/vendor/js\" mkdir \"../../public/static/vendor/js\"",
    "copy_vendor": "npm-run-all --parallel copy-*",
    "copy-datatablesnet-js": "cp -r node_modules/datatables.net/js/*.min.js ../../public/static/vendor/js",
    "copy-datatablesbs5-css": "cp -r node_modules/datatables.net-bs5/css/*.min.css  ../../public/static/vendor/css",
    "copy-datatablesbs5-js": "cp -r node_modules/datatables.net-bs5/js/*.min.js ../../public/static/vendor/js",
    "copy-datatablesrespoonsive-js": "cp -r node_modules/datatables.net-responsive/js/*.min.js ../../public/static/vendor/js",
    "copy-datatablesresponsive-css": "cp -r node_modules/datatables.net-responsive-bs5/css/*.min.css ../../public/static/vendor/css",
    "copy-datatablesrespoonsive-bs5-js": "cp -r node_modules/datatables.net-responsive-bs5/js/*.min.js ../../public/static/vendor/js",
    "copy-jquery-js": "cp -r node_modules/jquery/dist/*.js ../../public/static/vendor/js"
  },
  "license": "SEE LICENSE IN LICENSE",
  "private": true,
  "dependencies": {
    "datatables.net": "^2.3.2",
    "datatables.net-bs5": "^2.3.2",
    "datatables.net-responsive-bs5": "^3.0.4",
    "jquery": "^3.7.1",
    "npm-run-all2": "^8.0.4"
  }
}

Now run the following commands:

cd vendor/node_packages
npm install
npm run build

This will install DataTables packages, create public/static/vendor/css and public/static/vendor/js directories in the Django root directory, and copy the necessary *.min.css and *.min.js files. These files need to be included in the templates of views which use DataTables (we will discuss this later).

Install DataTables Python packages

pip install django-datatables-kit

If you use PDM:

pdm add django-datatables-kit

Note that django-helper-kit is a dependency and is automatically installed.

Setup Django

Edit Django settings.py:

  1. Import DataTables settings provided by this package. There are two settings dictionaries: DJDTK_DATATABLES_CONFIG and DJDTK_DATATABLES_DEFAULTS. If you want to override these settings, copy them into separate file(s) and import them here (modify your import likewise). Caution: Do not change the names of the settings variables.

from django_datatables_kit.settings import *
  1. Add packages to INSTALLED_APPS. Note that django_helper_kit is required to be added, and it must appear before django_datatables_kit.

INSTALLED_APPS = [
    # ...
    "django_helper_kit",
    "django_datatables_kit",
    # ...
]

Note: This is an alpha version, and things may change quite a bit.

Usage

We will demonstrate usage with an example.

Example Model

from django.db.models import CharField, ForeignKey, Model, PROTECT


class StateChoices(models.TextChoices):
    AP = "ap", _("Andhra Pradesh")
    GJ = "gj", _("Gujarat")
    KA = "ka", _("Karnataka")
    MH = "mh", _("Maharashtra")


class Example(Model):
    name = CharField(max_length=64)
    city = CharField(max_length=64)
    state = CharField(choices=StateChoices, max_length=2)

    objects_all = models.Manager()

    class Meta:
        default_manager_name = "objects_all"


class ExampleChild(Model):
    example = ForeignKey(Example, on_delete=PROTECT)
    description = CharField(max_length=64)

Template Includes and Imports

In the template using DataTables, include the following:

{% include "django_datatables_kit/datatables-config.html" %}

Depending on what DataTables related-packages you have installed and where you have copied DataTables and jQuery *.min.css and *.min.js, modify the following and create a partial template, then include it in the template using DataTables:

{% load static %}
<link rel="stylesheet" href="{% static 'vendor/css/dataTables.bootstrap5.min.css' %}">
<link rel="stylesheet" href="{% static 'vendor/css/responsive.bootstrap5.min.css' %}">
<script src="{% static 'vendor/js/jquery.min.js' %}"></script>
<script src="{% static 'vendor/js/dataTables.min.js' %}"></script>
<script src="{% static 'vendor/js/dataTables.bootstrap5.min.js' %}"></script>
<script src="{% static 'vendor/js/dataTables.responsive.min.js' %}"></script>
<script src="{% static 'vendor/js/responsive.bootstrap5.min.js' %}"></script>

Create a JavaScript file for DataTables and include this in the template. In the following example, state is a TextChoices field, and so the human_readable value is chosen to be displayed, the stored value can is available as raw.

DataTables JavaScript

document.addEventListener("DOMContentLoaded", function (event) {
    const dtTableId = "example-dt";
    const dtParms = readDtParms(dtTableId);
    initDataTable(
        tableId=dtTableId,
        columns=[
            {
                data: "id",
                responsivePriority: 1,
                searchable: false,
                orderable: false,
                name: "action",
                render: function (data, type, row, meta) {
                    return `<a href="${dtParms.viewExampleUrl.replace(':site_id:', data)}" title="${DJDTK_DATATABLES_CONFIG.language.view}"><i class="bi bi-eye"></i></a>`;
                },
            },
            {
                data: "id",
                responsivePriority: 2,
                searchable: false,
                orderable: false,
            },
            {
                data: "name",
                responsivePriority: 3,
                searchable: true,
                orderable: true,
            },
            {
                data: "city",
                responsivePriority: 4,
                searchable: false,
                orderable: false,
            },
            {
                data: "province",
                responsivePriority: 5,
                searchable: false,
                orderable: false,
                render: function (data, type, row, meta) { return data.human_readable; },
            },
            {
                data: "example_children_count",
                responsivePriority: 6,
                searchable: false,
                orderable: false,
            },
        ],
        order=[[2, "asc"]],
    );
});
document.addEventListener("DOMContentLoaded", function (event) {
    const dtTableId = "example-children-dt";
    const dtParms = readDtParms(dtTableId);
    initDataTable(
        tableId=dtTableId,
        columns=[
            {
                data: "id",
                responsivePriority: 1,
                searchable: false,
                orderable: false,
                name: "action",
                render: function (data, type, row, meta) {
                    return `<a href="${dtParms.viewExampleUrl.replace(':site_id:', data)}" title="${DJDTK_DATATABLES_CONFIG.language.view}"><i class="bi bi-eye"></i></a>`;
                },
            },
            {
                data: "description",
                responsivePriority: 2,
                searchable: true,
                orderable: true,
            },
        ],
        order=[[1, "asc"]],
    );
});
<script src="{% static 'app_example/js/datatables/example/dt-example-list.js' %}"></script>

Template HTML Table

In the template table HTML tag, define id (value must match dtTableId above, this links the DataTable to HTML table) and data-dt-parms attributes. You can pass any parameter in data-dt-parms which will be made available to DataTables JavaScript (see later).

<table id="example-dt" class="table table-hover display nowrap" data-dt-parms='{"apiUrl": "{% url 'app_example:list_examples' %}", "viewExampleUrl": "{% url 'app_example:view_example' ':example_id:' %}"}'>
 <thead>
  <tr>
   <th class="fw-bold">{% translate 'Action' %}</th>
   <th class="fw-bold">{% translate 'ID' %}</th>
   <th class="fw-bold">{% translate 'Name' %}</th>
   <th class="fw-bold">{% translate 'City' %}</th>
   <th class="fw-bold">{% translate 'Province' %}</th>
   <th class="fw-bold">{% translate 'Children Count' %}</th>
  </tr>
 </thead>
 <tbody></tbody>
</table>
<table id="example-children-dt" class="table table-hover display nowrap" data-dt-parms='{"apiUrl": "{% url 'app_example:list_example_children' example.id %}"}'>
 <thead>
  <tr>
   <th class="fw-bold">{% translate 'ID' %}</th>
   <th class="fw-bold">{% translate 'Description' %}</th>
  </tr>
 </thead>
 <tbody></tbody>
</table>

View

The view can be defined in 2 ways:

Quick View

In urls.py:

from django.db.models import Count
from django.urls import path
from django_datatables_kit.views import BaseDataTablesView
from ..models import Example


urlpatterns = [
    path("list-examples",
         BaseDataTablesView.as_view(
             http_method_names = ["post"],
             model=Example,
             column_masks={"id": "id",
                           "name": "name",
                           # "city" mask is missing, Python None (JS null) will be returned, no error
                           "province": "state",  # "province" mapped to "state" column
                           "example_children_count": "annot_children_count"},
             annotations={"annot_children_count": Count("examplechild")},
             default_order_by=["id"]),
         name="list_examples"),
]

Inherited View

Create the view:

from django_datatables_kit.views import BaseDataTablesView
from ..models import ExampleChild


class ExampleChildrenDataTableView(BaseDataTablesView):
    http_method_names = ["post"],
    model=ExampleChild,
    column_masks={"id": "id",
                  "description": "description"},
    default_order_by=["description"]),

    def initial_queryset(self, *args, **kwargs):
        return self.model.objects.filter(example_id=int(kwargs.get("example_id")))

Add to urlpatterns:

from .views import

urlpatterns = [
       path("list-example-children/<int:example_id>",
         ExampleChildrenDataTableView.as_view(),
         name="list_example_children"),
]

Note: This is an alpha version, and things may change quite a bit.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_datatables_kit-0.1.0a6.tar.gz (17.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_datatables_kit-0.1.0a6-py3-none-any.whl (17.9 kB view details)

Uploaded Python 3

File details

Details for the file django_datatables_kit-0.1.0a6.tar.gz.

File metadata

  • Download URL: django_datatables_kit-0.1.0a6.tar.gz
  • Upload date:
  • Size: 17.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: pdm/2.25.3 CPython/3.13.5 Windows/11

File hashes

Hashes for django_datatables_kit-0.1.0a6.tar.gz
Algorithm Hash digest
SHA256 825485df64e5000a524bec77e0c4d98c749b0cea78a2d13f135e3e5bcde3a0f0
MD5 84f0fd8898b9578798fd8e0595413d46
BLAKE2b-256 63ebe444e412f9669f643219fc92892369bde54d295ff0841b60b37a0c15f521

See more details on using hashes here.

File details

Details for the file django_datatables_kit-0.1.0a6-py3-none-any.whl.

File metadata

File hashes

Hashes for django_datatables_kit-0.1.0a6-py3-none-any.whl
Algorithm Hash digest
SHA256 46281b11e476d26733937f4d31b5115b46916d3e6baab305628392419fa5e864
MD5 35cf8b42d6e114308a06bcc6abb5c793
BLAKE2b-256 f6c323a5c5909b001d20d22e7456d300a45d0b9857de0eaed5a5fc1b546473fe

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page