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.

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.

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!