Barburka
Barburka

Reputation: 465

Django - template containing model's 'table'

Here's my problem: I want to print a table in template which contains every object with every field

Here's my solution:

views.py

def start(request):
  all_rows = Person.objects.all()
  all_fields_names = Person._meta.get_fields()
  content = { 'all_rows': all_rows, 
              'all_fields_names': all_fields_names }

  return render(request, 'start.html', content)

start.html

<table class="table table-striped table-hover table-responsive">
<thead>
  {% for names in all_fields_names %}<th>{{ names.name |title }}</th>{% endfor %}
</thead>
<tbody>
  {% for row in all_rows %}
    <tr>
      <td>{{ row.name }}</td>
      <td>{{ row.yabadiba }}</td>
      <td>{{ row.value1 }}</td>
      <td>{{ row.value2 }}</td>
    </tr>
  {% endfor %}
</tbody>
</table>

Everything works perfectly. The problem is, when I don't know exactly how many fields is in the class. Second of all, my solution break the DRY rule. I've tried:

getattr(row, names)

and nested loops, with no success. Is there any simple solution?

Moreover: How to print such view for every class?

Upvotes: 1

Views: 778

Answers (1)

Tiny.D
Tiny.D

Reputation: 6556

What you need is values_list query in your views, it returns tuples when iterated over. Each tuple contains the value from the respective field or expression passed into the values_list()

all_fields_names = Mileage._meta.get_fields()   
value_fields = [f.name for f in all_fields_names]
all_rows = Mileage.objects.values_list(*(value_fields)) #pass fields to value_list

Then you can use nested for loop in your templates:

{% for row in all_rows %}
    <tr>{% for value in row %}<td>{{ value }}</td>{% endfor %}</tr>
{% endfor %}

Upvotes: 1

Related Questions