通过Django模板变量将Python对象传递给JavaScript
我已经能够传递原始类型,例如像这样的整数,但我想传递更复杂的对象,比如我创建的一些Django模型。这样做的正确方法是什么?
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?
我知道我参加派对有点晚了但是我偶然发现了在我自己的工作中提出这个问题。
I know I'm a little late to the party but I've stumbled upon this question in my own work.
这是适用于我的代码。
这是在我的views.py文件。
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)
然后,当我访问我的html文件中的数据时,它看起来像这样:
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>
数据是JSON对象的列表所以我正在访问第一个,所以这就是为什么它的数据[ 0]。每个JSON对象都有三个属性:pk,model和fields。 fields属性是数据库中的字段。此信息可在此处找到: https://docs.djangoproject。 com / es / 1.9 / topics / serialization / #serialization-formats-json
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