我能够在命令行中打印B字典的内容但是当我在HttpResponse(B)中传递B时,它只显示字典的键。我希望字典的内容可以打印在模板上。但无法这样做。我怎样才能做到这一点?
这是我的View.py文件
def A(request):
B = db_query() # B is of type 'dict'
print B # prints the whole dictionary content with key and value pairs in the command line.
return HttpResponse(B) #only prints the key in the template. Why?
答案 0 :(得分:2)
它只打印键,因为字典的默认迭代器只返回键。
>>> d = {'a': 1, 'b': 2}
>>> for i in d:
... print i
...
a
b
在模板中,您需要遍历键和值:
{% for k,v in var.iteritems %}
{{ k }}:{{ v }}
{% endfor %}
您还需要使用任何模板渲染功能,而不是HttpResponse
:
from django.shortcuts import render
def A(request):
b = db_query()
return render(request, 'template.html', {'var': b})