我正在努力将 django 查询集传递给 d3.js 进行绘图。
我正在尝试做的事情:
- 我有一个表单,允许用户在我的数据库中进行特定查询(这工作得很好)。
- 该搜索的结果都是按日期排序的(更多内容见下文),但可能很多(在 0 到 20 000 之间)。所以我不想将它们显示为列表,而是制作条形图。
问题:我不知道将结果传输到 d3js 的最佳方法是什么,因为我返回到我的 View 的不仅仅是我想要绘制的内容。
我的观点.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'
alldates 是以下形式的字典:
{"N": ["20150926T230027", "20150926T230547", "20150926T231106", \
"20150926T233741", "20150926T234301", "20150926T234820", \
"20150926T235339", "20150926T235858", "20150927T000936",]}
目前我的模板 data/query_results.html 看起来像这样:
{% 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 %}
而且这个 bug 出在 d3.json 上。我确实知道 d3.json 实际上发送了对 json 流的请求......但我被困在那里。
我希望这里有足够的信息来帮助我
Thaaaaanks!!!
最佳答案
要将 Django 的变量传递给 JS 变量,您需要:
var js_variable = "{{ django_variable }};"
在你的情况下:
<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>
关于json - Django - 没有明确请求的 d3.js 通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35753305/