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

<span id="dirtcount" class="bigblue">0</span>


Tagged As: Django
Jun 08 2007
5:43 a.m. united states
#1

Why do you have the ".*" in you urls.py. Should it not be '^dirt_count/$'?

Jun 08 2007
6:56 a.m. taiwan
#2

David: Thanks for pointing this out! I'm not posting any data, so there isn't a need for a .* -- updated.

Jun 19 2007
10:37 p.m. united states
#3

Sheesh. This makes it all look so easy! Thanks for the quickie!

Jun 20 2007
1:31 a.m. taiwan
#4

Johnny D: Quite welcome! Another Djangoer named Will has written up a great tutorial: http://www.willarson.com/blog/?p=36 ... He goes into quite a bit more detail than I do.

Jun 24 2007
5:05 p.m. united states
#5

Why does dirt_count() need to return an HttpResponse? Seems like it should be able to just return a string...

Jun 24 2007
9:15 p.m. taiwan
#6

Ennis:

I am unaware of a better response object to use. HttpResponse will take care of the necessary headers, which is why I used it. Is the a better way to return a simple string, something I'm obviously missing?

Aug 01 2007
3:25 p.m.
#7

No, if you try to return a string some error will occur.

Aug 18 2007
12:36 a.m. viet nam
#8

Thanks Daniel.

Comments are currently closed for this entry.