Django and AJAX
One hot topic that keeps coming up over and over again on the Django mailing lists and in IRC has to do with when Django will get “AJAX support”. There are two answers to that question; one can be stated with authority, and the other consists entirely of my own unofficial and non-binding opinion. Let’s start with the first:
We’ve already got it, and more is on the way
Doing AJAX with Django has always been pretty easy, though maybe in a way that’s not obvious to users of other frameworks. All you have to do is use a slightly different template — to return XML- or JSON-formatted data instead of HTML — and you’re golden.
This has gotten quite a bit easier in the past week, thanks to the first draft of a new module:
django.core.serialization. In essence, the serialization system is designed to make it easy to translate Django model instances into various other formats. Serializers for XML, JSON and simple Python are now included in Django, so you could now do this in a view:
And voilà: you have a view which returns the latest five objects from a model in JSON format. Perfect for AJAX requests. You could even have the same view respond to both “normal” and AJAX requests by adding a parameter to the URL and changing output types based on that.
The same idea can easily be applied to most of the common operations people want to use AJAX for; comment posting, for example, could be handled by firing an XMLHttpRequest to a view which would save the comment and return it serialized in the format of your choice.
Is that it?
And now it’s time for me to step up on my soapbox and issue a big fat disclaimer: the following represents nothing more than my own opinion, and has no necessary bearing on what will actually end up happening in Django. This is just what I think, and doesn’t attempt to speak for anyone or anything else, and what I have to say on this topic is inflammatory and is almost certainly going to make some people angry. Read on with that in mind, and at your own risk.
Of course, that’s a ludicrous thing to suggest. HTML and CSS are foundational technologies of the Web, and no-one is suggesting that web developers shouldn’t have to know them. In fact, a “web developer” who didn’t know HTML and CSS has no right to the title.
So, to get back to the actual topic at hand:
- You can already do AJAX with Django, and it’s not really hard at all.
- It’ll probably get easier in the future as the serialization stuff improves, and even easier if/when we get a web-services API in place.