1

I'm very new to Django and am trying to figure out why I can call the keys in a dict in my template as expected, but looping through the dict does not produce any text, nor any error messages. I don't want to hard code the key names (i.e. below msgid in my template, because the dict is dynamic and so I only want to loop through it.

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

In the template2.html you can see the msgid value (one of several values in smsreport_dict) being called, which is displayed on my page. But for some reason the smsreport_dict looping produces no text. Where am I going wrong?

pymat
  • 1,090
  • 1
  • 23
  • 45
  • Try `t.render(context={'smsreport_dict':smsreport_dict})` in your method `populate_html_text`. – Jens Apr 25 '17 at 14:55
  • @ Jens, ozgur: the resolve was a combination of both your answers. I needed to add items in my template, plus context={'smsreport_dict':smsreport_dict}. Thank you! – pymat Apr 25 '17 at 15:02

2 Answers2

2

smsreport_dict should be inside the Context you use in order to render the template:

...
html = t.render(Context({"smsreport_dict": smsreport_dict}))
...

Plus, you forgot to call .items when iterating through the dict in the template:

{% for key, value in smsreport_dict.items %}
  ...
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
0

You need to add .items to smsreport_dict

MSGID: {{ msgid }}

<p> Begin
{% for key, value in smsreport_dict.items %}
    <tr>
        <td> Key: {{ key }} </td> 
    </tr>
{% endfor %}
</p>End

See here for a similar situation.

Community
  • 1
  • 1
Brian Witte
  • 53
  • 1
  • 5