CMC
CMC

Reputation: 25

How to return JSON in django

I want to return only JSON data for this view method and I'm not sure if I'm doing it the right way. Any tips would be greatly appreciated.

def helpful_click(request,object):
    if request.POST and request.is_ajax():
        form = HelpfulForm(request.POST)
        if form.is_valid():
            form.save()
    return simplejson.dumps({'helpful':True})

Upvotes: 2

Views: 2036

Answers (2)

dfrankow
dfrankow

Reputation: 21407

There is a JsonResponse object:

>>> from django.http import JsonResponse
>>> response = JsonResponse({'foo': 'bar'})
>>> response.content
b'{"foo": "bar"}'

Upvotes: 0

My understanding is that every Django view should return an HttpResponse object, and you should also make sure the mime-type is set correctly:

http://jibbering.com/blog/?p=514

In a project I was working on I had something like this:

return HttpResponse(simplejson.dumps({'helpful':True}), 'application/json')

Upvotes: 6

Related Questions