将JSON字符串传递给Django模板 [英] Passing JSON strings to Django templates
问题描述
我一直在想办法弄清楚为什么我不能将从Django模型生成的JSON字符串传递到模板的javascript静态文件中.事实证明,问题不在于模型级别(使用serializers.serialize)-将相同的字符串放入脚本本身将可以成功解析,但是将字符串传递不会:
views.py:
def texas(request):
test_json = '{"incidents": [{"field1": 1, "field2": 2}], "debug": 1}'
return render(request, 'tx/texas.html', {'tx': test_json})
tx/texas.html:
{% load staticfiles %}
<html>
<head>
<title>texas map</title>
</head>
<body>
<p id='texas'></p>
<script>
function load_texas() {
return '{{ tx }}';
}
</script>
<script src="{% static 'js/texas.js' %}"></script>
</body>
</html>
js/texas.js失败,并显示 JSON.parse:JSON数据的第1行第2列的预期属性名称或'}':
var json_data = load_texas();
var paragraph = document.getElementById('texas');
try {
paragraph.innerHTML = JSON.parse(json_data);
}
catch(err) {
paragraph.innerHTML = err.message;
}
,但是如果在脚本中输入了相同的字符串,则成功:
// this JSON string is identical to the one passed in views.py
var json_data = '{"incidents": [{"field1": 1, "field2": 2}], "debug": 1}';
我是否缺少有关Django处理上下文变量的方式的信息?
传递字符串不是一个很好的解决方法,但是我现在将JSON对象直接传递给模板,这解决了我最初将模型引入javascript的问题.
views.py:
from django.shortcuts import render
from django.core import serializers
import json
from .models import Tx
def texas(request):
tx_database = Tx.objects.all()
# Django serialize puts square brackets around the string,
# so slice them off.
json_string = serializers.serialize('json', tx_database)[1:-1]
# Load string into JSON object... is this best practice?
test_json = json.loads(json_string)
return render(request, 'tx/texas.html', {'tx': test_json})
您需要禁用自动转义.
return '{{ tx|safe }}';
请注意,您实际上不应该在视图中将JSON数据创建为字符串.将其创建为Python数据结构,然后使用json.dumps()
.
I've been banging my head against the wall trying to figure out why I can't pass a JSON string generated from a Django Model into a template's javascript static file. As it turns out, the problem wasn't at the Model level (using serializers.serialize) - putting an identical string in the script itself will successfully parse, but passing the string in will not:
views.py:
def texas(request):
test_json = '{"incidents": [{"field1": 1, "field2": 2}], "debug": 1}'
return render(request, 'tx/texas.html', {'tx': test_json})
tx/texas.html:
{% load staticfiles %}
<html>
<head>
<title>texas map</title>
</head>
<body>
<p id='texas'></p>
<script>
function load_texas() {
return '{{ tx }}';
}
</script>
<script src="{% static 'js/texas.js' %}"></script>
</body>
</html>
js/texas.js fails with JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data:
var json_data = load_texas();
var paragraph = document.getElementById('texas');
try {
paragraph.innerHTML = JSON.parse(json_data);
}
catch(err) {
paragraph.innerHTML = err.message;
}
but is successful if the same string is just entered in the script:
// this JSON string is identical to the one passed in views.py
var json_data = '{"incidents": [{"field1": 1, "field2": 2}], "debug": 1}';
Am I missing something about the way Django handles context variables?
Edit:
Not quite a fix for passing a string, but I'm now passing a JSON object directly to the template which solves my original problem of getting Models into javascript.
views.py:
from django.shortcuts import render
from django.core import serializers
import json
from .models import Tx
def texas(request):
tx_database = Tx.objects.all()
# Django serialize puts square brackets around the string,
# so slice them off.
json_string = serializers.serialize('json', tx_database)[1:-1]
# Load string into JSON object... is this best practice?
test_json = json.loads(json_string)
return render(request, 'tx/texas.html', {'tx': test_json})
You need to disable autoescaping.
return '{{ tx|safe }}';
Note, you really should not create JSON data as strings in your view; create it as a Python datastructure, then use json.dumps()
.
这篇关于将JSON字符串传递给Django模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!