【发布时间】:2017-09-22 15:59:57
【问题描述】:
我对 Django 很陌生,我想弄清楚为什么我可以按预期在模板中调用字典中的键,但是循环遍历字典不会产生任何文本,也不会产生任何错误消息。我不想硬编码键名(即在我的模板中低于msgid,因为字典是动态的,所以我只想循环遍历它。
views.py
class Pymat_program(View):
def get(self, request, *args, **kwargs):
selected_xml = 'a_directory_to_my_file'
smsreport_dict = self.parse_xml_file(selected_xml)
html = self.populate_html_text(smsreport_dict)
return HttpResponse(html)
def populate_html_text(self, smsreport_dict):
t = get_template('template2.html')
html = t.render(smsreport_dict)
return html
template2.html
<p>MSGID: {{ msgid }}</p>
<p> Begin
{% for key, value in smsreport_dict %}
<tr>
<td> Key: {{ key }} </td>
</tr>
{% endfor %}
</p>End
在 template2.html 中,您可以看到 msgid 值(smsreport_dict 中的几个值之一)被调用,它显示在我的页面上。但由于某种原因,smsreport_dict 循环不会产生任何文本。我哪里错了?
【问题讨论】:
-
在你的方法
populate_html_text中尝试t.render(context={'smsreport_dict':smsreport_dict})。 -
@ Jens, ozgur:解决方案是您的两个答案的结合。我需要在我的模板中添加项目,加上 context={'smsreport_dict':smsreport_dict}。谢谢!
标签: python django django-templates