2013-07-17 45 views
0

我能夠在命令行中打印B字典的內容,但是當我在HttpResponse(B)中傳遞B時,它只顯示字典的鍵。我想要將字典的內容打印在模板上。但無法這樣做。我怎樣才能做到這一點?HttpResponse無法打印字典的內容

這裏是我的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? 

回答

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}) 
+0

謝謝。非常有用。 +1。 – PythonEnthusiast