5

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(){});

3 Answers 3

17

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 escapejs filter. You can also use the safe filter but with caution.

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.


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_string = 'hello'
    my_list = [...]
    my_dict = {...}
    
    context = {'my_list': json.dumps(my_list), 'my_dict': json.dumps(my_dict)}
    return ...
var my_string = '{{ my_string }}';

// for lists and dicts, use JSON.parse() to convert
// them into JS objects
var my_list = JSON.parse('{{ my_list|escapejs }}');
var my_dict = JSON.parse('{{ my_dict|escapejs }}');
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. I am passing a dict {"one" : 1, "two":2} like this for example. after doing json.dumps. In my javascript end, whenI just did alert("{{context}}" it gave "{"one": 1, "two": 2}". Plase gelp
@Trickycoder Hello. Sorry, my answer had some mistakes. I've fixed them and edited the whole answer and have added more explanation. Hope this helps you this time.
Is there any documentation on this?
Even when the context variable is just a string you should still use escapejs. Otherwise a Python string like "foo \" \' bar" would not be correctly represented in JS
3

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.

2 Comments

How can I apply this?
What exactly do you want to apply? The 1st method (JS code within html) or the 2nd (JS file separate)?
3

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

1 Comment

Can we use var my_dict = JSON.parse("{{ my_dict|safe }}"); ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.