I'm struggling with a django queryset to be passed to d3.js for plotting.
What I'm trying to do:
- I have a form which allow the user to make specific queries in my database (this is working really fine).
- The result of that search are all ordered by date (more below) but may be a lot (between 0 to 20 000). So I don't want to display them as a list but make a bar chart.
The problem: I don't know what would be the best method to transfer the results to d3js, since I'm returning more to my view than just what I want to plot.
my views.py:
class QBinnedImages(View):
template_name = 'data/query_simple.html'
form_class = QueryImages
def get(self, request, *args, **kwargs):
### working fine
def form_valid(self, form):
### Do some stuff to get the query results
context = {"title":"Query Results", "form":form, \
"ndata":len(alldates), "data":JsonResponse(alldates)}
return render(self.request, 'data/query_results.html', context)
class QueryResults(View):
template_name='data/query_results.html'
The alldates is a dictionary of the form:
{"N": ["20150926T230027", "20150926T230547", "20150926T231106", \
"20150926T233741", "20150926T234301", "20150926T234820", \
"20150926T235339", "20150926T235858", "20150927T000936",]}
for the moment my template data/query_results.html look like this:
{% entends 'base.html' %}
{% block content %}
<div id="blablabla">
<h1> {{ title }} </h1>
<p> You queried with the following constrains : </p>
{{ form.as_p }}
<p> We found {{ ndata }} satisfying your query </p>
</div>
<div id="plots">
<svg class="bresults"> </svg>
</div>
<script src="//d3js.org/d3.v3.js" charset="utf-8"></script>
<script>
// definition of the axis and other small stuff
d3.json( "{{ data }}", function(error, data) {
if (error) return console.warn(error);
x.domain([0, d3.max(data, function(d) { return d.value; })]);
});
</script>
{% endblock content %}
And the bug is at d3.json off course. I do understand that d3.json actually send a requests for a json stream ... but I'm stuck there.
I hope there is enough information here to help me out
Thaaaaanks!!!
To pass a Django's variable to a JS variable you need:
var js_variable = "{{ django_variable }};"
In your case:
<script>
// definition of the axis and other small stuff
var data = "{{ data|escapejs }}"; // transfer from django to js
d3.json( data, function(error, data) {
if (error) return console.warn(error);
x.domain([0, d3.max(data, function(d) { return d.value; })]);
});
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With