The object of the Django dictionary shows nothing in the model but is printed on the console

Following Django’s tutorials https://docs.djangoproject.com/en/1.6/topics/db/sql/#executing-custom-sql-directly
I have called a stored a procedure and populated a dictionary object.

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()
    ]

Printing print(results)
shows in the console:

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

However the list in the template shows nothing
:

Results Test


    {% for key, value in results.items %}
  • {{ key }}: {{ value }}
  • {% endfor %}

Why is this?

You are misunderstanding what the dictionary is used for when calling render_to_response
. If I were to call

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

I would effectively be able to use

{{customer_id}}

Somewhere in my template.

In this case, you want

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

However, notice that your results
variable is a list
, not a dictionary
, so in your template you will need something like

{% for result in results %}
    {% for key, value in result %}
    ...
Hello, buddy!稿源:Hello, buddy! (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » The object of the Django dictionary shows nothing in the model but is printed on the console

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录