Django中HTML模板无法显示Bokeh图表问题求助
Hey there, let's troubleshoot why your Bokeh plot is showing up as those four little dots instead of the actual chart in your Django app. This is usually a sign that the chart's JavaScript or HTML components aren't being loaded/rendered correctly. Here are the key fixes to try:
1. 确保正确使用components()函数
Bokeh需要将图表拆分为JavaScript和HTML组件才能嵌入Django模板。如果跳过这一步或只渲染其中一部分,就会出现占位符圆点。
首先,更新你的视图代码来生成这两个组件:
from bokeh.embed import components # ...(你创建figure对象'p'的现有代码) # 生成脚本和div元素 script, div = components(p) # 将两者传递给模板上下文 return render(request, "your_template.html", {"script": script, "div": div})
然后在模板中,你需要渲染div和脚本两者(别忘了用|safe过滤器避免Django转义代码):
{{ div|safe }} {{ script|safe }}
2. 验证Bokeh静态资源已加载
如果你的Django设置没有自动引入Bokeh的CSS和JS,图表将无法正常渲染。把这些代码添加到模板的<head>部分(确保版本与你安装的Bokeh版本一致——可以在Python中用bokeh.__version__查看):
<link rel="stylesheet" href="https://cdn.bokeh.org/bokeh/release/bokeh-2.4.3.min.css" type="text/css" /> <script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-2.4.3.min.js"></script>
3. 检查图表是否包含实际内容
一个空的Bokeh figure(没有添加线条、圆圈或其他图形元素)也会显示占位符圆点。确保你已向图表添加了数据:
from bokeh.plotting import figure # 创建figure并添加图形元素(示例:圆圈) p = figure(title="My Plot") p.circle([1, 2, 3, 4], [10, 20, 30, 40], size=12, color="red")
4. 查看浏览器控制台的错误信息
打开浏览器的开发者工具(F12)并切换到Console标签。任何JavaScript错误(比如资源加载失败、变量未定义)都会告诉你问题所在。常见问题包括CDN链接与安装包的Bokeh版本不匹配。
5. 确认模板上下文传递正确
仔细检查你是否正确将script和div变量传递给模板,没有拼写错误。例如,如果在视图中不小心将变量命名为scripts而不是script,模板将找不到它,从而导致占位符出现。
完整可用示例
这里提供一个端到端的示例供参考:
视图代码:
from django.shortcuts import render from bokeh.plotting import figure from bokeh.embed import components import bokeh def bokeh_plot_view(request): # 创建示例图表 p = figure(title="Sample Bokeh Plot", x_axis_label="X Values", y_axis_label="Y Values") p.line([1, 2, 3, 4, 5], [5, 3, 8, 1, 6], line_width=2) # 获取组件 script, div = components(p) # 传递版本号用于CDN链接 context = { "script": script, "div": div, "bokeh_version": bokeh.__version__ } return render(request, "plot_template.html", context)
模板(plot_template.html):
<!DOCTYPE html> <html> <head> <title>My Bokeh Plot</title> <link rel="stylesheet" href="https://cdn.bokeh.org/bokeh/release/bokeh-{{ bokeh_version }}.min.css" type="text/css" /> <script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-{{ bokeh_version }}.min.js"></script> </head> <body> <h1>My Bokeh Chart</h1> {{ div|safe }} {{ script|safe }} </body> </html>
内容的提问来源于stack exchange,提问作者Nitin

