django模板计算 - django模板语言循环
如何将独立的散景图嵌入到Django模板中 (4)
我想通过django框架在我的Web应用程序中显示bokeh库提供的图形,但是我不想使用bokeh-server可执行文件,因为这不是好方法。 那有可能吗? 如果是,该怎么做?
也可以使其与AJAX请求一起使用。 假设我们加载了一个页面,并且希望在不单击整个页面的情况下单击按钮时显示一个图。 从Django视图中,我们以JSON返回Bokeh脚本和div:
from django.http import JsonResponse
from bokeh.plotting import figure
from bokeh.resources import CDN
from bokeh.embed import components
def simple_chart(request):
plot = figure()
plot.circle([1,2], [3,4])
script, div = components(plot, CDN)
return JsonResponse({"script": script, "div": div})
当我们在JS中获得AJAX响应(在本示例中使用Jquery)时,首先将div附加到现有页面上,然后附加脚本:
$("button").click(function(){
$.ajax({
url: "/simple_chart",
success: function(result){
var bokeh_data = JSON.parse(result);
$('#bokeh_graph').html(bokeh_data.div);
$("head").append(bokeh_data.script);
}});
});
使用Fabio Pliger建议的 Embedding Bokeh Plots 文档示例,可以在Django中做到这一点:
在
views.py
文件中,我们输入:
from django.shortcuts import render
from bokeh.plotting import figure
from bokeh.resources import CDN
from bokeh.embed import components
def simple_chart(request):
plot = figure()
plot.circle([1,2], [3,4])
script, div = components(plot, CDN)
return render(request, "simple_chart.html", {"the_script": script, "the_div": div})
在
urls.py
文件中,我们可以放置:
from myapp.views import simple_chart
...
...
...
url(r'^simple_chart/$', simple_chart, name="simple_chart"),
...
...
在模板文件
simple_chart.html
我们将:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Experiment with Bokeh</title>
<script src="http://cdn.pydata.org/bokeh/release/bokeh-0.8.1.min.js"></script>
<link rel="stylesheet" href="http://cdn.pydata.org/bokeh/release/bokeh-0.8.1.min.css">
</head>
<body>
{{ the_div|safe }}
{{ the_script|safe }}
</body>
</html>
而且有效。
您不需要使用bokeh服务器来嵌入bokeh图。 这只是意味着您将不会使用(可能不需要)它提供的额外功能。
实际上,您可以通过生成bokeh独立组件的方式以多种方式嵌入bokeh图,方法是生成bokeh独立组件,然后在渲染模板时将其嵌入到django应用中,或者使用我们称为“自动加载”的方法,该方法使bokeh返回将替换的标签本身具有散景图。 您可以在 documentation 找到更多详细信息。
另一个很好的灵感来源是可以在存储库中找到的 嵌入示例 。
这是一个
烧瓶应用程序
,它使用jquery与bokeh图进行交互。
查看可重复使用的javascript
templates/
。
还可以在github上搜索bokeh-demos。