Categories
Python Answers

How to pass Python Data to JavaScript via Django Python?

Spread the love

To pass Python Data to JavaScript via Django Python, we can call render_template_to_response with the data we want to pass to the template in a dict as the 2nd argument.

For instance, we write

from django.utils import simplejson


def view(request):
    js_data = simplejson.dumps(my_dict)
    # ...
    render_template_to_response("my_template.html", {"my_data": js_data})

to call render_template_to_response with the template file name and a dict with the data we pass to the template.

Then in our template, we write

<script type="text/javascript">
    data_from_django = {{ my_data }};
    widget.init(data_from_django);
</script>

to interpolate the my_data value in the template by putting my_data in curly braces.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *