Eliran Nider
Eliran Nider

Reputation: 75

Django adding dict to template as a table

How can I add dictionary to a template nicely with Django - Just want all the information in a nice table.

I have the following dict:

{'Information': {0: 'size', 1: 'energy [kWh]', 2: 'ratio [PR]'}, 'Value': {0: 570.66, 1: 984092.66, 2: 81.7}}

Tried to use {% for v in values[0] %} - Could not parse the remainder: '[0]' from 'values[0]'

HTML Part

         <div>
            <table>
                <tr>
                    <th>Information</th>
                    <th>Value</th>
                </tr>
                    <tr>
                        {% for key, values in dict_data.items %}
                        {% for v in values %}
                        <td>{{v}}</td>
                        {% endfor %}
                    </tr>
                    {% endfor %}
            </table>
        </div>

It's resulting with that: enter image description here

Thank you!

Upvotes: 0

Views: 466

Answers (1)

Sam
Sam

Reputation: 1415

I don't think your HTML matches what you say is resulting; your Information header is before the Value header, but in your output Value comes first. Also, you only have two headers <th>, but your nested dictionaries have 3 values, so the way you currently process the data will result in more cells in the table body than headers.

Another issue: your values is a dict also, so {% for v in values %} just gets you the keys (0, 1, 2) of the nest dict, and you never get the nested values (size, energy [kWh], ratio [PR]). You probably want something like:

{% for key, values in dict_data.items %}
{% for sub_key, sub_value in values.items %}

Also: you are processing one key/value set per row, so the first row of your table will have the Information values, and the second row will have the Value values (or vice-versa), but what you want is one value from Information and one value from Value per row. So ultimately you will need to structure your data differently (as pairs, perhaps).

Instead of your current structure, I'd have information/value pairs:

dict_data = {'Information': {0: 'size', 1: 'energy [kWh]', 2: 'ratio [PR]'}, 'Value': {0: 570.66, 1: 984092.66, 2: 81.7}}
info_value_pairs = [('size', 570.66), ('energy [kWh]', 984092.66), ('ratio [PR]', 81.7)]

and then in your template:

{% for pair in info_value_pairs %}
<tr><td>{{ pair.0 }}</td><td>{{ pair.1 }}</td></tr>
{% endfor %}

Upvotes: 2

Related Questions