【问题标题】:How to show all dictionary in template in Django?如何在Django的模板中显示所有字典?
【发布时间】:2021-03-16 14:22:33
【问题描述】:

我正在使用 IFC,我需要从 .ifc 文件中提取一些数据以显示在 Django 模板中。

模板:

{% extends 'base.html' %}

{% block content %}
    <h2>upload</h2>
    <form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input type="file" name="document">
    <button type="submit">Upload File</button>
    </form>
    <br>
    {{result}}
{% endblock %}

我尝试了两种方法:

    OpenIfcFile = ifcopenshell.open(filepath) #select the file
    BrowseIfcProducts = OpenIfcFile.by_type('IfcElement') #search for the attribute 'IfcElement'
    for eachproduct in BrowseIfcProducts:
        #add the .ifc searched data to dict 'context' with 'result' key 
        context['result'] =
        [
            eachproduct.is_a(),
            eachproduct.GlobalId,
            eachproduct.get_info()["type"],
            eachproduct.get_info().get("Name","error"),
        ]
return render(request, 'upload.html', context)

在这种方法中,由于键“结果”在每次迭代中都不会改变,只存储最后一个项目,在我的模板中我看不到所有项目。

所以,为了解决这个问题,我将结果键连接到一个迭代器 (i):

    i = 1
    for eachproduct in BrowseIfcProducts:    
        context['{} {}'.format('result', i)] = [
            eachproduct.is_a(), 
            eachproduct.GlobalId, 
            eachproduct.get_info()["type"],
            eachproduct.get_info().get("Name","error"),
        ]
        i += 1
return render(request, 'upload.html', context)

但是很遗憾,模板中没有显示任何内容

我卡在这里,我不知道如何在模板上显示数据,有人可以帮助我吗?

【问题讨论】:

    标签: python django dictionary ifc


    【解决方案1】:

    在您引用{{ result }} 的模板中,但在您传递给视图的context 字典中似乎没有result 的键。

    由于您的键似乎是任意的,您可能只需要一个列表。 (或者如果您不需要复杂的运算符,您可以直接将BrowseIfcProducts 传递给模板)

    object_list = [[x.is_a(), z.GlobalId, x.get_info()["type"], x.get_info().get('name', 'Error')] for x in BrowseIfcProducts] 
    context['results'] = object_list
    

    并且在模板中你可以使用

    {{ results }}

    一个小的 FYI——如果你使用 Django 调试工具栏,在“模板”部分你可以看到你的模板可用的所有上下文——这可能有助于未来的调试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-24
      • 1970-01-01
      • 1970-01-01
      • 2014-11-21
      • 2013-05-06
      • 2020-10-19
      • 1970-01-01
      • 2012-04-19
      相关资源
      最近更新 更多