Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

340
Views
Usando Django, envíe un diccionario de Python a una página HTML y conviértalo en matrices de Javascript en Javascript Script

He estado tratando de enviar un diccionario de Python a una página HTML y usar ese diccionario en Javascript para agregar un gráfico en mi sitio web, usando Django

El formulario toma una carga de imagen, y el código es el siguiente,

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

Luego, esta imagen se envía a views.py , donde se procesa y se genera una imagen resultante, así como un diccionario a partir de esa imagen. Y, de nuevo, se representa una página HTML donde el diccionario y la imagen resultante se envían en la variable de contexto. El código es el siguiente,

 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)

Ahora, quiero convertir los elementos y claves del diccionario en dos matrices Javascript diferentes, que luego se utilizarán para trazar un gráfico en la página HTML. El código de plantilla del Javascript es el siguiente,

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

He intentado muchas cosas diferentes para acceder a mi diccionario de Python en el script de Javascript y luego convertirlo en matrices de Javascript, pero aún no he logrado hacerlo. También probé diferentes publicaciones de Stackoverflow, etc., pero nada realmente podría guiarme adecuadamente en esto. También soy bastante nuevo en Django, por lo que tampoco conozco mucho la sintaxis.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

De Django-doc json_script

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

dentro de tu 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 Report

0

¿Puedes probar esto?

vistas.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}}

plantilla.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 Report

0

html

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

JS

 var dictionary = JSON.parse($('#dictionary').val());
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!