python - 使用 django 模板将特定的 json 值填充到 html
问题描述
我是 json 新手,不熟悉它。
在我的 Django 视图文件中,我只想将某些 json 值传递给 Django 视图中的 html :学校、地址、每个学生的姓名(Andy、Tom、Jack)和 id(Andy.id、Tom.id、Jack.id) . 我怎样才能实现上述情况?
我的json内容是:
{
"school": "xxx",
"address": "xxx",
"number": "xxx,
"students": {
"Andy": {
"id": "xxx",
"add": "xxx"
},
"Tom": {
"id": "xxx",
"add": "xxx"
},
"Jack": {
"id": "xxx",
"add": "xxx"
},
},
}
在我的 view.py 中,我有这些代码。jresult 是 json 字符串,我使用 json.dumps() 来生成 JSON,但它会将所有 json 数据填充到 html 中。我怎样才能实现上述情况?任何帮助将不胜感激。
def model_form_upload(request):
if request.method == 'POST':
form = FileForm(request.POST, request.FILES)
if form.is_valid():
file = request.FILES['file'].read()
jresult = execution(file)
json_string = json.dumps(jresult, indent=4)
return render(request,
'virus/home.html',
{'json_string': json_string})
else:
form = FileForm()
return render(request, 'virus/upload.html', {
'form': form
})
我的 home.html 模板:
<body>
<pre>{{ json_string|safe }}</pre>
</body>
解决方案
您可以跳过使用json.dumps
并仅传递dict
对象,然后在模板中访问键以获取值。
示例:
<!-- template -->
School: {{ json_dict.school }}
Address: {{ json_dict.address }}
<!-- and so on -->
推荐阅读
- dask-distributed - 什么是“意外任务状态”错误?
- bash - 如何在 Linux 中生成指定数量的整数?
- c# - 如何订购 NUnit 测试装置的执行?
- javascript - 设置默认值属性后无法重新分配它
- c# - 如何保持命令处理程序的查询逻辑干净?(CQRS 和 MediatR)
- javascript - 在 MUI 主题中使用自定义颜色模式
- google-cloud-firestore - 在每条 Firebase 安全规则中扮演角色
- appium - Appium Inspector Screenshot request get 500 iOS
- django-models - Django 中的“str”和“datetime.timedelta”实例之间不支持“<=”
- ansible - 如何在 ansbile playbook 上使用 (delegate_to) 时成为非 root 用户?