Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

113
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!