Dev360.com - Web Development and Beyond

In a split-second, customers will determine if your site is worthy of their time. Can you afford to lose them?

Blog

Categories

Archive for November, 2008

JSON serialization in Django

Thursday, November 27th, 2008

I’ve been quite busy lately, but I decided I’d share a few lines of code on how to do JSON (as well as XML) serialization in Django - its very simple.

I like the REST-based approach that Rails takes, so I kind of incorporated that in my code. It allows you to do something like this:

Regular view:
http://foo.com/banners/list/
JSON serialized data:
http://foo.com/banners/list/?format=json
XML serialized data:
http://foo.com/banners/list/?format=xml

On to the code:

# models.py
class Banner(models.Model):
	title = models.CharField(max_length=64)
	url = models.URLField()
	image = models.ImageField(upload_to='img/banners/')

# views.py
from django.core import serializers
from django.http import HttpResponse, QueryDict
from django.shortcuts import render_to_response

def request_format(request):
	default_format = 'http'
	q = QueryDict(request.META['QUERY_STRING'])
	format = q.get('format', default_format)
	if(format not in ['http','json','xml']):
		format = default_format
	return format

def list_banners(request):
	banners = Banner.objects.filter()
	format = request_format(request)
	if format == 'http':
		return render_to_response('list_banners.html', {'banners':banners})
	else:
		serialized_data = serializers.serialize(format, banners, fields = ('title', 'url', 'image'))
		return HttpResponse(serialized_data, mimetype='application/'+format)