Last active
September 13, 2019 11:17
-
-
Save sanjaykrishnan/52b0f33ffd16ba945f34fa8952db2412 to your computer and use it in GitHub Desktop.
jquery datatables with django
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db.models import QuerySet | |
from django.views import View | |
class DataTableMixin(View): | |
queryset = None | |
columns = None | |
serializer_class = None | |
page_size = 10 | |
def get_queryset(self): | |
""" | |
Get the list of items for this view. | |
This must be an iterable, and may be a queryset. | |
Defaults to using `self.queryset`. | |
This method should always be used rather than accessing `self.queryset` | |
directly, as `self.queryset` gets evaluated only once, and those results | |
are cached for all subsequent requests. | |
You may want to override this if you need to provide different | |
querysets depending on the incoming request. | |
(Eg. return a list of items that is specific to the user) | |
""" | |
assert self.queryset is not None, ( | |
"'%s' should either include a `queryset` attribute, " | |
"or override the `get_queryset()` method." | |
% self.__class__.__name__ | |
) | |
queryset = self.queryset | |
if isinstance(queryset, QuerySet): | |
# Ensure queryset is re-evaluated on each request. | |
queryset = queryset.all() | |
return queryset | |
def get_columns(self): | |
""" | |
Return the column names to be used for ordering as integer keys and string values. | |
For Ex: {0: 'activeuser', 1: 'firstname', 2: 'username', 3: 'email', 4: 'department__name'} | |
""" | |
assert self.columns is not None, ( | |
"'%s' should either include a `serializer_class` attribute, " | |
"or override the `get_serializer_class()` method." | |
% self.__class__.__name__ | |
) | |
return self.columns | |
def get_serializer(self, *args, **kwargs): | |
""" | |
Return the serializer instance that should be used for validating and | |
deserializing input, and for serializing output. | |
""" | |
serializer_class = self.get_serializer_class() | |
kwargs['context'] = self.get_serializer_context() | |
return serializer_class(*args, **kwargs) | |
def get_serializer_class(self): | |
""" | |
Return the class to use for the serializer. | |
Defaults to using `self.serializer_class`. | |
You may want to override this if you need to provide different | |
serializations depending on the incoming request. | |
(Eg. admins get full serialization, others get basic serialization) | |
""" | |
assert self.serializer_class is not None, ( | |
"'%s' should either include a `serializer_class` attribute, " | |
"or override the `get_serializer_class()` method." | |
% self.__class__.__name__ | |
) | |
return self.serializer_class | |
def get_serializer_context(self): | |
""" | |
Extra context provided to the serializer class. | |
""" | |
return { | |
'request': self.request, | |
'view': self | |
} | |
def get(self, request): | |
queryset = self.get_queryset() | |
result_dict = {} | |
draw = request.GET.get('draw', None) | |
start = int(request.GET.get('start', 0)) | |
tab_length = int(request.GET.get('length', self.page_size)) | |
end = start + tab_length | |
columns = self.get_columns() | |
for col_index in range(0, len(columns)): | |
col_order = request.GET.get('order[' + str(col_index) + '][column]', None) | |
col_order_dir = request.GET.get('order[' + str(col_index) + '][dir]', None) | |
if col_order: | |
break | |
result_dict['draw'] = draw | |
result_dict['recordsTotal'] = queryset.count() | |
result_dict['recordsFiltered'] = queryset.count() | |
if col_order: | |
if col_order_dir == 'asc': | |
queryset = queryset.order_by(columns[int(col_order)])[start:end] | |
else: | |
queryset = queryset.order_by('-' + columns[int(col_order)])[start:end] | |
else: | |
queryset = queryset[start:end] | |
result_dict['data'] = self.get_serializer(queryset, many=True).data | |
return JsonResponse(result_dict) | |
class UserAjaxView(DataTableMixin): | |
queryset = Users.objects.all() | |
coloumns = {0: 'activeuser', 1: 'username', 2: 'firstname', | |
3: 'lastname', 4: 'dob', 5: 'email'} | |
serializer_class = UserSerializer |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
$(document).ready(function(){ | |
var user_table = $('#users_list').DataTable({ | |
"order": [], | |
'paging': true, | |
'lengthChange': false, | |
'searching': false, | |
'ordering': true, | |
'info': true, | |
'rowId': 2, | |
'autoWidth': false, | |
"processing": true, | |
"serverSide": true, | |
"ajax": "ajax-list/", | |
"columns": [ | |
{ "data": "activeuser" }, | |
{ "data": "username" }, | |
{ "data": "firstname" }, | |
{ "data": "lastname" }, | |
{ "data": "dob" }, | |
{ "data": "email" } | |
] | |
}); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment