DalinDad
DalinDad

Reputation: 103

How to delete columns in django-tables2?

I instantiate my table in my view.

view.py

def my_function():
    ...
    ...
    #init a new table with data and news columns !!!!!
    table = ResistanceTable(data=data,newscolumns=geneList)

    return render(request, 'page.html',  {'table': table})

with data a dict of data and geneList a list of name for news columns.

tables.py

class ResistanceTable(tables.Table):

    souche = tables.Column();
    column_default_show = ['souche']

    def __init__(self, data, newscolumns, *args, **kwargs):
    
        if newscolumns:
        
            for col in newscolumns:
                self.base_columns[col] = tables.Column(verbose_name=col)

        super(ResistanceTable, self).__init__( data, newscolumns, *args, **kwargs)
    

    class Meta:
        attrs = {'class': 'table table-bordered table-striped table-condensed'}

The problem is when I run my code the first time, I have all I want. But if I run my code a second time, the table model will keep the column defined previously.

How to remove these columns?

Upvotes: 1

Views: 1219

Answers (2)

Brett Beeson
Brett Beeson

Reputation: 19

If you, like me, came from Google wanting to "delete a column" from a Table, consider using exclude as documented. For example:

  table1  = ResistanceTable(data, exclude="coumn_name_to_exclude")

Upvotes: 1

Jieter
Jieter

Reputation: 4229

Use extra_columns argument to the table constructor.

extra_columns (str, Column) – list of (name, column)-tuples containing extra columns to add to the instance.

This will make sure a copy is made of Table.base_columns before the extra columns are added to the table instance.

Upvotes: -1

Related Questions