Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

339
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

0

html

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

JS

var dictionary = JSON.parse($('#dictionary').val());
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda