简体   繁体   English

通过Django模板变量将Python对象传递给JavaScript

[英]Passing Python Objects to JavaScript through Django Template Variable

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. 我已经能够传递像这样的整数这样的原始类型,但是我想传递更复杂的对象,例如我创建的一些Django模型。 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. 我知道我参加聚会有点晚了,但是我在自己的工作中偶然发现了这个问题。

This is the code that worked for me. 这是对我有用的代码。

This is in my views.py file. 这是在我的views.py文件中。

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: 然后,当我访问html文件中的数据时,它看起来像这样:

<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]. data是JSON对象的列表,因此我正在访问第一个对象,因此这就是data [0]的原因。 Each JSON object has three properties: “pk”, “model” and “fields”. 每个JSON对象都有三个属性:“ pk”,“ model”和“ 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 可在以下位置找到此信息: https : //docs.djangoproject.com/es/1.9/topics/serialization/#serialization-formats-json

For Django model instances in particular, you can serialize them into JSON and use the serialized value in your template context. 特别是对于Django模型实例,您可以它们序列化为JSON并在模板上下文中使用序列化的值。

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). 如果使用JSON-js (更安全)。

For Python objects in general see How to make a class JSON serializable 有关Python对象的一般信息,请参见如何使可序列化的JSON类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM