2

Integrating the DataTables plugin was straightforward and getting the Editor add-on integrated was also pretty painless - up to a point. However, the client/server side has been a bear for me.

The following is the JavaScript for DataTables and Editor. The part I cannot resolve is this snippet from the code that follows

var table = $('#theader').DataTable( { **bProcessing: true, bServerSide: true, start: 1, dataSrc: "id", sAjaxSource: 'load_user_json',** } 

After the JavaScript is the html code relevant to the JavaScript.

The examples given, on the DataTables/Editor site, use PHP on the server side. I know zero about PHP and I cannot figure out how to replace it with Python to pass back JSON (via the code snippet above) to the Javascript that follows using Ajax which is a current requirement of the DataTables plugin.

Everything looks great. Everything work except getting the new/edit/delete action to work. I started with the following example on the DataTables/Editor site.

https://editor.datatables.net/examples/styling/bootstrap.html


JAVASCRIPT (DataTables / Editor)

 $(document).ready(function() { $(".dropdown-toggle").dropdown(); }); $(document).ready(function() { $(".dropdown-toggle").dropdown(); }); $(document).ready(function edit_users() { var csrftoken = getCookie('csrftoken'); var editorUser = new $.fn.dataTable.Editor( { ajax: '', table: "#theader", fields: [ { label: "ID:", name: "ID" }, { label: "Name:", name: "NAME" }, { label: "CM:", name: "CM" }, { label: "Email:", name: "EMAIL" } ] } ); if ( !$.fn.dataTable.isDataTable( '#theader' ) ) { $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); var table = $('#theader').DataTable( { bProcessing: true, bServerSide: true, start: 1, dataSrc: "id", sAjaxSource: 'load_user_json', columns: [ { data: "ID" }, { data: "NAME" }, { data: "CM" }, { data: "EMAIL" } ], select: true } ); } new $.fn.dataTable.Buttons( table, [ { extend: "create", editor: editorUser }, { extend: "edit", editor: editorUser }, { extend: "remove", editor: editorUser } ] ); table.buttons().container() .appendTo( $('.col-sm-6:eq(0)', table.table().container() ) ); $('#theader tfoot th').each( function () { var title = $(this).text(); $(this).html( '<input type="text" placeholder="Search '+title+'" />' ); } ); table.columns().every( function () { var that = this; $('input', this.footer() ).on( 'keyup change', function () { if ( that.search() !== this.value ) { that .search( this.value ) .draw(); } } ); } ); } ); 

HTML

 {% extends "base.html" %} {% load crispy_forms_tags %} {% load staticfiles %} {% block content %} {% if queryset %} <h2>Current Users</h2> <table id="theader" class="table table-bordered table-hover small order-column"> <thead> <tr> <th>ID</th> <th>NAME</th> <th>CM</th> <th>EMAIL</th> </tr> </thead> <tfoot> <tr> <th>ID</th> <th>NAME</th> <th>CM</th> <th>EMAIL</th> </tr> </tfoot> <tbody> {% for row in queryset %} <tr id=forloop.counter> <!-- Needed for DataTables row identification --> <td>{{ row.operator_id }}</td> <td>{{ row.fullname }}</td> <td>{{ row.cm }}</td> <td>{{ row.email }}</td> </tr> {% endfor %} </tbody> </table> {% else %} <h4>No SKUs have been defined</h4> {% endif %} <script src="{% static 'js/searchable-users-table.js' %}"></script> {% endblock %} 
2
  • Have you looked into using the DataTables PHP library? The author wrote a server-side library and it's pretty well documented (albeit hard to find). Link to Documentation Commented Jun 29, 2016 at 18:24
  • Thanks, I had not considered that actually. Something to consider Commented Jun 29, 2016 at 23:22

1 Answer 1

1

First things first; you don't have to provide a JSON endpoint to work with DataTables.js. You can render a table and call DataTable() on it.

Take the following example:

 $(document).ready(function(){ $('#theader').DataTable({ pageLength:25, rowReorder:false, colReorder:true, order: [[1, 'asc'],[0, 'asc']] }); }); 

The table element at id theader is passed to DataTable, where the magic happens; DataTables will paginate, order, and allow for re-ordering based on this. If you don't know how to build a JSON endpoint, you can avoid it for now unless you truly need to have in-table editing.

If you do want to explore building a JSON API, Django Rest Framework is a great option and allows for fine control over serialization of models. This means that you can use the modular Viewsets and Serializers from DRF to build out all CRUD functionality for a given model / set of related models at a single endpoint.

However, for quick and dirty retrieval-only applications you can also build a view, call it via JS/JQuery's AJAX function on page load, and return a JsonResponse in your Django view. It's very quick and basically boils down to this:

  1. Retrieve a queryset for a model based on some parameters (either provided via request.GET, request.POST, or url parameters)
  2. Process as needed.
  3. Convert an array of values (my_queryset=SomeModel.objects.filter(something=somevalue).values('field_1','field2'))
  4. Serialize to JSON and respond, setting safe=False in the JsonResponse kwargs if not return a dictionary.(return JsonResponse(my_queryset, safe=False)). Alternately, convert your queryset to an ordered dict and pass it to JsonResponse.
Sign up to request clarification or add additional context in comments.

2 Comments

Appreciate the response. DataTables has an additional add-on called Editor. That add-on requires Ajax. Converting to JSON is required as well and that is where I be stuck. I can get Ajax to work independent of the DataTables and Editor add-ons (plug-ins) and I taking my DB query result and converting it to JSON is not an issue, but not with the add-ons.
All you have to keep in mind is that the ajax param of your DataTables initialisation is an url where a POST is sent on change for a field. Once your API is set up with DRF or otherwise, supply the url used for Update operations and you will be able to update away :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.