通过Django模板变量将Python对象传递给JavaScript [英] Passing Python Objects to JavaScript through Django Template Variable

查看:116
本文介绍了通过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

这篇关于通过Django模板变量将Python对象传递给JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆