Passing Python Data to JavaScript

Created on Dec. 5, 2012, 11:40 p.m. by Hevok & updated by Hevok on May 2, 2013, 5:25 p.m.

Data can be passed from Python to JavaScript by dumping the Object into JSON and safe escaping it in the Template (py2js):

# views.py
...
from django.shortcuts import render
from django.utils import simplejson
...
def view(request, template='graph.html'):
      network = {
      'data': {
                 'nodes': [
                     {'id': '1', 'label': 'Concepts', 'text':'Denigma Concepts'},
                     {'id': '2', 'label': 'Aspects', 'text':'Three aspects'}
                 ],
                 'edges': [
                     {'id': '2to1', 'label': 'belongs_to', 'text':'A belonging to relationship', 'target':'1', 'source': '2'}
                 ]
             }
      }
     network_json = simplejson.dumps(network)
     return render(request, template, {'network_json': network_json})
     ...
// graph.html
...
<script type="text/javascript">
    ...
    data = {{ network_json|safe }};
    ...
</script>
...
json.gif

Tags: conversion, js, rest, django
Categories: Tutorial, reST
Parent: Web Framework

Update entry (Admin) | See changes

Comment on This Data Unit