I have been able to pass primitive types such as integers like this, but I would like to pass more complicated objects, such as some the Django models that I have created. What is the correct way of doing this?
-
send it to the javascript as json – nathan hayfield May 24 '13 at 17:31
-
Can't you just pass it? As dict (which is json)? – Jerry Meng May 24 '13 at 17:32
-
There's no "correct" way. Just pass what you need as JSON, strings, etc. – Brandon Taylor May 24 '13 at 17:33
-
1Are there any advantages/disadvantages of converting from an object to JSON on the Python/JavaScript side? – abw333 May 24 '13 at 17:36
-
You want the data. This is the way to do it. So just forget about advantages/disadvantages. – Jerry Meng May 24 '13 at 17:39
-
JSON is the usual choice for sound reasons. Sometimes you need to do a little extra work to convert more complex Python types, and dates get a little tricky. But if you have something too complex to embed as a single literal, you'll be better served solving any conversion problems than you will trying to find another method. – Peter DeGlopper May 24 '13 at 17:40
2 Answers
I know I'm a little late to the party but I've stumbled upon this question in my own work.
This is the code that worked for me.
This is in my views.py file.
from django.shortcuts import render
from django.http import HttpResponse
from .models import Model
#This is the django module which allows the Django object to become JSON
from django.core import serializers
# Create your views here.
def posts_home(request):
json_data = serializers.serialize("json",Model.objects.all())
context = {
"json" : json_data,
}
return render(request, "HTMLPage.html",context)
Then when I'm accessing the data in my html file it looks like this:
<script type = 'text/javascript'>
var data = {{json|safe}}
data[0]["fields"].ATTRIBUTE
</script>
data is a list of JSON objects so I'm accessing the first one so that's why it's data[0]. Each JSON object has three properties: “pk”, “model” and “fields”. The "fields" attribute are the fields from your database. This information is found here: https://docs.djangoproject.com/es/1.9/topics/serialization/#serialization-formats-json

- 573
- 2
- 7
- 21
For Django model instances in particular, you can serialize them into JSON and use the serialized value in your template context.
From there, you can simply do:
var myObject = eval('(' + '{{ serialized_model_instance }}' + ')');
or
var myObject = JSON.parse('{{ serialized_model_instance }}');
if using JSON-js (which is safer).
For Python objects in general see How to make a class JSON serializable