我得到的错误:
需要 2 个值在 for 循环中解包;得到 1.
这是我的观点:
class Index(View):
def get(self, request, slug):
test = {
1: {
'id': 1,
'slug': 'test-slug-1',
'name': 'Test Name 1'
},
2: {
'id': 2,
'slug': 'test-slug-2',
'name': 'Test Name 2'
}
}
context = {
'test': test
}
return render(request, 'wiki/category/index.html', context)
这是我的模板:
{% block content %}
<div>
{{ test }}
<ul>
{% for key, value in test %}
<li>
<a href="#">{{ key }}: {{ value }}</a>
</li>
{% endfor %}
</ul>
</div>
{% endblock %}
我也试过这样的模板:
{% block content %}
<div>
{{ test }}
<ul>
{% for value in test %}
<li>
<a href="#">{{ value }}: {{ value.name }}</a>
</li>
{% endfor %}
</ul>
</div>
{% endblock %}
然后没有错误,但是 {{ value }}
显示 key (很好),但是 {{ value.name }}
什么都不显示。 {{ test }}
显示我的字典。
最佳答案
遍历字典的项目以获取键和值:
{% for key, value in test.items %}
关于python - Django 模板 : key, 值在 for 循环中不可能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46437264/