PK |€INl"Eîî î datatables_ajax/datatables.pyclass DjangoDatatablesServerProc(object):
def __init__(self, request, model, columns):
"""
model = StatoUtenzaCorso
columns = ['pk', 'cliente', 'corso', 'altro',
'contattato_mediante', 'data_creazione', 'stato']
"""
self.columns = columns
self.model = model
self.dt_ajax_request = dict(request.GET)
# queryset attributes
self.aqs = None
self.fqs = None
# response object will be similar to this, but with datas!
# Since DataTables never sends draw as 0, it should never be
# returned as 0 (assuming that was the issue). As the documentation
# says, it should be returned as the same value that was sent
# (cast as an integer)
self.d = {'draw': int(self.dt_ajax_request['draw'][0]),
'recordsTotal': 0,
'recordsFiltered': 0,
'data': []}
self.lenght = self.dt_ajax_request['length']
self.start = self.dt_ajax_request['start']
self.search_key = self.dt_ajax_request['search[value]']
self.order_col = self.dt_ajax_request['order[0][column]']
self.order_dir = self.dt_ajax_request['order[0][dir]']
# casting
for field in ['lenght', 'start', 'search_key',
'order_col', 'order_dir']:
attr = getattr(self, field)
if isinstance(attr, list):
setattr(self, field, attr[0])
else:
setattr(self, field, attr)
if getattr(self, field).isdigit():
setattr(self, field, int(attr))
def get_queryset(self):
"""
Overload me.
The query must be customized to get it work
"""
if self.search_key:
self.aqs = self.model.objects.filter(
Q(cliente__nome__icontains=self.search_key) | \
Q(cliente__cognome__icontains=self.search_key) | \
Q(cliente__nominativo__icontains=self.search_key) | \
Q(corso__nome__istartswith=self.search_key) | \
Q(contattato_mediante__nome__istartswith=self.search_key) | \
Q(altro__nome__istartswith=self.search_key) \
)
else:
self.aqs = self.model.objects.all()
def get_ordering(self):
"""
overload me if you need different ordering approach
"""
if not self.aqs:
self.get_queryset()
# if lenght is -1 means ALL the records, sliceless
if self.lenght == -1:
self.lenght = self.aqs.count()
# fare ordinamento qui
# 'order[0][column]': ['2'],
# bisogna mappare la colonna con il numero di sequenza eppoi
# fare order_by
if self.order_col:
self.col_name = self.columns[self.order_col]
if self.order_dir == 'asc':
self.aqs = self.aqs.order_by(self.col_name)
else:
self.aqs = self.aqs.order_by('-'+self.col_name)
def get_paging(self):
# paging requirement
self.get_ordering()
self.fqs = self.aqs[self.start:self.start+self.lenght]
def fill_data(self):
"""
overload me if you need some clean up
"""
if not self.fqs:
self.get_paging()
for r in self.fqs:
cleaned_data = []
for e in self.columns:
# this avoid null json valueù
v = getattr(r, e)
if v:
cleaned_data.append(v.__str__())
else:
cleaned_data.append('')
self.d['data'].append( cleaned_data )
self.d['recordsTotal'] = self.model.objects.count()
self.d['recordsFiltered'] = self.aqs.count()
def get_dict(self):
if not self.d['data']:
self.fill_data()
return self.d
PK äƒINØæA A 4 django_datatables_ajax-0.6.dist-info/DESCRIPTION.rst# Django Datatables server processing
Lightweight Django class for a full Datatables server processing implementation.
https://datatables.net/examples/data_sources/server_side.html
After hanging around for a good integration of Datatables server processing in Django, I tested the things I found on internet but they all have the same problem, they cannot manage the ForeignKey relations as well. After all, I made it by myself.
This code was tested on Datatables 1.10.+ and Django 1.10.+.
To get it works just put datatables in your html template, like this:
```html
```
Requirements
------------
Download your preferred DataTables release from [here](https://datatables.net/download/).
Setup and examples
------------------
Install package in your Python environment.
````
pip install git+https://github.com/peppelinux/django-datatables-ajax.git
````
Create a view
````
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.http import HttpResponse, Http404
from django.http.response import HttpResponseRedirect
from django.http import JsonResponse
from .datatables import DjangoDatatablesServerProc
@login_required
def datatable_data(request):
radcheck = get_radcheck_active(request)
radius_accounts = _get_radius_accounts(request, radcheck)
model = RadiusPostAuth
columns = ['pk', 'username', 'reply', 'calling_station_id', 'date']
base_query = model.objects.filter(username__in=[i.username for i in radius_accounts]).exclude(calling_station_id='').order_by('-date')
class DTD(DjangoDatatablesServerProc):
def get_queryset(self):
if self.search_key:
self.aqs = base_query.filter(
Q(username__icontains=self.search_key) | \
Q(reply__icontains=self.search_key) | \
Q(calling_station_id__icontains=self.search_key))
else:
self.aqs = base_query.filter(username=radcheck.username)
dtd = DTD( request, model, columns )
return JsonResponse(dtd.get_dict())
````
Create an url resource
````
from django.conf.urls import include, url
from django.contrib.auth.decorators import login_required
from .views import *
urlpatterns = [
url(r'^datatable.json$', login_required(StatoUtenzaCorso_DTJson), name='datatable_json'),
]
````
PK äƒIN³s^’ï ï 2 django_datatables_ajax-0.6.dist-info/metadata.json{"classifiers": ["Development Status :: 5 - Production/Stable", "License :: OSI Approved :: BSD License", "Programming Language :: Python :: 3 :: Only", "Operating System :: POSIX :: Linux"], "extensions": {"python.details": {"contacts": [{"email": "giuseppe.demarco@unical.it", "name": "Giuseppe De Marco", "role": "author"}], "document_names": {"description": "DESCRIPTION.rst"}, "project_urls": {"Home": "https://github.com/peppelinux/django-datatables-ajax"}}}, "extras": [], "generator": "bdist_wheel (0.24.0)", "license": "BSD", "metadata_version": "2.0", "name": "django-datatables-ajax", "run_requires": [{"requires": ["django"]}], "summary": "Lightweight Django class for a full Datatables server processing implementation", "version": "0.6"}PK äƒINsRG 2 django_datatables_ajax-0.6.dist-info/top_level.txtdatatables_ajax
PK äƒIN[÷C\ \ * django_datatables_ajax-0.6.dist-info/WHEELWheel-Version: 1.0
Generator: bdist_wheel (0.24.0)
Root-Is-Purelib: true
Tag: py3-none-any
PK äƒIN!<