Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing data from Django view to D3

Complete newbie question:

I have a Django app running in which I generate a view with data:

result = json.dumps(data)

context = RequestContext(request, {
    'result': result,
})

return HttpResponse(template.render(context))

Now I have a map.js file in which I render a heat map of the data using d3.js. I also have an index.html file where my page is rendered and the heatmap reference is passed via

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

Question: how do I pass my data generated in the view to the map.js file?

Thanks so much for your help!

like image 926
notrockstar Avatar asked Jun 26 '13 23:06

notrockstar


2 Answers

In your template use {{ result }} in between <script></script> tags to do your JavaScript magic.

If result is a serialized JSON object you can just 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>
like image 141
Alp Avatar answered Sep 29 '22 02:09

Alp


There are a few potential solutions here.

The first, as noted by Alp, is to do this:

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

Another solution is to render your script file using a view and include it in the target page.

EDIT:

To be more clear, the second solution would involve changing the template to be your JavaScript file, using the same trick above to set a variable's value to this. Then in your page you would do this:

<script src="my_view's_path"></script>
like image 33
ZachS Avatar answered Sep 29 '22 03:09

ZachS