[Django]-Ajax views with django

6👍

This article seems to be quite a good tutorial on how to work with both ajax and regular requests. The request object has a method is_ajax() which will look for HTTP_X_REQUESTED_WITH: XMLHttpRequest. This will of course depend on these values being set correctly by the javascript sending the request.

From the article:

from django.http import HttpResponse
from django.core import serializers
from django.shortcuts import render_to_response
from your_app.models import ExampleModel

def xhr_test(request, format):
    obj = ExampleModel.objects.all()
    if request.is_ajax():
        data = serializers.serialize('json', obj)
        return HttpResponse(data,'json')
    else:
        return render_to_response('template.html', {'obj':obj}, context=...)

Or, you could use django-piston which is a RESTful framework for Django. I use this module in my project. You can define resources (sort of like views), and depending on either the mime-type or format passed to your url, it will emit either html, xml, or json. This will probably be the best way to go if every single view (or a large majority) need to be returned in different formats.

0👍

I have used a decorator for this. Have the view return the context, the template, and an alternate template.

If the Ajax version wants to return data, the third return value can be the data object to turn into JSON.

Leave a comment