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

Django: passing JSON from view to template

本文关键字:视图 JSON Django      更新时间:2023-09-26

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

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

其中每个CCD_ 2以unix时间为单位,而CCD_。

有没有一种方法可以在render函数的上下文中将时间序列数据作为json对象传递?

为什么这样做:我在前端使用Cal heatmap,它要求数据为json格式。Ajax请求目前可以正常工作,但如果可能的话,理想情况下我希望使用render方法。

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

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>

json.dumps值传递给模板。它已经是一个有效的JSON字符串,所以您不需要解析它或其他任何东西。只有在模板中呈现时,才将其标记为safe以防止HTML引用。

# views.py
def foo(request):
    time_series_json = json.dumps(time_series)
    return render(request, 
                  "template.html", 
                  context={'time_series': time_series_json})
# in the template
<script>
    const timeSeries = {{ time_series | safe }};
</script>

使用Django模板内置过滤器json_script:

views.py:中

render(request, "foo.html", {'time_series_data': time_series})

在模板foo.html:中

{{ time_series_data|json_script:"time-series-data" }}

在您的脚本中:

const timeSeriesData = JSON.parse(document.getElementById('time-series-data').textContent);

您是否尝试过将类似json.dumps(time_series)的东西传递给render函数?