Simple Ajax with Django

Published on June 1, 2007

So, the Django developers, in my opinion, are freaking smart. Instead of bundling Django with a particular library, they have added XML and JSON serialization; us humble users can choose whatever AJAX library we want. Prototype 1.5.1 has been pretty fun to work with, so I'll kick off this demo with a really simple example.

How simple? The intended goal is to have the total number of 'dirts' update without user intervention. Laaaammmeee. If you are a visual type of person, take a look on the Colddirt huh page. That number automatically increases without user intervention. And this is how.

The process (some pseudocode) will go like this:

check /dirt_count/ for an update
if update:
make number bigger
else:
check less frequently

Pretty simple, eh?

urls.py

    (r'^dirt_count/$', views.dirt_count),

As you can see, it just sends the request to the view.

views.py

def dirt_count(request):
    from django.http import HttpResponse
    countd = str(Dirt.objects.all().count())
    return HttpResponse(countd, mimetype='text/plain')

Pretty simple -- count the dirts. That makes sense.

dirty.js

new Ajax.PeriodicalUpdater('dirtcount', '/dirt_count/', {
  method: 'get',
  frequency: 3,
  decay: 2,
});

Yea, Prototype makes that real easy. Just make sure to have a element in your template somewhere with an id of 'dirtcount'.

templates/huh.html

0


Tagged as: ajax | colddirt | django | json
blog comments powered by Disqus

About this page

This entry is from my tech blog and was written on June 1, 2007. It's been tagged with ajax and colddirt and django and json.

Via Twitter

"So far we only got one case." -Yan-Shih bidding on auction wine. (about 1 week, 4 days ago)

Related Readings

Book Book Book Book