Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

I have been trying to send a Python Dictionary to a HTML Page and use that dictionary in Javascript to add a Graph on my website, using Django

The form takes a Image Upload, and the code is as follows,

 <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">

This image is then sent to views.py where it is processed and a resultant image, as well as a dictionary is generated from that image. And then again, a HTML page is rendered where the dictionary as well as the resultant image is sent in context variable. The code is as follows,

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)

Now, I want to convert the Dictionary items and keys into two different Javascript arrays, which are then to be used to plot a Graph on the HTML page. The template code of the Javascript is as follows,

          <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>

I have tried a lot of different things to access my Python Dictionary in the Javascript Script and then convert that to Javascript arrays, but I still have not managed to do it. I also tried different Stackoverflow posts etc but nothing could really properly guide me on this. I am quite new to Django as well so I am not much aware of the syntax as well.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

From Django-doc json_script

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

inside your 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>
about 4 years ago · Juan Pablo Isaza Denunciar

0

can you take a try this,

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>
about 4 years ago · Juan Pablo Isaza Denunciar

0

html

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

JS

var dictionary = JSON.parse($('#dictionary').val());
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda