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

418
Visualizações
using Django template tags in response to ajax

I use Ajax to update a list of objects, let's say each time a button is clicked. But I want to use Django template tags to generate each item of the list. The problem is that I have to send a JsonResponse back to JavaScript, but there, I can't use these tags.

I have to send object attributes as json. and I'm stuck with plain html in Ajax:

...
success: function (json) {
    if (json.new_messages.length) {
        for (let m of json.new_messages) {
            $('#messages-list').append("<li>"+m.sender_name+" "+m.content+"</li>");
        }
    }
},
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

One way I found to solve this problem is to render the template first, and then send the resulting text in response.

In a template file, only include the html that needs to be used in Ajax. No extra html tags. Here you can use all Django tags and filters. For example:

{% for m in messages_list %}
    <li>
    <b>{{ m.sender.profile.get_short_name }}</b>
    ({{ m.send_time|time:"H:i" }}):
    {{ m.content }}
    {% if m.sender == user %}
        {% if m.is_seen %}
            <b><small>✓✓</small></b>
        {% else %}
            <b><small>✓</small></b>
        {% endif %}
    {% endif %}
    </li>
{% empty %}
    <li>No messages here yet...</li>
{% endfor %}

In the view, using a function called render_to_string, render the template and send it in context of the json response:

response = render_to_string("just_list.html", context={"messages_list": new_messages})
return JsonResponse({"messages": response})

Then it can easily be used in Ajax:

...
success: function (json) {
    $('#messages-list').append(json.messages);
},
over 4 years ago · Santiago Trujillo 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