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

460
Vistas
Passing a Dictionary from Django view to a Django template

I am trying to pass the following context from views.py to a Django Template:

views.py:

def home(request):
     context = {
           'dict_1': {'key_1': ['val_11', 'val_12'], 'key_2': ['val_21', 'val_22']} 
          }
return render(request, 'app/home.html', context)

home.html:

<script type="text/javascript">
    var java_dict = {{ dict_1 }};
    console.log(java_dict);
</script>

This throws an error: Uncaught SyntaxError: Unexpected token '&'

Upon investigating, I see that the dictionary in javascript is read as follows:

{&#39;key_1&#39;: [&#39;val_11&#39;, &#39;val_12&#39;], &#39;key_2&#39;: [&#39;val_21&#39;, &#39;val_22&#39;]}

which probably means that the quotes-character (') is read incorrectly. How do I fix this issue?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

The context data that you pass into Django templates are escaped by default, for security purposes.

If you're sure that the data is safe, you can do this:

views.py

import json

def home(request):
    # Use JSON dump so that it will be a data that can be loaded in javascript
    context = {
        'dict_1': json.dumps({
            'key_1': ['val_11', 'val_12'], 'key_2': ['val_21', 'val_22']
        })
    }
return render(request, 'app/home.html', context)

home.html

<script type="text/javascript">
    var java_dict = {{ dict_1| safe }};  // Actually solve your problem. Don't escape the data.
    console.log(java_dict);
</script>
about 4 years ago · Juan Pablo Isaza Denunciar

0

By default, all values in Django templates escape HTML characters for security purposes. If you want to use this dictionary in JavaScript you should use json_script filter. Please read the docs to understand what's going on.

A solution for your problem would be to:

  1. Add the script tag containing your dict to the template

    {{ dict_1 |json_script:"ID_OF_NEW_SCRIPT_TAG" }}
    
  2. Load the dict value in your script tag (I'll use the name you had in your example)

    var java_dict = JSON.parse(document.getElementById('ID_OF_NEW_SCRIPT_TAG').textContent);
    
    console.log(java_dict);
    

Replace ID_OF_NEW_SCRIPT_TAG with whatever ID makes sense to you.

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