2015-10-16 56 views
1

我有一個包含許多列的django-tables2表。因此,我不想單獨指定Table類中的每一列,而只是相應地設置模型。django-tables2:爲許多列設置attrs?

現在,我想改變一些列的屬性,我可以通過它們的名稱來識別。我想這樣做:

table = MyTable(my_queryset) 

for col in table.columns.items(): 
    col_name = col[0] 
    if col_name.endswith('some_suffix'): 
     table.columns[col_name].attrs['td'].update({'align': 'right'}) 

...這是應該改變其名稱以'some_suffix'使得值右對齊結束所有列。

然而,問題似乎是table.columns[col_name]BoundColumn其屬性顯然不能改變。

有沒有人知道這個問題的快速解決方案(「讓選定的列右對齊」)?

謝謝你,菲利普

回答

0

我發現,做這種事情的最好方法是動態創建表(即使用蟒蛇type創建一個Table類並設置其字段)。我在這篇文章中描述了這種技術(解決不同的問題):http://spapas.github.io/2015/10/05/django-dynamic-tables-similar-models/

我在那篇文章中提出的建議是創建一個get_table_class方法,該方法將創建Table子類。在你的情況下,它可能是這樣的:

 
def get_table_class(model): 
     def get_table_column(field): 
      if field.name.endswith('some_suffix'): 
       return tables.Column(attrs={"td": {"align": "right"}}) 
      else: 
       return tables.Column() 

     attrs = dict(
      (f.name, get_table_column(f)) for 
      f in model._meta.fields if not f.name == 'id' 
    ) 
     attrs['Meta'] = type('Meta',(), {'attrs':{"class":"table"}, "order_by": ("-created_on",) }) 
     klass = type('DTable', (tables.Table,), attrs) 

     return klass 

上面的attrs = dict(...)行創建包含您傳遞給它(除了id字段)模型的所有字段名字典密鑰和相應的Table列(使用後綴檢查將它們與get_table_column對齊)作爲值。 attrs['Meta'] = ...行添加一個Meta到這本詞典(因爲你可以看到模型屬性不再需要),最後klass = type...行創建一個Table子類使用上面的字典!

0

我有一個類似的問題,無法更改綁定列的屬性。這個問題似乎是SO中唯一解決這個問題的問題。

除了table.columns還有一個屬性table.base_columns。第二列中的列尚未綁定。所以這裏是我的方法:

import django_tables2 as tables 

class YourTable(tables.Table) 
    # define your columns 

    # overload the init method 
    def __init__(self, *args, **kwargs): 
     for col in self.base_colulmns: 
      if col[0].endswith('some_suffix'): 
       col[1].attrs['td'].update({'align': 'right'}) 
     # very important! call the parent method 
     super(YourTable, self).__init__(*args, **kwargs) 

現在的更改將被保存,因爲它們是在綁定之前在基列中創建的。調用父方法 - 重載__init__方法 - 綁定它們,並且更改在模板中可見。