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

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

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 Relatório

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 Relatório

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