How to pass data from django to d3.js

d3.js, django

Solution

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?

Problem

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?

Original source