Skip to main content

Django datatables view

Project description

About

django-datatables-view is a base view for handling server side processing for the awesome datatables 1.9.x, 1.10.x (http://datatables.net).

django-datatables-view simplifies handling of sorting, filtering and creating JSON output, as defined at: http://datatables.net/examples/server_side/

Example

Example project that uses django-datatables-view is available at: https://bitbucket.org/pigletto/django-datatables-view-example/

Usage

1. Install django-datatables-view

pip install django-datatables-view

2. Edit views.py

django_datatables_view uses GenericViews, so your view should just inherit from base class: BaseDatatableView, and override few things (there is also a DatatableMixin - pure datatables handler that can be used with the mixins of your choice, eg. django-braces). These are:

  • model - the model that should be used to populate the datatable

  • columns - the columns that are going to be displayed. If not defined then django_datatables_view will look for ‘name’ in the columns definition provided in the request by DataTables, eg.: columnDefs: [{name: ‘name’, targets: [0]} (only works for datatables 1.10+)

  • order_columns - list of column names used for sorting (eg. if user sorts by second column then second column name from this list will be used with order by clause). If not defined then django_datatables_view will look for ‘name’ in the columns definition provided in the request by DataTables, eg.: columnDefs: [{name: ‘name’, targets: [0]} (only works for datatables 1.10+)

  • filter_queryset - if you want to filter your DataTable in some specific way then override this method. In case of older DataTables (pre 1.10) you need to override this method or there will be no filtering.

  • filter_method - returns ‘istartswith’ by default, you can override it to use different filtering method, e.g. icontains: return self.FILTER_ICONTAINS

For more advanced customisation you might want to override:

  • get_initial_queryset - method that should return queryset used to populate datatable

  • prepare_results - this method should return list of lists (rows with columns) as needed by datatables

  • escape_values - you can set this attribute to False in order to not escape values returned from render_column method

The code is rather simple so do not hesitate to have a look at it. Method that is executed first (and that calls other methods to execute whole logic) is get_context_data. Definitely have a look at this method!

See example below:

from django_datatables_view.base_datatable_view import BaseDatatableView
from django.utils.html import escape

class OrderListJson(BaseDatatableView):
    # The model we're going to show
    model = MyModel

    # define the columns that will be returned
    columns = ['number', 'user', 'state', 'created', 'modified']

    # define column names that will be used in sorting
    # order is important and should be same as order of columns
    # displayed by datatables. For non sortable columns use empty
    # value like ''
    order_columns = ['number', 'user', 'state', '', '']

    # set max limit of records returned, this is used to protect our site if someone tries to attack our site
    # and make it return huge amount of data
    max_display_length = 500

    def render_column(self, row, column):
        # We want to render user as a custom column
        if column == 'user':
            # escape HTML for security reasons
            return escape('{0} {1}'.format(row.customer_firstname, row.customer_lastname))
        else:
            return super(OrderListJson, self).render_column(row, column)

    def filter_queryset(self, qs):
        # use parameters passed in GET request to filter queryset

        # simple example:
        search = self.request.GET.get('search[value]', None)
        if search:
            qs = qs.filter(name__istartswith=search)

        # more advanced example using extra parameters
        filter_customer = self.request.GET.get('customer', None)

        if filter_customer:
            customer_parts = filter_customer.split(' ')
            qs_params = None
            for part in customer_parts:
                q = Q(customer_firstname__istartswith=part)|Q(customer_lastname__istartswith=part)
                qs_params = qs_params | q if qs_params else q
            qs = qs.filter(qs_params)
        return qs

3. Edit urls.py

Add typical django’s urlconf entry:

url(r'^my/datatable/data/$', login_required(OrderListJson.as_view()), name='order_list_json'),

4. Define HTML + JavaScript

Example JS:

$(document).ready(function() {
    var oTable = $('.datatable').dataTable({
        // ...
        "processing": true,
        "serverSide": true,
        "ajax": "{% url 'order_list_json' %}"
    });
    // ...
});

Another example of views.py customisation

from django_datatables_view.base_datatable_view import BaseDatatableView
from django.utils.html import escape

class OrderListJson(BaseDatatableView):
    order_columns = ['number', 'user', 'state']

    def get_initial_queryset(self):
        # return queryset used as base for futher sorting/filtering
        # these are simply objects displayed in datatable
        # You should not filter data returned here by any filter values entered by user. This is because
        # we need some base queryset to count total number of records.
        return MyModel.objects.filter(something=self.kwargs['something'])

    def filter_queryset(self, qs):
        # use request parameters to filter queryset

        # simple example:
        search = self.request.GET.get('search[value]', None)
        if search:
            qs = qs.filter(name__istartswith=search)

        # more advanced example
        filter_customer = self.request.GET.get('customer', None)

        if filter_customer:
            customer_parts = filter_customer.split(' ')
            qs_params = None
            for part in customer_parts:
                q = Q(customer_firstname__istartswith=part)|Q(customer_lastname__istartswith=part)
                qs_params = qs_params | q if qs_params else q
            qs = qs.filter(qs_params)
        return qs

    def prepare_results(self, qs):
        # prepare list with output column data
        # queryset is already paginated here
        json_data = []
        for item in qs:
            json_data.append([
                escape(item.number),  # escape HTML for security reasons
                escape("{0} {1}".format(item.customer_firstname, item.customer_lastname)),  # escape HTML for security reasons
                item.get_state_display(),
                item.created.strftime("%Y-%m-%d %H:%M:%S"),
                item.modified.strftime("%Y-%m-%d %H:%M:%S")
            ])
        return json_data

Yet another example of views.py customisation

This sample assumes that list of columns and order columns is defined on the client side (DataTables), eg.:

$(document).ready(function() {
    var dt_table = $('.datatable').dataTable({
        order: [[ 0, "desc" ]],
        columnDefs: [
            {
                name: 'name',
                orderable: true,
                searchable: true,
                targets: [0]
            },
            {
                name: 'description',
                orderable: true,
                searchable: true,
                targets: [1]
            }
        ],
        searching: true,
        processing: true,
        serverSide: true,
        stateSave: true,
        ajax: TESTMODEL_LIST_JSON_URL
    });
});
class TestModelListJson(BaseDatatableView):
    model = TestModel

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-view-1.19.0.tar.gz (13.8 kB view details)

Uploaded Source

Built Distributions

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

django_datatables_view-1.19.0-py3-none-any.whl (9.9 kB view details)

Uploaded Python 3

django_datatables_view-1.19.0-py2-none-any.whl (9.9 kB view details)

Uploaded Python 2

File details

Details for the file django-datatables-view-1.19.0.tar.gz.

File metadata

  • Download URL: django-datatables-view-1.19.0.tar.gz
  • Upload date:
  • Size: 13.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/2.0.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.36.1 CPython/3.6.8

File hashes

Hashes for django-datatables-view-1.19.0.tar.gz
Algorithm Hash digest
SHA256 f39b81646def04113b33ca9ab7a20974c783c8d8599d99135857ccdba63855d9
MD5 fb2aae908a1eae81e3a3c00583688016
BLAKE2b-256 e49dd3e2a796eabf6bb77dd7f859cacfe4f7a159f313a2396a96c7f75a7b741d

See more details on using hashes here.

File details

Details for the file django_datatables_view-1.19.0-py3-none-any.whl.

File metadata

  • Download URL: django_datatables_view-1.19.0-py3-none-any.whl
  • Upload date:
  • Size: 9.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/2.0.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.36.1 CPython/3.6.8

File hashes

Hashes for django_datatables_view-1.19.0-py3-none-any.whl
Algorithm Hash digest
SHA256 beeaec03ed6dc2c9015a63f655ec5e42ac91d095791f0c117ba361b028ad9cfd
MD5 6401133e7aad987c503a382b97f38b52
BLAKE2b-256 bfcf65b6f0937b5ef5d2a32525e8435f29d691c0fea156b8b14f059bafb561c6

See more details on using hashes here.

File details

Details for the file django_datatables_view-1.19.0-py2-none-any.whl.

File metadata

  • Download URL: django_datatables_view-1.19.0-py2-none-any.whl
  • Upload date:
  • Size: 9.9 kB
  • Tags: Python 2
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/2.0.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.36.1 CPython/3.6.8

File hashes

Hashes for django_datatables_view-1.19.0-py2-none-any.whl
Algorithm Hash digest
SHA256 c90dd5a87ec477d5639ba0d042048083c284056edb7ca3b4d66f5bf623fffd18
MD5 98eaae2b5d79126a1f0e91887797de5f
BLAKE2b-256 78d5f947c6b50f351f4c58997d9f2b1ef2c06d5d69aaf62df3d9115ac50a12c4

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