django-datatables-view


Namedjango-datatables-view JSON
Version 1.20.0 PyPI version JSON
download
home_pagehttps://bitbucket.org/pigletto/django-datatables-view
SummaryDjango datatables view
upload_time2022-04-05 09:11:07
maintainer
docs_urlNone
authorMaciej Wiśniowski
requires_python>=3.6
licenseMIT
keywords django datatables
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            [![pypi](https://img.shields.io/pypi/v/django-datatables-view.svg)](https://pypi.python.org/pypi/django-datatables-view/)
[![Downloads](https://pepy.tech/badge/django-datatables-view)](https://pepy.tech/project/django-datatables-view)

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 '
  data' or 'name' in the columns definition provided in the request by DataTables, eg.:
  columns: [{data: 'first_name'}] (only works for datatables 1.10+)
* **order_columns** - list of column names used for sorting (e.g. 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 'data'
  or 'name' in the columns definition provided in the request by DataTables, eg.: columns: [{data: 'first_name'}] (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:

```python

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:

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

### 4. Define HTML + JavaScript ###

Example JS:

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

## Another example of views.py customisation ##

```python
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 further 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.:

```javascript
$(document).ready(function () {
    var dt_table = $('.datatable').dataTable({
        order: [[0, "desc"]],
        columns: [
            {
                data: 'name',
                orderable: true,
                searchable: true
            },
            {
                data: 'description',
                orderable: true,
                searchable: true,
            }
        ],
        searching: true,
        processing: true,
        serverSide: true,
        stateSave: true,
        ajax: TESTMODEL_LIST_JSON_URL
    });
});
```

```python
class TestModelListJson(BaseDatatableView):
    model = TestModel
```



            

Raw data

            {
    "_id": null,
    "home_page": "https://bitbucket.org/pigletto/django-datatables-view",
    "name": "django-datatables-view",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.6",
    "maintainer_email": "",
    "keywords": "django,datatables",
    "author": "Maciej Wi\u015bniowski",
    "author_email": "pigletto@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/50/49/c62bcdbdbab27be93406abab28da141551a31251a8bc08256c2e69323798/django-datatables-view-1.20.0.tar.gz",
    "platform": null,
    "description": "[![pypi](https://img.shields.io/pypi/v/django-datatables-view.svg)](https://pypi.python.org/pypi/django-datatables-view/)\n[![Downloads](https://pepy.tech/badge/django-datatables-view)](https://pepy.tech/project/django-datatables-view)\n\nAbout\n=====\n\ndjango-datatables-view is a base view for handling server side processing for the awesome datatables 1.9.x,\n1.10.x (http://datatables.net).\n\ndjango-datatables-view simplifies handling of sorting, filtering and creating JSON output, as defined\nat: http://datatables.net/examples/server_side/\n\nExample\n=======\n\nExample project that uses django-datatables-view is available\nat: https://bitbucket.org/pigletto/django-datatables-view-example/\n\nUsage\n=====\n\n### 1. Install django-datatables-view ###\n\n    pip install django-datatables-view\n\n### 2. Edit views.py ###\n\n_django_datatables_view_ uses **GenericViews**, so your view should just inherit from base class: **BaseDatatableView**,\nand override few things\n(there is also a DatatableMixin - pure datatables handler that can be used with the mixins of your choice, eg.\ndjango-braces). These are:\n\n* **model** - the model that should be used to populate the datatable\n* **columns** - the columns that are going to be displayed. If not defined then django_datatables_view will look for '\n  data' or 'name' in the columns definition provided in the request by DataTables, eg.:\n  columns: [{data: 'first_name'}] (only works for datatables 1.10+)\n* **order_columns** - list of column names used for sorting (e.g. if user sorts by second column then second column name\n  from this list will be used with order by clause). If not defined then django_datatables_view will look for 'data'\n  or 'name' in the columns definition provided in the request by DataTables, eg.: columns: [{data: 'first_name'}] (only\n  works for datatables 1.10+)\n* **filter_queryset** - if you want to filter your DataTable in some specific way then override this method. In case of\n  older DataTables (pre 1.10) you need to override this method or there will be no filtering.\n* **filter_method** - returns 'istartswith' by default, you can override it to use different filtering method, e.g.\n  icontains: return self.FILTER_ICONTAINS\n\nFor more advanced customisation you might want to override:\n\n* **get_initial_queryset** - method that should return queryset used to populate datatable\n* **prepare_results** - this method should return list of lists (rows with columns) as needed by datatables\n* **escape_values** - you can set this attribute to False in order to not escape values returned from render_column\n  method\n\nThe code is rather simple so do not hesitate to have a look at it. Method that is executed first (and that calls other\nmethods to execute whole logic) is **get_context_data**. Definitely have a look at this method!\n\nSee example below:\n\n```python\n\nfrom django_datatables_view.base_datatable_view import BaseDatatableView\nfrom django.utils.html import escape\n\n\nclass OrderListJson(BaseDatatableView):\n    # The model we're going to show\n    model = MyModel\n\n    # define the columns that will be returned\n    columns = ['number', 'user', 'state', 'created', 'modified']\n\n    # define column names that will be used in sorting\n    # order is important and should be same as order of columns\n    # displayed by datatables. For non-sortable columns use empty\n    # value like ''\n    order_columns = ['number', 'user', 'state', '', '']\n\n    # set max limit of records returned, this is used to protect our site if someone tries to attack our site\n    # and make it return huge amount of data\n    max_display_length = 500\n\n    def render_column(self, row, column):\n        # We want to render user as a custom column\n        if column == 'user':\n            # escape HTML for security reasons\n            return escape('{0} {1}'.format(row.customer_firstname, row.customer_lastname))\n        else:\n            return super(OrderListJson, self).render_column(row, column)\n\n    def filter_queryset(self, qs):\n        # use parameters passed in GET request to filter queryset\n\n        # simple example:\n        search = self.request.GET.get('search[value]', None)\n        if search:\n            qs = qs.filter(name__istartswith=search)\n\n        # more advanced example using extra parameters\n        filter_customer = self.request.GET.get('customer', None)\n\n        if filter_customer:\n            customer_parts = filter_customer.split(' ')\n            qs_params = None\n            for part in customer_parts:\n                q = Q(customer_firstname__istartswith=part) | Q(customer_lastname__istartswith=part)\n                qs_params = qs_params | q if qs_params else q\n            qs = qs.filter(qs_params)\n        return qs\n```\n\n### 3. Edit urls.py ###\n\nAdd typical django's urlconf entry:\n\n```python\nurl(r'^my/datatable/data/$', login_required(OrderListJson.as_view()), name='order_list_json'),\n```\n\n### 4. Define HTML + JavaScript ###\n\nExample JS:\n\n```javascript\n$(document).ready(function () {\n    var oTable = $('.datatable').dataTable({\n        // ...\n        \"processing\": true,\n        \"serverSide\": true,\n        \"ajax\": \"{% url 'order_list_json' %}\"\n    });\n    // ...\n});\n```\n\n## Another example of views.py customisation ##\n\n```python\nfrom django_datatables_view.base_datatable_view import BaseDatatableView\nfrom django.utils.html import escape\n\n\nclass OrderListJson(BaseDatatableView):\n    order_columns = ['number', 'user', 'state']\n\n    def get_initial_queryset(self):\n        # return queryset used as base for further sorting/filtering\n        # these are simply objects displayed in datatable\n        # You should not filter data returned here by any filter values entered by user. This is because\n        # we need some base queryset to count total number of records.\n        return MyModel.objects.filter(something=self.kwargs['something'])\n\n    def filter_queryset(self, qs):\n        # use request parameters to filter queryset\n\n        # simple example:\n        search = self.request.GET.get('search[value]', None)\n        if search:\n            qs = qs.filter(name__istartswith=search)\n\n        # more advanced example\n        filter_customer = self.request.GET.get('customer', None)\n\n        if filter_customer:\n            customer_parts = filter_customer.split(' ')\n            qs_params = None\n            for part in customer_parts:\n                q = Q(customer_firstname__istartswith=part) | Q(customer_lastname__istartswith=part)\n                qs_params = qs_params | q if qs_params else q\n            qs = qs.filter(qs_params)\n        return qs\n\n    def prepare_results(self, qs):\n        # prepare list with output column data\n        # queryset is already paginated here\n        json_data = []\n        for item in qs:\n            json_data.append([\n                escape(item.number),  # escape HTML for security reasons\n                escape(\"{0} {1}\".format(item.customer_firstname, item.customer_lastname)),\n                # escape HTML for security reasons\n                item.get_state_display(),\n                item.created.strftime(\"%Y-%m-%d %H:%M:%S\"),\n                item.modified.strftime(\"%Y-%m-%d %H:%M:%S\")\n            ])\n        return json_data\n```\n\n## Yet another example of views.py customisation ##\n\nThis sample assumes that list of columns and order columns is defined on the client side (DataTables), eg.:\n\n```javascript\n$(document).ready(function () {\n    var dt_table = $('.datatable').dataTable({\n        order: [[0, \"desc\"]],\n        columns: [\n            {\n                data: 'name',\n                orderable: true,\n                searchable: true\n            },\n            {\n                data: 'description',\n                orderable: true,\n                searchable: true,\n            }\n        ],\n        searching: true,\n        processing: true,\n        serverSide: true,\n        stateSave: true,\n        ajax: TESTMODEL_LIST_JSON_URL\n    });\n});\n```\n\n```python\nclass TestModelListJson(BaseDatatableView):\n    model = TestModel\n```\n\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Django datatables view",
    "version": "1.20.0",
    "split_keywords": [
        "django",
        "datatables"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "md5": "ce8c056562a2627b3ba7d55027aa57c7",
                "sha256": "988c941f0c0e8bad308fe21c0456defc7a1e2bec6ce189bdafb586af38eb965d"
            },
            "downloads": -1,
            "filename": "django_datatables_view-1.20.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "ce8c056562a2627b3ba7d55027aa57c7",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.6",
            "size": 9856,
            "upload_time": "2022-04-05T09:11:05",
            "upload_time_iso_8601": "2022-04-05T09:11:05.449798Z",
            "url": "https://files.pythonhosted.org/packages/3b/e7/b0d3c120c34c2ec6a2ccaa46ed2a86e1f4d216b807b2771651f681a73715/django_datatables_view-1.20.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "md5": "6a4d1722c44ea0f51330a7ab7610afa9",
                "sha256": "ec5c2918de4f474213f8b69a466353be81414bff51a2574aff0fdc2eaea172f3"
            },
            "downloads": -1,
            "filename": "django-datatables-view-1.20.0.tar.gz",
            "has_sig": false,
            "md5_digest": "6a4d1722c44ea0f51330a7ab7610afa9",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.6",
            "size": 13312,
            "upload_time": "2022-04-05T09:11:07",
            "upload_time_iso_8601": "2022-04-05T09:11:07.369374Z",
            "url": "https://files.pythonhosted.org/packages/50/49/c62bcdbdbab27be93406abab28da141551a31251a8bc08256c2e69323798/django-datatables-view-1.20.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2022-04-05 09:11:07",
    "github": false,
    "gitlab": false,
    "bitbucket": true,
    "bitbucket_user": "pigletto",
    "bitbucket_project": "django-datatables-view",
    "lcname": "django-datatables-view"
}
        
Elapsed time: 0.05346s