Home > Net >  Using for django loop inside of a JavaScript variable
Using for django loop inside of a JavaScript variable

Time:03-07

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. 

CodePudding user response:

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.

  • Related