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)
Did you try to run that code sample? The django.core.serializers don't serialize dictionaries. They only work on model instances, querysets, ...
ReplyDeleteYou need to use simplejson, or equivalent, instead:
>>> import simplejson
>>> simplejson.dumps(data_obj)