首页 > 解决方案 > 使用 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>

标签: pythonjsondjangodjango-templates

解决方案


您可以跳过使用json.dumps并仅传递dict对象,然后在模板中访问键以获取值。

示例

<!-- template -->

School: {{ json_dict.school }}
Address: {{ json_dict.address }}
<!-- and so on -->

推荐阅读