DataTables and Django: Finally with Ajax!

Django and DataTables with Ajax: my nemesis during the last week. But after several attempts and burned my eyes in StackOverflow and Django Documentation I finally reach the solution. How I solved it? Just reading carefully the json outputted and the changelog of DataTables 1.10 and how them now process the json and ajax requests. If you are reading this, perhaps you don't have any idea how Django or DataTables works, but over the Internet are a lot of great tutorials, so, I wont explain how work with them. Let's begin. You should have a model defined, something like:

models.py

from django.db import models

class MyModel(models.Model):
    someAttr = models.CharField()

    def __unicode__(self):
        return self.someAttr

Then, you should define a view, returning a queryset in json format.

views.py

from django.http import HttpResponse
from django.core import serializers
from .models import MyModel

def myModel_asJson(request):
    object_list = MyModel.objects.all() #or any kind of queryset
    json = serializers.serialize('json', object_list)
    return HttpResponse(json, content_type='application/json')

Here, you must define a url for your ajax view, as follows:

urls.py

from django.conf.urls import patterns, url

urlpatterns = patterns('myapp.views',
                    url(regex=r'^$',
                    view='myModel_asJson',
                    name='my_ajax_url'),
)

Then in your template, you should define a table and the javascript function, something like:

template.html

<table cellpadding="0" cellspacing="0" border="0" id="example">
     <thead>
         <tr><th>My Attr Heading</th></tr>
     </thead>
     <tbody></tbody>
</table>


<script type="text/javascript" language="javascript" class="init">
     $(document).ready(function() {
         $('#example').dataTable( {
             "processing": true,
             "ajax": {
                 "processing": true,
                 "url": "{% url 'my_ajax_url' %}",
                 "dataSrc": ""
             },

             "columns": [
                     { "data": "fields.someAttr },
                     { "data": "pk" }
                 ]
         } );
     } );
 </script>

Notice that dataSrc is empty due to the format of the json outputted by Django.You should also read how serialize natural keys in Django, in case you have foreign keys in your models. It is simple, but the documentation explain it very clearly: Just add a method to the model itself:

def natural_key(self):
    return self.my_natural_key

This way you assure your json follows the foreing keys values and not the foreign key itself(which means the integer value).

And you got it! Or I hope so. The example above works for me, I wish it be self-explanatory, at least, more than other examples over the Internet.

Comments