[Answer]-Django-tables2 dynamic columns

1๐Ÿ‘

If you want to specify the columns of a table at runtime rather than at programming time, you can use the class below:

tables.py

import django_tables2 as tableslib

class DynamicColumnsTable(tableslib.Table):

    def __init__(self, *args, column_specs=(), **kwargs):
        bc = type(self.base_columns)(self.base_columns) # clone                                                                                                          
        for name, column in column_specs:
            self.base_columns[name] = column
        tableslib.Table.__init__(self, *args, **kwargs) # refers to static spec                                                                                          
        type(self).base_columns = bc # restore static spec

Example usage:

views.py

import django.shortcuts as shortcuts
import django_tables2 as tableslib

def test(request):
    data = [
        {"name": "Bobo"},
        {"name": "Gogo"},
    ]

    djtable = DynamicColumnsTable(column_specs=(  ('name', tableslib.Column()),  ),
                                  data=data)
    return shortcuts.render(request, 'test.html', {'djtable': djtable})
๐Ÿ‘คOlivier

0๐Ÿ‘

The Table should look like this:

class ABC(tables.Table):  
      user= tables.Column(accessor='user.username')
      column= tables.Column(accessor= 'column.header')  
      data= tables.Column(accessor='data')


    class Meta:
       model = Data
       sequence= ('user', 'column', 'data')

Details: http://django-tables2.readthedocs.org/en/latest/#specifying-alternative-data-for-a-column

๐Ÿ‘คruddra

Leave a comment