Dynamically setting the verbose_name for a column while instantiating a table
intiocean opened this issue · 0 comments
I'm trying to dynamically set the verbose_name
of a column in a table and have recently found a bug with my existing approach (I have had it implemented this way for a long time and I'm not certain if the bug was always present or if it had just gone by unnoticed because most of the time my verbose_name
doesn't change AND because different workers serve each django request in production...).
What happens is that the verbose_name
I set in the init
seems to be sticky and doesn't change in the next initialisation and it continues displaying the previously configured verbose_name
. Maybe because base_colums
is a class property rather than an instance property... I took a look at the code but couldn't make sense the base_columns
- it has become more magic and complex internally since I last looked. 😅
A simplified version of my approach that exhibits the bug
class MyTable(tables.Table):
dynamic_col = tables.Column()
def __init__(self, dynamic_column_name, *args, **kwargs):
super().__init__(*args, **kwargs)
self.base_columns["dynamic_col"].verbose_name = dynamic_column_name
However, changing the last line to the below makes it work (but feels like a hack).
self.columns["dynamic_col"].column.verbose_name = dynamic_column_name
Is there a recommended way to dynamically change the verbose_name
of a column during table instantiation (I don't know the value until building the table).
I know I can pass a new column into the table constructor but that also feels like overkill.
You can reproduce the bug by creating the table I have defined above and then examining the column header
x = MyTable("abc", data={})
y = MyTable("xyz", data={})
x.columns["dynamic_col"].column.header
>
y.columns["dynamic_col"].column.header
> 'abc'
# After experimenting I tried creating a new table again and it seems to use the last value... 🤯
z = MyTable("zzz", data={})
z.columns["dynamic_col"].column.header
> 'xyz'