Metadata-Version: 2.4
Name: django-advanced-datatables
Version: 2.1.1
Summary: Django views with javascript filters using Datatables
Author: Ian Jones
Maintainer: Thomas Turner
License-Expression: MIT
Project-URL: Homepage, https://github.com/django-advance-utils/django-advanced-datatables
Project-URL: Upstream, https://github.com/jonesim/django-datatables
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Requires-Python: >=3.6
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: ajax-advanced-helpers>=1.0.1
Requires-Dist: django-advanced-menus>=1.0.0
Requires-Dist: django-advanced-modals>=1.0.0
Provides-Extra: excel
Requires-Dist: openpyxl; extra == "excel"
Dynamic: license-file

[![PyPI version](https://img.shields.io/pypi/v/django-advanced-datatables)](https://pypi.org/project/django-advanced-datatables/)

# django-advanced-datatables

The [django-advance-utils](https://github.com/django-advance-utils) line of Ian Jones's
[django-filtered-datatables](https://github.com/jonesim/django-datatables), forked so that releases can be
cut as the downstream libraries and django-advanced-report-builder need them. The Python package
is still `django_datatables`, so existing imports and `INSTALLED_APPS` entries do not change; only the
pip name does. It depends on [ajax-advanced-helpers](https://github.com/django-advance-utils/ajax-advanced-helpers),
[django-advanced-menus](https://github.com/django-advance-utils/django-advanced-menus) and
[django-advanced-modals](https://github.com/django-advance-utils/django-advanced-modals).

A Django library for building interactive data tables powered by [DataTables.js](https://datatables.net/), with server-side processing, dynamic JavaScript filters, inline editing, and a rich plugin system.

Define your tables in Python using Django models and ORM queries -- columns, filters, sorting, annotations, and rendering are all configured from your views, with minimal JavaScript required.

## Features

- **20+ column types** -- dates, currency, booleans, links, many-to-many, choice fields, lambdas, and more
- **AJAX and non-AJAX modes** -- load data dynamically or render inline
- **JavaScript filters** -- pivot, tag, select2, date range, and text search filters
- **Modal filter dialogs** -- form-based filtering with crispy-forms support
- **Inline editing** -- edit cells directly in the table with select2 dropdowns or text inputs
- **Row selection** -- checkbox-based row selection with bulk actions
- **Plugins** -- column totals, conditional row colouring, drag-and-drop reordering, save/restore filter state
- **Data export** -- Excel (.xlsx) download and clipboard copy
- **Client-side rendering** -- render functions for badges, links, conditional formatting, and lookups
- **Django ORM integration** -- annotations, aggregations, foreign key traversal, callable model methods
- **Model-defined columns** -- configure columns directly on your Django models via an inner `Datatable` class
- **Multiple tables per view** -- display several tables on a single page
- **Spreadsheet mode** -- JSpreadsheet integration for spreadsheet-like editing
- **Form widgets** -- `DataTableWidget` and `DataTableReorderWidget` for use in Django forms
- **Mobile responsive** -- automatic device detection with per-device column visibility
- **Redis caching** -- optional cache layer with signal-based invalidation

## Installation

```bash
pip install django-advanced-datatables
```

Add to your `INSTALLED_APPS`:

```python
INSTALLED_APPS = [
    # ...
    'django_datatables',
    'ajax_helpers',
    # ...
]
```

Include the required JavaScript and CSS in your base template. The library depends on DataTables.js, jQuery, and Bootstrap.

## Quick Start

### 1. Define a view

```python
from django_datatables.datatables import DatatableView

class CompanyList(DatatableView):
    model = Company

    @staticmethod
    def setup_table(table):
        table.add_columns(
            'id',
            'name',
            'dissolved',
        )
```

### 2. Wire up the URL

```python
urlpatterns = [
    path('companies/', CompanyList.as_view(), name='company-list'),
]
```

### 3. Use the template

The default template renders a complete DataTables table. You can override it via `template_name` on your view.

## Usage

### Adding Columns

Columns can be added in several ways:

```python
def setup_table(table):
    table.add_columns(
        'name',                                          # model field name
        ('id', {'title': 'ID', 'width': '30px'}),       # tuple with options
        DateColumn('date_entered', column_name='Date'),  # column class instance
        'company__name',                                 # foreign key traversal
        'Tags',                                          # model-defined column
    )
```

**String prefix syntax** for quick column options:
- `.field` -- hidden column (still available for filtering/rendering)
- `_field` -- calculated column (not from the database)
- `$field` -- secure column (hidden from client source)

### Column Types

| Column | Purpose |
|--------|---------|
| `DatatableColumn` | Standard column with customisable `row_result` and `col_setup` |
| `DateColumn` | Formats dates (dd/mm/yyyy) |
| `DateTimeColumn` | Formats datetimes |
| `ChoiceColumn` | Maps integer choices to display labels |
| `CurrencyColumn` | Currency formatting |
| `BooleanColumn` | Boolean display |
| `ColumnLink` | Clickable link using Django URL names |
| `ManyToManyColumn` | Displays many-to-many relationships |
| `CallableColumn` | Calls a model method |
| `LambdaColumn` | Processes values with a lambda function |
| `SelectColumn` | Row selection checkboxes |
| `TextFieldColumn` | Long text with truncation |

### Model-Defined Columns

Configure columns directly on your models:

```python
class Company(models.Model):
    name = models.CharField(max_length=80)

    class Datatable(DatatableModel):
        # Annotation-based column
        people = {'annotations': {'people': Count('person__id')}}

        # Link column
        collink_1 = ColumnLink(title='View', field=['id', 'name'], url_name='company-detail')

        # Column list (renders multiple fields as a group)
        company_list = ['id', 'name']

        # Custom column class
        class ModelIdColumn(DatatableColumn):
            def col_setup(self):
                self.field = 'id'
                self.title = 'Custom ID'
```

These columns can then be referenced by name in `add_columns()`:

```python
table.add_columns('id', 'name', 'people', 'collink_1', 'ModelIdColumn')
```

### Filters

```python
def setup_table(table):
    table.add_columns('id', 'name', 'company__name', 'Tags')

    # JavaScript filters
    table.add_js_filters('tag', 'Tags')                    # tag filter
    table.add_js_filters('select2', 'company__name')       # select2 dropdown
    table.add_js_filters('totals', 'id')                   # totals/count filter
    table.add_js_filters('date', 'date_entered')           # date range
    table.add_js_filters('expand', 'level', id_column='id')  # tree expand

    # ORM-level filters
    table.filter = {'company__id': 1}
    table.exclude = {'dissolved': True}
```

#### Modal Filter (form-based)

```python
from django_datatables.modal_filter.mixins import DatatableFilterMixin, DatatableFilterField

class CompanyList(DatatableFilterMixin, DatatableView):
    model = Company
    filter_fields = [
        DatatableFilterField('Company Name', CharField(required=False), datatable_field='name__contains'),
        DatatableFilterField('Tags', FilterModelMultipleChoiceField(queryset=Tags.objects.all()), datatable_field='tags__in'),
    ]
```

### Sorting

```python
table.sort('name')           # ascending
table.sort('-name')          # descending
table.sort('name', '-id')   # multi-column
```

### Column Search

Per-column search boxes appear below the header by default. Customise them:

```python
table.add_columns(
    ColumnBase(column_name='status', field='dissolved',
               col_search_select=[['true', 'Dissolved'], ['false', 'Active']]),
    ColumnBase(column_name='order', field='order', no_col_search=True),
)
table.table_options['no_col_search'] = True  # disable all column search
```

### Client-Side Rendering

Render functions transform cell data in the browser without extra server round-trips:

```python
from django_datatables.helpers import render_replace, row_button

table.add_columns(
    # Badge rendering
    ColumnBase(column_name='people', field='people', render=[
        render_replace(column='people', html='<span class="badge badge-primary">%1%</span>'),
    ]),

    # Row action button
    ColumnBase(column_name='action', render=[row_button('delete', 'Delete')]),

    # Lookup-based rendering
    ('id', {'title': 'Status', 'render': [
        {'function': 'ReplaceLookup', 'html': '%1%', 'var': '%1%'}
    ], 'lookup': [[1, 'Active'], [2, 'Inactive']]}),
)
```

Available render functions: `Replace`, `ReplaceLookup`, `Html`, `MergeArray`, `ValueInColumn`.

### Plugins

```python
from django_datatables.plugins.colour_rows import ColourRows
from django_datatables.plugins.column_totals import ColumnTotals
from django_datatables.plugins.reorder import Reorder

# Conditional row colouring
table.add_plugin(ColourRows, [
    {'column': 'status', 'values': {'overdue': 'table-danger', 'pending': 'table-warning'}}
])

# Column totals in footer
table.add_plugin(ColumnTotals, {
    'amount': {'sum': True},
    'id': {'text': 'Total', 'css_class': 'text-danger'},
    'percentage': {'sum': 'percentage', 'numerator': 'vans', 'denominator': 'total', 'decimal_places': 1},
})

# Drag-and-drop row reordering
table.add_plugin(Reorder)
```

### Inline Editing

```python
def setup_table(table):
    table.edit_fields = ['first_name', 'title']
    table.edit_options = {'company__name': {'select2': True}}
```

### Row Actions (AJAX Commands)

Handle row-level actions from buttons:

```python
class MyView(DatatableView):
    ajax_commands = ['row']

    def row_delete(self, **kwargs):
        return self.command_response('delete_row', row_no=kwargs['row_no'], table_id=kwargs['table_id'])

    def row_toggle_tag(self, **kwargs):
        row_data = json.loads(kwargs['row_data'])
        # ... process action ...
        table = self.tables[kwargs['table_id']]
        return table.refresh_row(self.request, kwargs['row_no'])
```

### Refreshing Many Rows

`table.refresh_rows(request, row_ids)` answers with one `refresh_rows` command carrying every row
asked for, read in one query and keyed by row id (`'i<id>'`); the page repaints them and redraws
once. A row gone, or filtered out of the table since, is left out. The table's own filter still
applies, whether a dict or a `Q`.

```python
return table.refresh_rows(self.request, ['i12', 'i15', 'i19'])
```

From the page, `{function: 'refresh_rows', table_id: 'people', row_nos: ['i12', 'i15']}` with no
`rows` asks the view for them: `DatatableView.row_refresh_many` answers it, given
`ajax_commands = ['row']`.

### Data Export

```python
from django_datatables.downloads.excel_download import ExcelDownload
from django_datatables.downloads.clipboard import ClipboardCopy

class MyView(ExcelDownload, ClipboardCopy, DatatableView):
    model = MyModel

    def setup_menu(self):
        self.add_menu('menu', 'buttons').add_items(
            self.download_menu_item(),
            self.clipboard_menu_item(),
        )
        super().setup_menu()
```

### Multiple Tables Per View

```python
class TwoTableView(DatatableView):
    template_name = 'two_tables.html'

    def add_tables(self):
        self.add_table('t1', model=Company)
        self.add_table('t2', model=Person)

    @staticmethod
    def setup_t1(table):
        table.add_columns('id', 'name')

    @staticmethod
    def setup_t2(table):
        table.add_columns('id', 'first_name')
```

### Non-Model Data

Load data from any source (JSON files, APIs, etc.):

```python
class JsonTableView(DatatableView):

    @staticmethod
    def setup_table(table):
        table.add_columns(
            ColumnBase(column_name='field1'),
            ColumnBase(column_name='field2'),
        )

    @staticmethod
    def get_table_query(table, **kwargs):
        with open('data.json') as f:
            return json.load(f)
```

### Custom Column Classes

```python
from django_datatables.columns import DatatableColumn

class FullName(DatatableColumn):
    def col_setup(self):
        self.field = ['first_name', 'surname']

    def row_result(self, data_dict, _page_results):
        return f'{data_dict["first_name"]} {data_dict["surname"]}'
```

### Escaping Cells

DataTables writes every cell into the page as HTML, and a column hands it what it read as it is stored. So a
name somebody typed with a tag in it runs in the browser of everyone who opens the table, unless its column
escapes it. Turn on escaping for every cell instead:

```python
# settings.py
DATATABLES_ESCAPE_CELLS = True
```

Each cell is then escaped on its way to the page, unless the code that built it marked it safe. `format_html`,
`mark_safe` and `escape` all return a `SafeString`, so markup a column builds round a name keeps working, and
the name in it stays escaped:

```python
from django.utils.html import format_html

class StatusColumn(DatatableColumn):
    def row_result(self, data, _page_data):
        return format_html('<span class="badge">{}</span>', data[self.field])
```

A column that returns markup as a plain string shows its tags as text: harmless, and easy to see. A column
whose cells the page reads as data rather than shows (a lookup's key, a url for a script) opts out with the
class attribute `page_escape = False`, or the keyword `page_escape=False`. A column that builds markup of its
own round text it reads can override `page_value(value)` to escape the text alone on its way to the page, as
`TextFieldColumn` does to keep its line breaks. A single table follows its own `escape_cells` (`True` or
`False`) when it has one, whatever the setting.

A lookup goes the same way. The `[key, label]` pairs a column hands the page for a `ReplaceLookup` render (a
`ManyToManyColumn`'s names, a `BooleanColumn`'s `replace`) have their labels escaped unless marked safe, and
their keys escaped as the cells are, so a lookup keyed by stored text still finds its cells. A `BooleanColumn`'s
`replace` is html by definition and is marked safe for you.

Only the page is escaped. `get_table_array` still gives the Excel download, the clipboard and a spreadsheet
the text as it was typed; the page writers use `get_page_array`. It is off unless the setting turns it on.

### Table Options

Common options passed via `table.table_options`:

```python
table.table_options['pageLength'] = 50
table.table_options['no_col_search'] = True
table.table_options['scrollX'] = True
table.table_options['ajax_url'] = '/custom/ajax/url/'
table.table_options['row_href'] = [render_replace(column='id', html='/detail/%1%/')]
```

### While a table is built

The table is written into the page before the script that builds it runs, and that script waits for the document
to be ready. Until then the table is hidden, keeping its space, and a spinner with "Loading..." shows over it. Both go
once DataTables has built it.

`datatables/table.html` draws the table with the class `datatable-pending` and the message (`.datatable-loading`) as
the element straight before it, and takes the class off once the table has been set up, whether or not that worked.
`datatables.css` hides `table.datatable-pending:not(.dataTable)` and shows the message only while the table after it
is still pending. A template of your own that draws the table instead needs all three: the class, the message
straight before the table, and taking the class off after set-up.

### Column permissions

Name a function in `settings.DJANGO_ADVANCED_PERMISSION_CHECK` and `add_columns` asks it about every
column:

```python
DJANGO_ADVANCED_PERMISSION_CHECK = 'myproject.permissions.check'

def check(request, kind, name, obj=None):  # kind 'column', name the column_name, obj the table
    return not (name == 'margin' and obj.table_id == 'orders')
```

A refused column is left out of the table altogether: it is not drawn, not queried, not exported
and not offered in the column chooser, so its data never reaches the browser. `sort()`,
`remove_columns()` and `add_js_filters()` skip a refused column rather than failing, whether it is named
in full, by field or by the last part of its name; a js filter that sums a refused column is left out
as well. Anything else that looks a refused column up, such as `table.column()`, raises
`RefusedColumnError`, a `DatatableError`. The refused columns are in `table.refused_columns`, keyed by
name. Refusing the id column leaves rows that cannot be refreshed or linked to, and logs a warning.
Name columns rather than give positions in `table_options` (`order`, `column_id`): a refused column
moves every column after it, and only positions worked out from names are moved with them.

`request` is `None` for a table built without a view, such as one a project builds for tree-grid rows
or an export, so a check should allow for that. With the setting unset every column is added. A table
built with `cache_data` keeps a separate copy for each set of refused columns. The library's own
tables (the column chooser, the multi-select widget's tick column, `OrderedDatatable`'s handle columns)
pass `check_permissions=False` to `add_columns`, which a project can do too.
ajax-advanced-helpers and django-advanced-modals read the same setting, each
with a `kind` of its own.

### Reordering rows

`ReorderDatatableView` shows a model's rows in the order of its `order_field` and saves the order a drag
leaves them in. Rows are shown, and a drag is read, in `row_order`: by default the order field and then the
primary key, so rows that share a value always come in the same order. Set `row_order` on the view (for
example `('order', 'name', 'pk')`) to break ties another way.

A drag saves each row whose position changed with `save()`, in one transaction, so `auto_now` fields and
signals see it. A handle let go where it was saves nothing. Positions are whole numbers from 0, saved as sent; a
payload that is not a list of `[position, pk]` pairs, or has a negative position, is ignored. A sort for a table
the view does not have raises `BadRequest`.

`reorder(model, order_field, sort_data, order_by=None)` saves a drag outside the view. Pass `order_by` as the
order the rows were shown in, and a drag that leaves them in that order writes nothing. Without it the shown
order is not known, so the positions sent are always saved.

Override `can_reorder()` to decide who may drag. When it returns `False` the rows are shown in order with no
handle column and no dragging, and a sort sent anyway raises `PermissionDenied`. The table is built with the
view, so column permission checks are given its request.

## Demo Application

A Docker-based demo is included with sample data and 15+ examples covering filters, plugins, editing, rendering, and more.

```bash
docker-compose up
```

Then visit [http://localhost:8006](http://localhost:8006).

## Dependencies

- Python >= 3.6
- Django
- [ajax-advanced-helpers](https://github.com/django-advance-utils/ajax-advanced-helpers) >= 1.0.1

Optional:
- `openpyxl` -- for Excel export
- `redis` -- for table caching

## License

MIT
