[Django]-Generating a dynamic HTML table from django template language

5๐Ÿ‘

โœ…

You can use the get_context_data method to send context to your template

Class table(TemplateView):
      template_name = 'table.html'

      def get_context_data(self, **kwargs):
            ctx = super(table, self).get_context_data(**kwargs)
            ctx['header'] = ['#', 'chemblID','Preferable Name']
            ctx['rows'] = [{'id':1, 'chemblid':534988,'prefName':'A'},
                           {'id':2, 'chemblid':31290,'prefName':'B'},
                           {'id':3, 'chemblid':98765,'prefName':'C'}]
            return ctx

And you can remove the extra loop in the html

<table class="table">
    <thead>
        <tr>
            {% for k in header %}
            <th>{{k}}</th>
            {% endfor %}
        </tr>
    </thead>
    <tbody>
        {% for r in rows %}
            <tr>
                <td>{{r.id}}</td>
                <td>{{r.chemblid}}</td>
                <td>{{r.prefName}}</td>
            </tr>
        {% endfor %}
    </tbody>
</table>
๐Ÿ‘คleelum1

-1๐Ÿ‘

In template
just change table class

<table class="table table-bordered">

In view

return render(request,self.template_name,{"header":header,"rows":rows})
๐Ÿ‘คPranay reddy

Leave a comment