51π
β
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>
8π
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>
π€Milan Cermak
- How do you actually use a reusable django app in a project?
- How to automatically get user's timezone from client in Django?
- Check if a function has a decorator
- How do I remove the square brackets at the end of a JS variable name during AJAX calls?
4π
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);
π€talz
2π
have you tried passing something like json.dumps(time_series)
to the render function?
π€Romeo Mihalcea
- How do I convert kilometres to degrees in Geodjango/GEOS?
- Make a Django model read-only?
- Group models in django admin
- Django runserver error when specifying port
- "Returning to that page might cause any action you took to be repeated" β Django
Source:stackexchange.com