Passing Arrays From Django To Javascript

To pass an array from Django to Javascript, you must convert it to a string first and then pass it to the template as part of the context. If your array contains strings then you need to be careful to properly enclose each string in quotes, which is a pain if the string contains quotes. A great solution is to use json. Like this:

# In your python code
import json
options = [[, unicode[x] for x in my_model.objects.all()]
options_for_js = json.dumps(options)

# In your Django template
var my_array = {{ options_for_js|safe }}

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s