Django:将JSON从视图传递给模板 [英] Django: passing JSON from view to template

查看:252
本文介绍了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>

这篇关于Django:将JSON从视图传递给模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆