Unable to embed JSON Bokeh Plot in Django template

早过忘川 提交于 2019-12-06 14:51:30

This is what I see so far:

FIRST: You are mixing 2 methods for injecting plot json data into the page. According to documentation you can do it using either of these two methods:

1) specify the div directly:

Python: json_data = json.dumps(json_item(p, "myplot"))
JavaScript: Bokeh.embed.embed_item(item);

2) specify the div in embed_item function:

Python: json_data = json.dumps(json_item(p))
JavaScript: Bokeh.embed.embed_item(item, "myplot");

But not both of them at the same time. Could this be the problem?

SECOND: Preferably don't insert Bokeh resources by hand: rather use CDN.render() or INLINE.render() to automatically include all that your script needs:

import json
from bokeh.resources import CDN

return render(request  = request, 
              template_name = 'app/sandbox_detail.html', 
              context = { json_object = json.loads(json_string), 
                          resources = CDN.render() } )

sandbox_detail.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
{{ resources }}
</head>
<body>
<div id="result"></div>
<script>
    Bokeh.embed.embed_item({{ json_object }}, "result");
</script>
</body>
</html>

THIRD: Make sure what you embed in the page is json object not a string (see variable naming above)

It helps when you debug your rendered template in your browser's debug tool.

I tried a very similar approach and found one large flaw: My browser noted that it could not find the None object. The reason here is that python stores the empty value as None, while JavaScript expects a null object.

The solution? Python already translates None to null, when you run json.dumps. To keep it that way, read the json string as a string. So instead of your data=json.loads(fp.read()) use data=fp.read().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!