【问题标题】:django-tables2: set attrs for many columns?django-tables2:为许多列设置属性?
【发布时间】:2015-10-16 13:56:32
【问题描述】:

我有一个包含许多列的 django-tables2 表。因此,我不想单独指定 Table 类中的每一列,而只是相应地设置 Model。

现在,我想更改一些可以通过名称识别的列的属性。我想做类似的事情:

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,其属性显然无法更改。

有谁知道这个问题的快速解决方法(“使选定的列右对齐”)?

谢谢你, 菲利普

【问题讨论】:

    标签: python css django django-tables2


    【解决方案1】:

    我发现执行此类操作的最佳方法是动态创建表(即使用 pythons type 创建一个 Table 类并设置其字段)。我在这篇文章中描述了这种技术(以解决不同的问题):http://spapas.github.io/2015/10/05/django-dynamic-tables-similar-models/

    我在那篇文章中提出的建议是创建一个get_table_class 方法来创建 Table 子类。在你的情况下,它可能是这样的:

    def get_table_class(模型): def get_table_column(字段): 如果 field.name.endswith('some_suffix'): return tables.Column(attrs={"td": {"align": "right"}}) 别的: 返回表.Column() 属性 = 字典( (f.name, get_table_column(f)) 对于 f in model._meta.fields 如果不是 f.name == 'id' ) attrs['Meta'] = type('Meta', (), {'attrs':{"class":"table"}, "order_by": ("-created_on", ) } ) klass = type('DTable', (tables.Table, ), attrs) 返回类

    上面的attrs = dict(...) 行创建了一个字典,其中包含您传递给它的模型的所有字段名称(id 字段除外)作为键和相应的Table 列(使用您的后缀检查将它们与@987654327 对齐@) 作为值。 attrs['Meta'] = ... 行将Meta 添加到此字典中(您可以看到不再需要模型属性),最后klass = type... 行使用上述字典创建Table 子类!

    【讨论】:

      【解决方案2】:

      我遇到了类似的问题,无法更改绑定列的属性。这个问题似乎是 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_columns:
                  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__ 方法 - 绑定它们并且更改在模板中可见。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多