JSON, jQuery, and Django

Django has a powerful system for returning HTML pages, and excellent integration with AJAX systems for returning HTML via AJAX requests, but you can take your project one step further using JSON.

Let’s say we have a web app with a table of dog breeds, and each row represents a different breed of dog. Because of the high number of rows that the table would contain, we probably want to allow the user to filter the table’s contents. Using jQuery and JSON, we can dynamically add rows to the table.

First, the Django side of things. We want a Django view that returns JSON. For our example, we gather a queryset of the objects we wish to add to the table, then extract the data we want from the objects and add it to a dictionary which will be returned via JSON.

# import all the necessary packages, including our Dogs model
from dog_app.models import Dogs
from django.http import HttpResponse
import simplejson

def more_dogs(request):
    # get the objects you wish to return
    dogs = Dogs.objects.filter(...)
    # construct a list which will contain all of the data for the response
    to_json = []
    for dog in dogs:
        # for each object, construct a dictionary containing the data you wish to return
        dog_dict = {}
        dog_dict['breed'] = dog.breed
        dog_dict['size'] = dog.size
        # ...etc
        # append the dictionary of each dog to the list
    # convert the list to JSON
    response_data = simplejson.dumps(to_json)
    # return an HttpResponse with the JSON and the correct MIME type
    return HttpResponse(response_data, mimetype='application/json')

Okay, so we have a Django view which will return the JSON, but we still need the JavaScript that will request the data and add it to the page. For this, we’ll use jQuery.
// Make the request
$.get('/ajax/more_dogs/', function(data) {
    // data is the response data. In this case, our JSON
    // Our JSON contains several dictionaries for each breed of dog,
    // and we want to construct an HTML table row for each 
    // First, lets get the table body which we'll add the rows to
    $tbody = $("#dog_table").find('tbody');
    // next, iterate through the JSON array
    $.each(data, function() {
        // create the row
        $row = $('<tr>');
        // iterate through each dog breed's attributes and create a column for each key, value pair
        $.each(this, function(key, value) {
            // create the column
            $col = $('<td>');
            // add text to the column
            // append the column to the row
        // append the row to the table body

When that JavaScript is executed, new rows will be added to the table.

There’s another advantage to using JSON, however. If you ever want to access database information from outside the project’s environment, you can use the same views.

Try it out and see what you can do!