2

I'm trying to build a table in a template based on a variable number of fields. The code I'm using is:

<table id="custom_report_table" class="display" width="100%">
          <thead>
            {% for field in fields %}
                <th>{{ field }}</th>
            {% endfor %}
          </thead>
          <tdody>
            {% for CI in CIs %}
              <tr>
                  <td>{{ CI }}</td>
              </tr>
            {% endfor %}
           </tdody>
        </table>

fields is a list with all the fields and CIs is a queryset with the data that needs to go into the table. The problem is that I usually know the name of the fields so I can call each on individually when creating the cells in the usual way:

{{CI.field1}}
{{CI.field2}}
....

But now I can't hard code the fields' names as they are variable and come from the list.

Is there a way to do this?

Thanks, Isaac

isaapm
  • 157
  • 2
  • 12
  • 2
    Related: http://stackoverflow.com/questions/2067006/accessing-a-dict-by-variable-in-django-templates and http://stackoverflow.com/questions/2894365/use-variable-as-dictionary-key-in-django-template. – alecxe Mar 20 '15 at 15:57

3 Answers3

0

Just iterate again over CIs using items

{% for key,value in CIs.items %}
<td>{{ key }} {{value}}</td>
{%endof%}
levi
  • 22,001
  • 7
  • 73
  • 74
  • sorry, this doesn't print anything. It doesn't get into the loop – isaapm Mar 20 '15 at 16:19
  • @isaapm sorry, It `CIs`, not `CI`. – levi Mar 20 '15 at 16:23
  • Hi Guys, getting a bit closer. The problem is that I was passing a queryset not a dict to the template. I'm passing a dict now with the following syntax in the view: 'CIs': CI_table.objects.values(*report_query_values).all()[:2] And I'm almost getting it, but it doesn't get the values of foreign keys as it did before, any ideas for this? – isaapm Mar 23 '15 at 12:08
0

If you only want to print items that are in fields:

{% for field_name, field_value in CIs.items %}
  {% if field_name in fields %}
    <th>{{ field_name }}</th>
    <td>{{ field_value }}</td>
  {% endif %}
{%endof%}
Selcuk
  • 57,004
  • 12
  • 102
  • 110
0

Solved by using .values in the queryset creation in the view. And to reference the foreign keys for each field I had to build up the list of values with a list of field_name_foreign_field. As the names for all foreign key fields followed a standard rule, it was quite easy with a for loop in the view.

isaapm
  • 157
  • 2
  • 12