notrockstar
notrockstar

Reputation: 853

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!

Upvotes: 10

Views: 5411

Answers (2)

Alp
Alp

Reputation: 29739

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>

Upvotes: 9

ZachS
ZachS

Reputation: 1248

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>

Upvotes: 2

Related Questions