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

114
Visualizações
Using for django loop inside of a JavaScript variable

I want to loop through a django query in JavaScript, example: musics = Music.query.all().

I did something like this:

const songs = [
{% for music in musics %}
    {
        id: "{{music.id }}",
        songName: "{{ music.title }}",
        poster: "{{ music.cover_image.url }}",
    }
{% endfor %}
]
 Array.from(document.getElementsByClassName("songItem")).forEach((element, I) =>{
  element.getElementsByTagName('img').src = songs[I].poster;
})

I get

Uncaught TypeError: Cannot read properties of undefined (reading 'poster'),

but if I use console log

console.log(element.getElementsByTagName('img').src = songs[I].poster);

it works in the console.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are missing a , in your foor loop. Therefore you are getting a syntax error.

const songs = [
  {% for music in musics %}
    {id: "{{music.id }}",
     songName: "{{ music.title}}",
     poster: "{{music.cover_image.url}}",
    }, // <-- HERE 
  {% endfor %}
]

If you want to convert your object data to json, you could also do this in your view and pass the json date as a template variable instead of creating songs manually.

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