Search code examples
pythondjangopython-3.xconstructordjango-tables2

Django-tables2: Change attribute for multiple columns in __init__()


I can't figure out how to change attribute for multiple columns in one for loop.

I want to set orderable=False to multiple columns. The only way which works is to explicitely define all these columns so I can add orderable=False to constructor.

class PizzaTable(tables.Table):

    class Meta:
        template_name = 'django_tables2/bootstrap-responsive.html'
        model = Pizza
        fields = ['created', 'ham', 'olives', 'corn', 'price',]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        unorderable_columns = ['ham', 'olives', 'corn',]
        for column in unorderable_columns:
            self.columns[column].orderable = False

This raises:

can't set attribute

It has to be able to do it somehow, otherwise I would have to specify all of those columns:

ham = tables.Column(accessor='ham',orderable=False)

Do you have any ideas?


Solution

  • self.columns contains instances of BoundColumn. These have some additional knowledge (e.g. their own attribute name within the table they are used in) and refer to the actual defined Column instance via self.column. They also expose that column's orderable attribute via a setter-less property, hence the error. In order to dynamically change that property, you have to set the attribute on the underlying column:

     self.columns[column].column.orderable = False
     # instead of 
     # self.columns[column].orderable = False