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

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

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