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

836
Vistas
How to use the context variables passed from Django in javascript?

I am having a method in views.py as follows:

def index(self, request):
    initial = get_initial()
    context = {"context" : initial_topics}
    template = loader.get_template('index.html')
    return HttpResponse(template.render(context, request))

How do I access the "context" dict in javascript ?? Like in my $(function(){});

about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

You can access the context variable inside the HTML script tag.

Still, some rules apply:

  1. If the context variable is a string, surround the context variable in quotes.
  2. If the context variable is a dict or a list, convert them to json in your view and use the safe filter:

Warning: Never use safe filter on untrusted data (such as data submitted by a user). Always sanitize the data (escape unsafe characters) before using the safe filter. Read about XSS attacks to learn more.


Example:

<script>
$(function(){
    var my_str = "{{ my_str }}";
    var my_dict = {{ my_dict|safe }}; // no quotes here
    var my_list = {{ my_list|safe }}; // no quotes here
});
</script>

You should convert the dict and list variables to json in your views because if there are any Python specific keywords, such as True or False or None in the dict, JS won't understand them and will raise an error.

In JS, the equivalent keywords are true, false and null. So, converting dicts and lists to json will transform the data into a JS compatible format.

Example:

import json 

def my_view(...):
    my_list = [...]
    my_dict = {...}
    
    context = {'my_list': json.dumps(my_list), 'my_dict': json.dumps(my_dict)}
    return ...
var my_list = {{ my_list|safe }};
var my_dict = {{ my_dict|safe }};
about 4 years ago · Santiago Trujillo Denunciar

0

If the javascript code lies in the html template being rendered, you can use it in the normal way {{ context }}. Else, declare a global in the html template and access that global from your separate js file.

about 4 years ago · Santiago Trujillo Denunciar

0

If you want to insert into Javascript then make sure to use escapejs, and in more advanced cases you may need to use JSON.parse;

var context = "{{ context }}"

If you are still having issues, then try;

var context = JSON.parse("{{ context|escapejs }}");

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned. doc

about 4 years ago · Santiago Trujillo 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