[Django]-How do i create a table from a dict using django-tables2

4👍

this is what i ended up doing:

in my tables.py:

class Small_table (tables.Table):
    name = tables.Column(verbose_name="category",order_by="name")
    tot  = tables.Column(orderable=False)
    class Meta:
        attrs = {"class": "paleblue"}

in my view

from .tables import Small_table
from django_tables2   import RequestConfig
nob =  [{"name":m,"tot":n} for m,n in zip(cats,tot3)]
nt = Small_table(nob)
RequestConfig(request).configure(nt)
return render(request, "job/job_home.html", { "small":nt })

and in the template:

{% load render_table from django_tables2 %}
 <link rel="stylesheet" href="{{ STATIC_URL }}django_tables2/themes/paleblue
{% render_table small %}
👤mike

1👍

I’m not familiar with this django-tables app, but if your goal is to simply display your data in a table, I would do it like that:

  1. Your data structure is much too complicated. Simply create a list of tuples and return it as your template context.

    >>> a = [u'meal', u'personal', u'sleep', u'transport', u'work']
    >>> b =  ['0:08:35.882945', 0, 0, 0, 0]
    >>> nob = zip(a, b)
    >>> nob 
    [(u'meal', '0:08:35.882945'),
     (u'personal', 0),
     (u'sleep', 0),
     (u'transport', 0),
     (u'work', 0)]
    
  2. In your template, you can then do:

    <table> 
    {% for i, j in nob %}
        <tr>
            <td>{{ i }}</td>
            <td>{{ j }}</td>
        </tr>
    {% endfor %}
    </table>
    

This creates a row with two cells in the table for each entry in nob. Now you may see why a list of sets is not a good idea here. Sets don’t preserve the ordering of elements, i.e. {{ i }} would sometime be taken from list a and sometimes from list b whereas you want {{ i }} always to be taken from list a and {{ j }} always to be taken from list b.

Leave a comment