- Author:
- yuvi
- Posted:
- January 14, 2014
- Language:
- Python
- Version:
- Not specified
- Score:
- 0 (after 0 ratings)
jQuery dataTables is a fantastic and powerful client-side plugin, which has many capabilities.
There are many libraries out there that easily integrate it with django with little to no effort. However, they provide everything out of the box, which isn't always the most flexible solution. I also think beginners have a lot to learn from not using already created tools.
So, finding the general examples out there lacking, I though I'd hatch out a quick example of how to very basically integrate the two.
I supply two lists at the top which define how to order the fields and which are searchable (quite similar to the one defined in the admin site) and later everything is figured from there.
Of course, for a little more complex implementation (say using a method instead of a field) this will not work (since getattr doesn't automatically call a function if it is a function), but this snippet isn't supposed to provide everything but a very basic usage example, which can be very quickly expended in any way needed.
Anyway, this snippet should work on all django versions and all dataTables versions without a hitch.
last note- I use cStringIO
with json.dump
out of good personal experience with that settings, though it might not be the best way to serialize the data.
Good luck, share use and enjoy, ~yuvi
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | from django.http import HttpResponse
from django.db.models import Q, CharField
import json
from cStringIO import StringIO
def datatables_view(request):
objects = MyModel.objects.all()
list_display = ['field1', 'field2', ...]
list_filter = [f.name for f in MyModel._meta.fields if isinstance(f, CharField)] #a simple way to bring all CharFields, can be defined in specifics
# count total items:
iTotalRecords = objects.count()
#filter on list_filter using __contains
search = request.GET['sSearch']
queries = [Q(**{f+'__contains' : search}) for f in list_filter]
qs = reduce(lambda x, y: x|y, queries)
objects = objects.filter(qs)
#sorting
order = dict( enumerate(list_display) )
dirs = {'asc': '', 'desc': '-'}
ordering = dirs[request.GET['sSortDir_0']] + order[int(request.GET['iSortCol_0'])]
objects = objects.order_by(order_by)
# count items after filtering:
iTotalDisplayRecords = objects.count()
# finally, slice according to length sent by dataTables:
start = int(request.GET['iDisplayStart'])
length = int(request.GET['iDisplayLength'])
objects = objects[ start : (start+length)]
# extract information
data = [map(lambda field: getattr(obj, field), list_display) for obj in objects]
#define response
response = {
'aaData': data,
'iTotalRecords': iTotalRecords,
'iTotalDisplayRecords': iTotalDisplayRecords,
'sEcho': request.GET['sEcho']
}
#serialize to json
s = StringIO()
json.dump(response, s)
s.seek(0)
return HttpResponse(s.read())
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.