Skip to main content

Django Datatables

The django datatables library makes creating tables that make use of the datatables library simple, reusable, pythonic, djangoesque, and quite a bit fun.

Project Goals

  • Allow creation of tables in a style similar to django forms.
  • Remove tedious editing of datatables javascript config to match columns.
  • Configure ajax URLs automagically.
  • Simplify use of Django style URLs within the datatable

Installation

pip install classy-django-datatables

Quick Setup

Download the library and place it somewhere accessable in your PYTHONPATH. The following is a basic example to demonstrate the ease to get up and running.

settings.py

Add django_datables to the INSTALLED_APPS setting.

INSTALLED_APPS = [
    ...
    'django_datatables',
    ...
]

urls.py

Add the following line to urls.py.

    url(r'^__django_datatables__/', include('django_datatables.urls')),

views.py

    from django_datatables.datatable import *
    from django_datatables import column

    class StudyListDatatable(Datatable):
        code_name = column.TextColumn()

        class Meta:
            model = Study

    def study_list(request)
        datatable = StudyListDatatable()
        return render(request, 'datatables_demo.html',
            {"datatable": datatable}
        )

Template

    {{datatable.render}}

Building Up

Custom Title/Value

In the example shown, the code_name, as the variable name is automatically used to fetch the field and then used as the header for the column. There will often be cases where the variable name will not coincide to either of these and can be overritten with the following:

    created_date = column.TextColumn(title='Made on')
    scientist = column.TextColumn(value='scientist__scientist_name')

CSS Class

A css class to apply to each cell in the column.

    scientist = column.TextColumn(css_class='text-danger')

Joined tables

Fields in joined tables are accessed using the same syntax used in django.

    scientist = column.TextColumn(value='scientist__scientist_name')

Adding links

Links support django's URL dispatcher. Just add the URL name to the link attribute and the arguments that get passed to the link. You don't even need the column listed -- Django Datables will integentally fetch the needed field and populate the links accordingly.

    code_name = column.TextColumn(link='edit_study', link_args=['slug'])

Data from multiple fields

To pull data from multiple fields into one column, declare the column as a StringColumn. If needed, add the fields to be requested from the database in the Meta.extra_fields attribute. Finally, render the desired with the render_* method.

    name = column.StringColumn()
    class Meta:
        model = Employee
        extra_fields = ('first_name', 'last_name')
    def render_name(self, row):
        return "{} {}".format(row['first_name'], row['last_name']).strip()

Other Querysets

The initial queryset can be overridden if a more complex query is needed, or if a default filter needs to be in place.

   def get_initial_queryset(self, request):
        return Employee.objects.filter(manager=request.user)

Meta

model: the primary model to be displayed in the table

    model = Study

order_columns: a list of the columns that can be sorted

    order_columns = ['study_name', 'created_date', 'modified_date', 'scientist']

initial_order: the inital sort of the table

    initial_order = ['created_date', 'scientist']

searching: (default: false) Enable the search box

search_fields the fields that the search box will search for content. This can be more finely controlled in the filter_by_search() method.

    search_fields = ['study_name', 'code_name', 'scientist__scientist_name']

title: The title of the report. Only used for the filename and sheet name of the excel export.

    title = "Study List"

export_to_excel: If openpyxl is installed and set to true, will display a link to download an excel file containing all rows in the table.

    export_to_excel = True

Custom rendering

Any field can have it's render method extended using render_*

    def render_code_name(self, value):
        return value.lower()

    def render_created_date(self, value):
        return value.strftime("%m/%d/%Y")

Columns

Attributes

  • title - Displayed in the header
  • css_class - A CSS class to apply to the column
  • value - The value in the database to use
  • link - The django url name this column will link to
  • link_args - the link arguments

The following column types are available in the django_datatables.column module.

TextColumn: A standard column that will display the contents of a single field.

ConstantTextColumn(text): Will display text independant of the database. Ex: Edit, or Delete

StringColumn: A column that will render text using multiple fields. Request the data with Meta.extra_fields and format the text with the render_* method.

CheckBoxColumn: Render a checkbox.

GlyphiconColumn(icon): Displayan icon from bootstrap's v3 glyphicon set.

FontAwesome4(icon): Display an icon from the Font Awesome 4 library. Ex: column.FontAwesome4Column('stop-circle fa-2x') (Must manually include bootstrap in source.)

DateColumn: Render a date in Y-m-d format.

Filters

Filter forms can be connected to the datatable by assigning a django form to Meta.filter_form. Naming the fields as django queryset keys (eg: name__icontains, count__gte) will auto filter the form as needed.

Filter example

class EmployeeFilterForm(forms.Form):
    last_name__icontains = forms.CharField(label="Last Name", required=False)


class StudyListDatatable(datatable.Datatable):

    name = column.StringColumn()
    class Meta:
        model = Employee
        filter_form = EmployeeFilterForm
        extra_fields = ('first_name', 'last_name')
    def render_name(self, row):
        return "{} {}".format(row['first_name'], row['last_name']).strip()

In the template, the form can be displayed with the following. There /must/ be a .datatable-form class attached to the form.

    <form class='datatable-form'>
        {{datatable.filter_form}}
        <button type="submit">Submit</button>
    </form>

Permissions

It's important to not just lock down the view, but also the ajax call that retrieves the data. Fortunately, authentication is easily handled with mixins. Django 1.9 ships with LoginRequiredMixin, UserPassesTestMixin, and PermissionRequiredMixin which handle most use cases. Ensure the permission-related mixins are stated first.

More information regarding mixins can be found at the official django authentication doc.

    from django.contrib.auth.mixins import LoginRequiredMixin

    class EmployeeListDatatable(LoginRequiredMixin, datatable.Datatable):
        ...

Metadata

Release files for classy-django-datatables 1.0.8

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for classy-django-datatables 1.0.8
File Size Uploaded
classy-django-datatables-1.0.8.tar.gz 13.9 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for classy-django-datatables 1.0.8
File Interpreter ABI Platform
classy_django_datatables-1.0.8-py3-none-any.whl Python 3 none any Details

Total release size: 29.8 kB

Release files / classy-django-datatables-1.0.8.tar.gz

Download URL classy-django-datatables-1.0.8.tar.gz
Size 13.9 kB
Tags Source
SHA-256 checksum
How to use checksums
cc9a12b61eb577da3f457b985ed7af6d9ea21735308f569c200dbe40749761f7
BLAKE2b-256 checksum
How to use checksums
c873794a3fd8c9f02f79abf0d1c362849797c884752b5f5f8204b36508f2e208
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/1.11.0 pkginfo/1.4.2 requests/2.19.1 setuptools/40.2.0 requests-toolbelt/0.8.0 tqdm/4.25.0 CPython/3.6.4

Release files / classy_django_datatables-1.0.8-py3-none-any.whl

Download URL classy_django_datatables-1.0.8-py3-none-any.whl
Size 15.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d4b06a91ced46deb4b55295c649c6ffec1fec14ccc29e1f618bdf34d950b1967
BLAKE2b-256 checksum
How to use checksums
1f7a21663a6d50533e437ab2b0d993d1b5d1c6353d634d495a81df6d0dfa810d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/1.11.0 pkginfo/1.4.2 requests/2.19.1 setuptools/40.2.0 requests-toolbelt/0.8.0 tqdm/4.25.0 CPython/3.6.4

Release history Release notifications | RSS feed

This release

1.0.8 This release

2 release files

1.0.7

2 release files

1.0.6

2 release files

1.0.4

2 release files

1.0.3

2 release files

1.0.2

2 release files

1.0.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page