How do I return JSON without using a template in Django? How do I return JSON without using a template in Django? python python

How do I return JSON without using a template in Django?


I think the issue has gotten confused regarding what you want. I imagine you're not actually trying to put the HTML in the JSON response, but rather want to alternatively return either HTML or JSON.

First, you need to understand the core difference between the two. HTML is a presentational format. It deals more with how to display data than the data itself. JSON is the opposite. It's pure data -- basically a JavaScript representation of some Python (in this case) dataset you have. It serves as merely an interchange layer, allowing you to move data from one area of your app (the view) to another area of your app (your JavaScript) which normally don't have access to each other.

With that in mind, you don't "render" JSON, and there's no templates involved. You merely convert whatever data is in play (most likely pretty much what you're passing as the context to your template) to JSON. Which can be done via either Django's JSON library (simplejson), if it's freeform data, or its serialization framework, if it's a queryset.

simplejson

from django.utils import simplejsonsome_data_to_dump = {   'some_var_1': 'foo',   'some_var_2': 'bar',}data = simplejson.dumps(some_data_to_dump)

Serialization

from django.core import serializersfoos = Foo.objects.all()data = serializers.serialize('json', foos)

Either way, you then pass that data into the response:

return HttpResponse(data, content_type='application/json')

[Edit] In Django 1.6 and earlier, the code to return response was

return HttpResponse(data, mimetype='application/json')

[EDIT]: simplejson was remove from django, you can use:

import jsonjson.dumps({"foo": "bar"})

Or you can use the django.core.serializers as described above.


In Django 1.7 this is even easier with the built-in JsonResponse.

https://docs.djangoproject.com/en/dev/ref/request-response/#jsonresponse-objects

# import itfrom django.http import JsonResponsedef my_view(request):    # do something with the your data    data = {}    # just return a JsonResponse    return JsonResponse(data)


In the case of the JSON response there is no template to be rendered. Templates are for generating HTML responses. The JSON is the HTTP response.

However, you can have HTML that is rendered from a template withing your JSON response.

html = render_to_string("some.html", some_dictionary)serialized_data = simplejson.dumps({"html": html})return HttpResponse(serialized_data, mimetype="application/json")