Django:将JSON从视图传递给模板

问题描述:

views.py 中,我将时间序列数据存储在字典中,如下所示:

In views.py, I have time series data stored in a dictionary as follows:

time_series = {"timestamp1": occurrences, "timestamp2": occurrences}

其中每个时间戳在unix时间,出现是一个整数。

where each timestamp is in unix time and occurrences is an integer.

有没有办法在 render 函数的上下文中传递时间序列数据作为json对象?

Is there a way to pass the time series data as a json object in the context of the render function?

为什么要这样做:我正在使用 Cal-heatmap 在前端需要数据为json格式。 Ajax请求工作现在很好,但如果可能,我最好想使用 render 方法。

Why do this: I am using Cal-heatmap on the front end which requires the data to be in json format. Ajax requests work just fine for now but I ideally would like to use the render approach if possible.

如果前端库需要解析JSON,可以使用 json 库将python dict转换为JSON有效的字符串。使用 escapejs 过滤器

If a frontend library needs a to parse JSON, you can use the json library to convert a python dict to a JSON valid string. Use the escapejs filter

import json

def foo(request):
    json_string = json.dumps(<time_series>)
    render(request, "foo.html", {'time_series_json_string': json_string})


<script>
    var jsonObject = JSON.parse('{{ time_series_json_string | escapejs }}');
</script>