views:

4197

answers:

2

I'm trying to make a Django function for JSON serializing something and returning it in an HttpResponse object.

def json_response(something):
    data = serializers.serialize("json", something)
    return HttpResponse(data)

I'm using it like this:

return json_response({ howdy : True })

But I get this error:

"bool" object has no attribute "_meta"

Any ideas?

EDIT: Here is the traceback:

http://dpaste.com/38786/

+13  A: 

The Django serializers module is designed to serialize Django ORM objects. If you want to encode a regular Python dictionary you should use simplejson, which ships with Django in case you don't have it installed already.

from django.utils import simplejson

def json_response(something):
    return HttpResponse(simplejson.dumps(something))

I'd suggest sending it back with an application/javascript Content-Type header (you could also use application/json but that will prevent you from debugging in your browser):

from django.utils import simplejson

def json_response(something):
    return HttpResponse(
        simplejson.dumps(something),
        content_type = 'application/javascript; charset=utf8'
    )
Simon Willison
Use <a href="https://addons.mozilla.org/en-US/firefox/addon/10869">JSONView</a> in Firefox to nicely format JSON returned with the application/json content type.
Dave
That was supposed to be a link to https://addons.mozilla.org/en-US/firefox/addon/10869
Dave
+4  A: 

What about a JsonResponse Class that extends HttpResponse:

from django.http import HttpResponse
from django.utils import simplejson

class JsonResponse(HttpResponse):
    def __init__(self, data):
        content = simplejson.dumps(data,
                                   indent=2,
                                   ensure_ascii=False)
        super(JsonResponse, self).__init__(content=content,
                                           mimetype='application/json; charset=utf8')
Filippo
Thats a good idea i'll probably use this
Justin Hamade