使用 Django,将 Python 字典发送到 HTML 页面,并在 Javascript 脚本中将其转换为 Javascript 数组

Using Django, send a Python Dictionary to a HTML Page and convert it to Javascript arrays in Javascript Script

我一直在尝试将 Python 字典发送到 HTML 页面,并在 Javascript 中使用该字典在我的网站上添加图表,使用 Django

表单采取图片上传,代码如下,

 <div class=" mx-5 font-weight-bold">
    Uplaod Image
  </div>
  <input class=" " type="file" name="filePath">
  <input type="submit" class="btn btn-success" value="Submit">

然后将此图像发送到 views.py,在那里对其进行处理,并根据该图像生成合成图像和字典。然后再次呈现 HTML 页面,其中字典以及生成的图像在上下文变量中发送。代码如下,

def predictImage(request):
    fileObj = request.FILES['filePath']
    fs = FileSystemStorage()
    filePathName = fs.save(fileObj.name, fileObj)
    filePathName = fs.url(filePathName)
    testimage = '.'+filePathName
    img_result, resultant_array, total_objects = detect_image(testimage)
    cv2.imwrite("media/results/" + fileObj.name, img=img_result)

    context = {'filePathName':"media/results/"+fileObj.name, 'predictedLabel': dict(resultant_array), 'total_objects': total_objects}
    #context = {}
    return render(request, 'index.html', context)

现在,我想将字典项和键转换成两个不同的 Javascript 数组,然后用于在 HTML 页面上绘制图表。 Javascript的模板代码如下,

          <script>
            // const value = JSON.parse(document.getElementById('data_values').textContent);
            // alert(value);
            var xArray = [];
            var yArray = []; 
            
            var xArray = ["Italy", "France", "Spain", "USA", "Argentina"]; // xArray needs to have Python Dictionary's keys
            var yArray = [55, 49, 44, 24, 15]; // yArray needs to have Python Dictionary's values

            var layout = { title: "Distribution of Labels" };

            var data = [{ labels: xArray, values: yArray, hole: .5, type: "pie" }];

            Plotly.newPlot("myPlot", data, layout);
          </script>

我尝试了很多不同的方法来访问 Javascript 脚本中的 Python 字典,然后将其转换为 Javascript 数组,但我仍然没有成功它。我也尝试了不同的 Whosebug 帖子等,但没有什么能真正正确地指导我。我对 Django 也很陌生,所以我也不太了解语法。

来自 Django-doc json_script

{{ value|json_script:"hello-data" }}

在你的Javascript

里面
<script>    
  const data = JSON.parse(document.getElementById('hello-data').textContent);
  var xArray = Object.keys(data) // return list of keys
  var yArray = Object.values(data) // return list of values
</script>

html

<input type="hidden" id="dictionary" value="{{ dictionary }}" />

JS

var dictionary = JSON.parse($('#dictionary').val());

你能试试这个吗,

views.py

# context data
context = {'filePathName':"media/results/"+fileObj.name, 'predictedLabel': dict(resultant_array), 'total_objects': total_objects,
    "data":  {"Italy":11, "France":22, "Spain":22, "USA":23, "Argentina":12}}

template.html

  <script>
    // const data = JSON.parse();
    // alert(value);
    var data = JSON.parse("{{data|safe}}".replaceAll("'", '"'));
    var xArray = [];
    var yArray = []; 
    
    var xArray = Object.keys(data); // xArray needs to have Python Dictionary's keys
    var yArray = Object.values(data) // yArray needs to have Python Dictionary's values

    var layout = { title: "Distribution of Labels" };

    var data = [{ labels: xArray, values: yArray, hole: .5, type: "pie" }];

    Plotly.newPlot("myPlot", data, layout);
  </script>