Search code examples
djangodjango-tables2

how to load unstructured non-queryset data with django-tables2


I'd like to use django-tables2 to display data from a spreadsheet or csv file. The data will always be dynamic so I need a way of dynamically adding columns to my django-tables2 table. From the documentation there seems to be no way of doing this.

Any ideas?


Solution

  • In Python, you can use type to construct classes dynamically.

    Let's use the example from the docs, which defines a table with one column, name.

    import django_tables2 as tables
    
    data = [
        {"name": "Bradley"},
        {"name": "Stevie"},
    ]
    
    class NameTable(tables.Table):
        name = tables.Column()
    

    This could be defined dynamically with

    NameTable = type('NameTable', (tables.Table,), {'name': tables.Column()})
    

    The data in your spreadsheet will be more complicated, but the same approach should work.