0

Is there a way to create a generic html table in Django. I want to reuse the same form.html to display entities with different columns.

For example in the below code a pass a list of headers, and dynamically create the thead,but I need for each row in the body to get every value. So I need to iterate. Or is there any other approach to reuse templates in a mo generic way instead of build N templates for each table yuo need to display

<table class="table table-bordered" id="vendor_table" style="text-align: center;">
    <thead class="tables-success"> 
        <tr>
            {% for header in list_headers %}
                <th>{{ header }}</th>
            {% endfor %}
        </tr>    
    </thead>
        {% for row in list_values %}
        <tr>
            {% for header_name in list_headers %}
                <th> {{ row.{{ header_name }} }} </th>  <---------
            {% endfor %}
        </tr>  
        {% endfor %} 
</table>
Diego Quirós
  • 898
  • 1
  • 14
  • 28
  • Could you elaborate? it seems like this is a perfectly right way to do what you're trying to achieve – Blye Jul 07 '23 at 23:33
  • If I understand your intent correctly, [this](https://stackoverflow.com/questions/36634923/django-form-dynamic-attribute-lookup) should answer your question about proper syntax for `{{ row.{{ header_name }} }}`. – STerliakov Jul 07 '23 at 23:43

1 Answers1

0

Passing

def get_classification( request ):
    objects = MyObject.objects.all()
    return render(request, 'myobject.html', { 'myObjects':objects, 'fields':ClassificationAdmin.list_display})

Then

<table class="table table-bordered" id="vendor_table" style="text-align: center;">
    <thead class="tables-success"> 
        <tr>
            {% for header in fields %}
                <th>{{ header }}</th>
            {% endfor %}
        </tr>    
    </thead>
        {% for row in myobjects%}
        <tr>
            {% for attr_name in fields%}
                <th> {{ row|getattr:attr_name}} }} </th> 
            {% endfor %}
        </tr>  
        {% endfor %} 
</table>
Diego Quirós
  • 898
  • 1
  • 14
  • 28