Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

159
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda