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 updatePretty simple, eh?
(r'^dirt_count/$', views.dirt_count),
As you can see, it just sends the request to the view.
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.
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'.
0
David: Thanks for pointing this out! I'm not posting any data, so there isn't a need for a .* -- updated.
Sheesh. This makes it all look so easy! Thanks for the quickie!
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.
Why does dirt_count() need to return an HttpResponse? Seems like it should be able to just return a string...
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?
No, if you try to return a string some error will occur.
Thanks Daniel.
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. There have been 8 comments so far.
Twitter contact import script seems to be broken and spamming my requests - apologies if I sent you 10 emails; I'm stubborn like that. (about 6 days, 16 hours ago)
Why do you have the ".*" in you urls.py. Should it not be '^dirt_count/$'?