pymat
pymat

Reputation: 1182

Django template not displaying looped keys, values

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?

Upvotes: 1

Views: 254

Answers (2)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52153

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 %}
  ...

Upvotes: 2

Brian Witte
Brian Witte

Reputation: 53

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.

Upvotes: 0

Related Questions