简体   繁体   中英

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?

self.columns contains instances of BoundColumn . These have some additional knowledge (eg 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM