简体   繁体   English

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

[英]Django: passing JSON from view to template

In views.py , I have time series data stored in a dictionary as follows:views.py ,我将时间序列数据存储在字典中,如下所示:

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

where each timestamp is in unix time and occurrences is an integer.其中每个timestamp都在 unix 时间, occurrences是一个整数。

Is there a way to pass the time series data as a json object in the context of the render function?有没有办法在render函数的上下文中将时间序列数据作为 json 对象传递?

Why do this: I am using Cal-heatmap on the front end which requires the data to be in json format.为什么这样做:我在前端使用Cal-heatmap ,它要求数据采用 json 格式。 Ajax requests work just fine for now but I ideally would like to use the render approach if possible. Ajax 请求现在工作得很好,但如果可能的话,我希望使用render方法。

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.如果前端库需要解析 JSON,您可以使用json库将 python dict 转换为 JSON 有效字符串。 Use the escapejs filter使用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(time_series)类的东西传递给渲染函数?

Pass a json.dumps value to the template.json.dumps值传递给模板。 It is already a valid JSON string so you don't need to parse it or anything.它已经是一个有效的 JSON 字符串,所以你不需要解析它或任何东西。 Only when rendering it in the template, mark it as safe to prevent HTML quoting.只有在模板中渲染时,才将其标记为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>

Using the Django templates built-in filter json_script :使用Django 模板内置过滤器json_script

In views.py :views.py

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

In the template foo.html :在模板foo.html

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

In your script:在你的脚本中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM