A simple Ajax example on Django 1.4

I used to use php to handle ajax request, which is pretty easy. Using Django framework is a little complex, here is a simple example, and I’m sure there are other ways.

1. In your views.py:

(1) include the following lines

from json import dumps
from django.views.decorators.csrf import csrf_exempt

(2) write a function to handle the requests:

@csrf_exempt #this is important
def quest(request):
	if request.is_ajax() and request.method == "POST" and request.POST["operation"] == "loadmovies":
		mimetype = "application/json";
		data = dumps(retrieveMovieInfo(Movie.objects.all()));
		return HttpResponse(data, mimetype);
		return HttpResponse("This is not an valid request");

2. In your urls.py, add the following lines:

url(r'^quest/$', 'quest'),

3. In your javascript, make a request, I am using jQuery here:

	data : {
            operation: "loadmovies"
	function (results) {
		//the results is already a js array, no need to JSON.parse

Leave a Reply

Your email address will not be published. Required fields are marked *