Creating a Javascript Object in Python/Django

Lets say you’ve got a view that handles your AJAX calls and you want to pass an javascript object back to your javascript callback. How to construct that object? Here it is:

from django.http import JsonResponse

def my_view(request):
    my_obj = {'item1': 'a', 'item2': 'b'}
    return JsonResponse(my_obj)

I think you can pass objects to template as part of context if you use json.dumps() to package the object.

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 = [[x.id, 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 }}