'Django: passing JSON from view to template
In views.py, I have time series data stored in a dictionary as follows:
time_series = {"timestamp1": occurrences, "timestamp2": occurrences}
where each timestamp is in unix time and occurrences is an integer.
Is there a way to pass the time series data as a json object in the context of the render function?
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.
Solution 1:[1]
Pass a json.dumps value to the template. It is already a valid JSON string so you don't need to parse it or anything. Only when rendering it in the template, mark it as safe to prevent HTML quoting.
# 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>
Solution 2:[2]
have you tried passing something like json.dumps(time_series) to the render function?
Solution 3:[3]
Using the Django templates built-in filter json_script:
In views.py:
render(request, "foo.html", {'time_series_data': time_series})
In the template foo.html:
{{ time_series_data|json_script:"time-series-data" }}
In your script:
const timeSeriesData = JSON.parse(document.getElementById('time-series-data').textContent);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Milan Cermak |
| Solution 2 | Romeo Mihalcea |
| Solution 3 | talz |
