Chartjs-Add dynamic data in a demo chart.js file of a django template

1👍

You already mentioned use of pandas; that’s why assume you can aggregate the names already.
For the django part:
You will need a view looking something like this:

def your_view(request):
  data = "[10, 20, 30]" # however your aggreated output will look.
  # for simplicity of this example I assume it as a string like that

  # you can pass variables to djangos frontend using context

  context = {'my_data': data}
  return render(request, 'index.html', context)

So basically you can put your data just in an ordinary django context.
If your js is that short and you want a quick and easy answer, it would be best to remove the js file and put the code directly into a script tag in your html (I assumed "index.html" for example here).

Then you can just go into your script tag and:

var ctx = document.getElementById("myPieChart");
var myPieChart = new Chart(ctx, {
  type: 'doughnut',
  data: {
    labels: ["Direct", "Referral", "Social"],
    datasets: [{
      data: {{ data }} ,
...

Overall the basic idea in django is: you create a view. You create an url pointing to the view. The view renders a HTML file (or well, "file" in general; word files and other files work as well). "Renders" basically means performing templating functions and putting whatever values you gave it in context into the according variable names written in double curly brackets.

After that the file is served. Which means whatever you do in template runs before the javascript runs because the server creates the file using template tags and just after that it is sent to the browser which then executes javascript. For your example you could image django context and template tags just as a basic "use whatever I put in this variable to replace it in my html/css/js/whatever file".

That means you could also do:

def your_view(request):

  context = {
    'data_one': 10
    'data_two': 20
    'data_three': 30
  }
  return render(request, 'index.html', context)

and accordingly:

var ctx = document.getElementById("myPieChart");
var myPieChart = new Chart(ctx, {
  type: 'doughnut',
  data: {
    labels: ["Direct", "Referral", "Social"],
    datasets: [{
      data: [{{ data_one }}, {{ data_two }}, {{ data_three }}],
...

Leave a comment