Django字典对象在模板中不显示任何内容,但打印到控制台

时间:2014-10-07 19:32:45

标签: django django-templates django-views

按照Django的教程https://docs.djangoproject.com/en/1.6/topics/db/sql/#executing-custom-sql-directly,我调用了一个存储过程并填充了一个字典对象。

Views.py

@login_required
def team_edit(request):
    user_instance = request.user
    user_id = user_instance.id

    cursor = connection.cursor()   
    cursor.execute("CALL test(%s)", user_id) #Call db stored procedure

    results = dictfetchall(cursor)

    print(results)

    return render_to_response('team_edit.html',results, context_instance=RequestContext(request))

# Converts a list to a dict 
def dictfetchall(cursor):
    "Returns all rows from a cursor as a dict"
    desc = cursor.description
    return [
        dict(zip([col[0] for col in desc], row))
        for row in cursor.fetchall()
    ]

在控制台中显示print(results)

[{'private_league_name': "Root's League", 'host_user_id': 1}, {'private_league_name': "Joe's League", 'host_user_id': 3}]

然而,模板中的列表显示

   <h2>Results Test</h2><br>

        <ul>
            {% for key, value in results.items %}
            <li> {{ key }}: {{ value }}</li>
            {% endfor %}
        </ul>

为什么会这样?

2 个答案:

答案 0 :(得分:2)

更改return中的view.py行,如下所示:

return render_to_response('team_edit.html',{'results':results}, context_instance=RequestContext(request))

答案 1 :(得分:1)

您在调用render_to_response时误解了字典的用途。如果我打电话

return render_to_response('team_edit.html',{'customer_id' : 5}, context_instance=RequestContext(request))

我实际上可以使用

{{customer_id}}

我模板中的某个地方。

在这种情况下,你想要

return render_to_response('team_edit.html',{'results' : results}, context_instance=RequestContext(request))

但是,请注意您的results变量是列表,而不是词典,因此在您的模板中,您需要类似

的内容
{% for result in results %}
    {% for key, value in result %}
    ...