Friday, September 18, 2009

Django Ajax Response

The Django Python web application framework is capable of many types of data serialization.  Be it, XML, or JSON, The built-in Django serialize() function can handle it.  The transformation typically starts with a Python dictionary or list but can also handle instances of user-defined types.  The end result is always a string.  The string is of course desired because that is what will be passed along inside the HTTP response.  It is nice to have this functionality, but what is it used for?  Why not just use standard templates with template variables and let the view render it for the client?  The main reason is that more and more non-browser clients are being used with web applications.  Even if the client is a web browser, there is a good chance that the request is coming from an ajax application and they don't always like HTML responses.  Most prefer the JSON format.

There is, however, a good chance that more than one format is going to be necessary for the same data set.  For instance, I might have a standard Python dictionary that I want to return to the client.  Depending on who the client is, that same data is going to be rendered differently.  This is so that the client can understand the response.  Say, for instance, that the client was a javascript application.  This client could, potentially, have the ability to selectively handle different response formats that server returns to it.  This responsibility shouldn't really be left to the client application.  It would be nice if the Django application could automatically determine if a javascript application is requesting the data instead of a standard web request.  Thankfully, Django can do this without much developer intervention.

Django HTTP request instances can determine if the request came from an ajax application.  Django does this under the hood by examining the HTTP headers.  As is illustrated by the following example, simple scenarios like this one can be implemented with a single controller.

#Example; Django Ajax response.

#Import Django components.
from django.http import HttpResponse
from django.template import Context, Template
from django.core.serializers import serialize

#Initialize the test data object.
data_obj={"first_name":"First Name", "last_name":"Last Name"}

#The test view.
def index(request):
    #Check if this is an ajax request.
    if request.is_ajax():

        #Set the result to serialized JSON data.
        result=serialize("json", data_obj)

    else:
        #Create a context object from the test data.
        context_obj=Context(data_obj)
        
        #Create a test template string.
        template_str="""<b>first_name</b>: {{first_name}}<br/>
                        <b>last_name</b>:  {{last_name}}"""
                        
        #Set the result to the rendered HTML.
        result=Template(template_str).render(context_obj)

    #Return the response.
    return HttpResponse(result)