how do i create a table from a dict using django-t

2019-07-13 04:06发布

I have a list of dict that look like this:

 [set([u'meal', '0:08:35.882945']),
  set([0, u'personal']),
  set([0, u'sleep']),
  set([0, u'transport']),
  set([0, u'work'])]

That I made from :

[u'meal',u'personal', u'sleep', u'transport', u'work']
['0:08:35.882945', 0, 0, 0, 0]

With this command:

nob =  [{m,n} for m,n in zip(cats,tot3)]

How can I turn this into a django-tables2 table?

I tried this :

# tables.py
class Small_table (tables.Table):
    category = tables.Column(verbose_name="category")
    class Meta:
        attrs = {"class": "paleblue"}

# views.py
nt = Small_table(nob)
RequestConfig(request).configure(nt)

But the table has one column of dashes rather than my data, what should I change?

2条回答
别忘想泡老子
2楼-- · 2019-07-13 04:22

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 %}
查看更多
神经病院院长
3楼-- · 2019-07-13 04:32

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.

查看更多
登录 后发表回答