Reputation: 649
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:
<h2>Results Test</h2><br>
<ul>
{% for key, value in results.items %}
<li> {{ key }}: {{ value }}</li>
{% endfor %}
</ul>
Why is this?
Upvotes: 0
Views: 369
Reputation: 5194
change return
line in view.py
like this:
return render_to_response('team_edit.html',{'results':results}, context_instance=RequestContext(request))
Upvotes: 2
Reputation: 8326
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 %}
...
Upvotes: 1