4๐
You are right that you should use HttpResponse()
.
D3.js has a nifty d3.json
method that will perform a GET request at the URL โ/myDataURL/โ and parse the response as a JSON object:
d3.json("/myDataURL/", function(error, data) {
// ... (Use `data` to load the visualization.)
});
Which means you can easily send your dict
in a JSON format from Django:
import json
def myView(request):
// ... Prepare the `data` dict.
return HttpResponse(json.dumps(data), content_type="application/json")
Note: using HttpResponse with content_type can be simplified in recent Django 1.7+ by using JsonResponse()
Now putting it all together, if you want to actually load the data as lines in (for example) a line chart, you could use (source):
var line = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); });
d3.json("/myDataURL/", function(error, data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain(d3.extent(data, function(d) { return d.close; }));
// ... Set up the axes. See the source above for detailed instructions.
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
});
๐คCasey Falk
Source:stackexchange.com