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

JSON serialization in Django

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)

Tags: ,

2 Responses to “JSON serialization in Django”

  1. What about your urls.py?

  2. I did not include the urls.py since it was fairly straight-forward (i.e. no parameters or anything).

    Also, please be aware that if you are going the route of writing a full-fledged REST api (i.e. read/write), then rolling your own RESTful views is not really a viable option unless you happen to be a REST black belt :p. Take a look at Django-Piston if this is what you are looking for - it is a very nice abstraction that ‘fits’ with Django.

    For urls.py, I believe this is what I used:

    from YourApp.Views import list_banners

    urlpatterns = patterns(”,
    (r’^banners/list/$’, list_banners),

    )

    Regards,

    Christian

Leave a Reply