0

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.

Leonardo
  • 2,439
  • 33
  • 17
  • 31

1 Answers1

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.

Helge Schneider
  • 483
  • 5
  • 8
  • I pass the song query through django template json like: ``{{ music|json_scripts: 'musics' }}`` how do i loop though the data – Oluwaseyi Obanibi Mar 06 '22 at 18:55
  • If you are serializing `musics` to json in your view, you do not have to loop through it in javascript. You could just do `const songs = {{ musics }}`. You can read more about serializing models [here](https://stackoverflow.com/a/37839240/15353043). Does the for loop work when you are inserting the `,`? – Helge Schneider Mar 06 '22 at 20:06
  • Thanks, have done it using the looping, just tried different approach and it worked – Oluwaseyi Obanibi Mar 07 '22 at 01:33