Transferring data from Django to D3

Complete the newbie question:

I have a Django application in which I generate a data view:

result = json.dumps(data) context = RequestContext(request, { 'result': result, }) return HttpResponse(template.render(context)) 

Now I have a map.js file in which I display a heat map of the data using d3.js I also have an index.html file where my page is displayed and the heatmap link is passed through

 <body> <div id="heatMap"> </div> <body> 

Question: how to transfer the data generated in the view to the map.js file?

Many thanks for your help!

+7
source share
2 answers

In your template, use {{ result }} between the <script></script> to make your JavaScript magic.

If result is a serialized JSON object, you can simply use JSON.parse(result) to convert the JSON string to a JavaScript object.

Example:

 <script type="text/javascript"> var data = JSON.parse("{{ result }}"); run_d3_stuff(data); </script> 
+7
source

There are several potential solutions here.

The first, as Alp noted, should do this:

 <script> run_d3_stuff('{{results}}'); //Use whatever your function is here. </script> 

Another solution is to render your script file with a view and include it on the landing page.

EDIT:

To be more clear, the second solution involves changing the template in your JavaScript file, using the same trick to set the variable value for this. Then on your page you will do the following:

 <script src="my_view's_path"></script> 
+2
source

All Articles