Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing JSON data to the front end using Django

Is there a way to pass JSON objects to the front end of a web template if using the Django framework or Python in general?

For example, if I want to send an object that has two arrays as properties (let's say xvalues and yvalues), how would I be able to use JavaScript or jQuery to do an Ajax call to obtain the object that has the properties?

like image 688
locoboy Avatar asked Aug 11 '11 02:08

locoboy


People also ask

How do I pass JSON data to frontend?

Send JSON Data from the Client SideUse JSON. stringify() to convert the JavaScript object into a JSON string. Send the URL-encoded JSON string to the server as part of the HTTP Request. This can be done using the HEAD, GET, or POST method by assigning the JSON string to a variable.

Does Django support JSON?

Since Django 1.9, the popular Python framework has supported jsonb and several other Postgres-specific fields. Native Django support means that creating jsonb fields, using them in your models, inserting data into them, and querying from them are all possible with Django's ORM.

What is Django JSON?

Django REST Framework JSON API is a library for creating JSON:API backends using the Django framework, built on top of the Django REST Framework library.


3 Answers

Sure, just setup a view that returns JSON and make a request to it. Here's a simple example:

import json      
from django.http import HttpResponse
from django.template import Template, Context

def ajax(request):
    """returns json response"""
    return HttpResponse(json.dumps({'foo': 'bar'}), mimetype='application/json')

def index(request):
    """simple index page which uses jquery to make a single get request to /ajax, alerting the value of foo"""
    t = Template("""
    <!doctype html>
      <head>
       <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
       <script type="text/javascript">
         $.get('/ajax/', function(data) {
           alert(data['foo']);
         });
       </script>
     </head>
    </html>""")
    return HttpResponse(t.render(Context()))

# urlconf
urlpatterns = patterns('',
    (r'^$', index),
    (r'^ajax/', ajax),
)
like image 130
zeekay Avatar answered Sep 22 '22 21:09

zeekay


If I understand you correctly, you want to render some JSON in your HTML output.

To do this, pass the json-encoded object from the view to the template:

views.py:

import json

def myview(request):
    obj = {"a": 1, "b": 2}
    return render_to_response("template.html", {"obj_as_json": json.dumps(obj)})

template.html:

<html>
    <head>
    <script type="text/javascript">
    var obj = {{ obj_as_json|safe }};
    </script>
    </head>
    ...
</html>

Will render as:

...
<script type="text/javascript">
var obj = {"a": 1, "b": 2};
...

Note that json.dumps only works with dictionaries containing simple data types. Django has support for serializing model objects to json, using:

from django.core import serializers
obj_as_json = serializers.serialize("json", my_model_object)

Update: note that you need to use "safe" to get this:

  var obj = {"items": [{"human": "Genesis", "usfm": "GEN"},],}

instead of this:

  var obj = {&quot;items&quot;: [{&quot;human&quot;: &quot;Genesis&quot;, &quot;usfm&quot;: &quot;GEN&quot;},],}
like image 42
codeape Avatar answered Sep 21 '22 21:09

codeape


Complementing zeekay answer, if you want to send only an object you could do a json dump, for example:

import json

def my_ajax_view(request):
    if not request.is_ajax():
        raise Http404

    data_dict = getmydata() #lets supose is a dict
    return HttpResponse(json.dumps(data_dict))

That way you will receive that data via your ajax success and do whatever you want with it.

You can send over lists too, when you receive your response sometimes you will need to do a JSON.parse on data (sometimes cause when you send a dictionary I think is not necessary)

like image 37
Hassek Avatar answered Sep 23 '22 21:09

Hassek