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

157
Views
Print Django model data as JavaScript Array

I have printed a for loop as below in my HTML Template:

                <td> 
                {% for athlete in booking.athlete.all %}
                {{athletes.id}}
                {% endfor %}
                </td>

The Output in HTML is as below.

<td> 
                
                1
                
                2
                
                3
                
                </td>

Is it possible to get the output to appear as [ "1", "2", "3" ], so we can then use this as a JS array or object?

I have tried a few things from the Django Template but it does not remove the additional white space.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The easiest way is probably to use a custom template tag to get the list of athlete.ids, and then the built-in json_script filter to render those ids as json.

Let's assume your app name is myapp. If you don't have any custom filters yet, create the directory myapp/templatetags/, and add an empty __init__.py file. Then in the file myapp/templatetags/myapp_filters.py add:

from django import template

register = template.Library()

@register.filter
def qs_to_id_list(qs):
    return list(qs.values_list('id', flat=True))

In your template example, you would do:

{% load myapp_filters %}
{% for booking in bookings %}
  <tr>
    <td>{{booking.id}}</td>
    <td>{{booking.program_type}}</td>
    <td>{{booking.booking_time}}</td>

    {# set a unique script id for easier access in javascript #} 
    {% with script_id='athletes-data-'|add:booking.id %}
        {{booking.athlete.all|qs_to_id_list|json_script:script_id}}
    {% endwith %}
  </tr>
{% endfor %}

The json_script filter will render a block like this (in each table row):

<script id="athletes-data-5" type="application/json">[1, 2, 3]</script>

which can be accessed in your client-side javascript.

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!