Home > Enterprise >  How to provide a dictionary with lists as values to Django Table2?
How to provide a dictionary with lists as values to Django Table2?

Time:05-04

I would like to populate a Django Table 2 with a dictionary like this, how can I do that ?

This is my code but the table has no data.

views.py

class MyDetailView(SingleTableMixin, generic.DetailView):
    model = MyModel

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        dic = {'col_1': [-6.9, -7.1, -3.8],
              'col_2': [-1.9, -7.9, -0.8],
              'col_3': ['2022-05-03T05:00:00Z', '2022-05-03T06:00:00Z', '2022-05-03T07:00:00Z']}

        table_2 = MyTable(dic)
        context['table_2'] = table_2
        return context

tables.py

class MyTable(tables.Table):
    col_1 = tables.Column()
    col_2 = tables.Column()
    col_3 = tables.Column()

CodePudding user response:

You enter values by row:

dic = [
    {"col_1": -6.9, "col_2": -1.9, "col_3": '2022-05-03T05:00:00Z'},
    # ...
]

Or a cooler way:

col_1 = [-6.9, -7.1, -3.8]
col_2 = [-1.9, -7.9, -0.8]
col_3 = ['2022-05-03T05:00:00Z', '2022-05-03T06:00:00Z', '2022-05-03T07:00:00Z']
dic =  [{"col_1": c1,"col_2": c2, "col_3": c3} for c1, c2, c3 in zip(col_1, col_2, col_3)]
  • Related