Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data from django to d3.js

Tags:

django

d3.js

I'm doing a survey web project at the moment that requires me to use d3.js to perform some kind of bar chart visualization. I'm using Django to program my web application.

The problem I encounter is how do I pass all values related to an object into an array that is used in d3.js?

choice = question.choicelist.get(choice_no=choice_no)

where votes for each choices to the question will be choice 1 = 4, choice 2 = 6, choice 3 = 7, choice 4 = 1.

For ds.js, the most simplest way to read a data set is:

var data = [ 4, 6, 7, 1]

How do I pass the data to my template such that d3.js is able to read it as the code above?

like image 465
U.f.O Avatar asked Oct 25 '12 09:10

U.f.O


1 Answers

Handiest option: convert it to json. Json is valid javascript, so you can insert it directly into the template, which seems to be what you want. Something like

import json

def your_view(request):
    poll_results = [4, 6, 7, 1]
    poll_as_json = json.dumps(poll_results)
    # Gives you a string '[4, 6, 7, 1]'
    ...
    return render_or_whatever(context={'poll_as_json': poll_as_json})

And in your template:

<script ...>
   var data = {{ poll_as_json }};
   ...
</script>

Something like that?

like image 148
Reinout van Rees Avatar answered Sep 26 '22 20:09

Reinout van Rees