Django: passing JSON from view to template

后端 未结 3 557
滥情空心
滥情空心 2020-12-16 00:24

In views.py, I have time series data stored in a dictionary as follows:

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


        
相关标签:
3条回答
  • 2020-12-16 01:00

    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>
    
    0 讨论(0)
  • 2020-12-16 01:13

    have you tried passing something like json.dumps(time_series) to the render function?

    0 讨论(0)
  • 2020-12-16 01:20

    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>
    
    0 讨论(0)
提交回复
热议问题