Ajax views with django
I'm working on a pretty big project right now where every view should be accessible via a normal request and an ajax request via the same url. I'm looking for ideas on how to create a small framework to handle this in a very generic way. Depending on if the view is called via ajax or not it needs to render a different template and return a json instead of a HttpResponse
object. I'd like to collect any ideas on this topic - the main goal shou开发者_如何学JAVAld be not to avoid the dry principle and make code that is as reusable as possible. I was already considering different options as generic views, decorators on views etc, but I'm open to anything. So please let me hear your suggestions or point me towards any readymade snippets you know!
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.
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.
精彩评论