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

117
Vistas
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 Respuestas
Responde la pregunta

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