新手問題: 我有一本字典在views.py如何訪問Django模板中的鍵值?
我的觀點定義的方法與extra_Context
渲染:
extra_context = {
'comment': comment
}
return direct_to_template(request, 'events/comment_detail.html', extra_context)
如果我打印comment
的它打印這樣的:
[{'comment': u'first', 'user': 2}, {'comment': u'second', 'user': 2}]
我想將此字典傳遞給我的模板。我試着用這個下面的代碼:
<tbody>
{% for obj in comment %}
{% for key,val in obj.items %}
<tr class="{% cycle 'odd' 'even' %}">
<td> {{val}}</td>
</tr>
{% endfor %}
{% endfor %}
</tbody>
它打印:
first
2
second
2
我想以這樣的方式
first 2
second 2
..和等
我應該加什麼它像上面那樣?
更新!
def comment_detail(request, object_id):
comment_obj = EventComment.objects.filter(event = object_id)
comment = comment_obj.values('comment','user')
extra_context = {
'comment': comment
}
return direct_to_template(request, 'events/comment_detail.html', extra_context)
comment_detail.html
<form action="" method="POST">
<table>
<thead>
<tr><th>{% trans "Comments" %}</th><th>{% trans "Timestamp "%}<th>{% trans "User" %}</th></tr>
</thead>
<tbody>
{% if comments %}
{% for com in comment %}
<td> {{com.comment}}</enter code heretd>
<td> {{com.user}}</td>
{% endfor %}
{% else %}
<td> No comments </td>
{% endif %}
</tr>
</tbody>
</table>
</form>
謝謝你的回覆。但根據你的回覆,我必須追加的數據,我從數據庫中獲得。請看看更新!部分的問題:) 我剛剛在view.py中發佈了該方法 –
@AmitPal它呈現模板失敗嗎?你可以在剛剛添加的方法下添加錯誤嗎? – dschulz
我還在更新部分添加了我的模板。使用它打印沒有評論td –