sach20
sach20

Reputation: 45

sending json data from django to d3.js

i am trying to pass a queryset in django's views.py to d3.js.

views.py :

def index(request): qs = DCPOWERSTATS.objects.all().values('TS','PuE').order_by('TS') return render(request, 'dashboard/dash.html', context=qs})

dash.html :

<!DOCTYPE html>
<meta charset="utf-8">
<style>

.chart div {
font: 10px sans-serif;
background-color: steelblue;
text-align: right;
padding: 3px;
margin: 1px;
color: white;
             }

</style>
<div class="chart"></div>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>

var data = {{ data_json }};

var x = d3.scale.linear()
          .domain([0, d3.max(data)])
          .range([0, 420]);

d3.select(".chart")
  .selectAll("div")
  .data(data)
  .enter().append("div")
  .style("width", function(d) { return x(d) + "px"; })
  .text(function(d) { return d; });

 </script>

I need to make changes in views.py and dash.html to create something like : https://bl.ocks.org/mbostock/3885304

All previous answers are confusing.I need a solution for views.py as well as dash.html. I also need to know the perfect way of sending queryset results to javascript.

Thanks!

Upvotes: 1

Views: 3499

Answers (1)

dahrens
dahrens

Reputation: 3959

You need to convert your models into plain lists/dictionaries to be able to convert them into JSON. You decided to use values() on the queryset. There is also django serialization.

Despite serialization you have two options here.

JSON returning views

Either you create a view that directly returns JSON data using JsonResponse.

from django.http import JsonResponse

def index(request):
    qs = DCPOWERSTATS.objects.all().values('TS','PuE').order_by('TS')
    # slice the queryset to hit the database and convert into list
    return JsonResponse(qs[:])

You can now load this data on client side using an ajax call.

html (using jQuery)

// assuming you have registered your view at '/dcpowerstats'
$.ajax({
  url: "http://example.com/dcpowerstats",  
  success: function(data) {
     console.log(data);
  }
});

Passing JSON to your template

Or you render your JSON data directly into the HTML template using. In this case you should add your serialized data to the view and use the template tag there.

view

import json
from django.shortcuts import render

def index(request):
    qs = DCPOWERSTATS.objects.all().values('TS','PuE').order_by('TS')
    # slice the queryset to hit the database and convert into list
    context = {'data_json': json.dumps(qs[:])}
    return render(request, 'dashboard/dash.html', context=context)

html

<script>
var data = {{ data_json|safe }};
</script>

Which way to pick depends on your frontend and preferences.

If you just need some static data available in your views javascript, I'd pick the template option.

If your frontend needs to be able to load different things dynamically and the amount of data is bigger pick the second option. In this case I would also consider using django rest framework.

Upvotes: 4

Related Questions