在Django模板中迭代dict键

在Django模板中迭代dict键,django,python-3.x,django-templates,Django,Python 3.x,Django Templates,我有一个从视图传递到模板的dict,但是我不能让dict正确地显示数据,如果有的话。格言如下: context_dct = { 'product0': { 'totalentries': '6', 'type': 'hammers', 'brandname': 'DEWALT', 'price': '$25.84'}, 'product1': { 'totalentries': '5',

我有一个从视图传递到模板的dict,但是我不能让dict正确地显示数据,如果有的话。格言如下:

context_dct = {

    'product0': {
        'totalentries': '6', 
        'type': 'hammers', 
        'brandname': 'DEWALT', 
        'price': '$25.84'}, 

    'product1': {
        'totalentries': '5', 
        'type': 'hammers', 
        'brandname': 'DEWALT', 
        'price': '$25.84'}, 

    'product2': {
        'totalentries': '8', 
        'type': 'hammers', 
        'brandname': 'DEWALT', 
        'price': '$25.84'}
}
使用django 2.2和python3,我通过render()将dict传递给我的模板,并尝试像这样访问它:

<h1>Results:</h1>
{% for key, value in context_dct.items %}
    <h1>{{ key }}</h1>
    <h1>{{ value }}</h1>
    </br>
{% endfor %}
结果:
{%用于键,上下文中的值\u dct.items%}
{{key}}
{{value}}

{%endfor%}

但唯一显示的是h1标记中的“结果”。我还尝试了其他几种访问字典的方法,类似于普通的python字典访问,但都没有用。当我不使用嵌套字典时,我可以让它正常工作,但用这种方式,我一直无法让它工作。这里缺少什么吗?

你需要将你的字典封装到另一本字典中,给它起个名字,比如:

def some_view(request):
    # ...
    return render(request, 'some_template.html', { 'context_dct': context_dct })
def some_视图(请求):
# ...
返回呈现(请求'some_template.html',{'context_dct':context_dct})

否则,您将定义变量,如
product0
product1
,等等。

很好,它可以工作。我能问一下,为什么这样做有效?我不完全明白这里发生了什么。我希望这不是一个太离谱的问题。@data\u the\u goonie:dictionary将模板中的变量名映射到内容。如果您直接传递
上下文\u dct
,它会将
产品0
映射到该字典,等等。但是您希望将字典本身作为变量访问,因此我们可以通过构建映射
'context\u dct'
(名称)的字典来解决这一问题那么,一旦我将每个键值输入到模板中,我将如何访问它?我现在可以让它们以迭代方式打印出来,但我希望能够分别对它们进行操作。@data\u the\u goonie:您也可以将它们作为
{'context\u dct':context\u dct,**context\u dct}
写入字典中。