在我的Django项目中,我需要有表,哪些列是动态的,并且取决于数据库中的内容.所以我在这里找到了一个解决方案,它有效,但有一点问题.这是我正在动态扩展的表的类:
class ClientsTable(tables.Table):
class Meta:
model = Client
attrs = {"class": "paleblue", "orderable":"True", "width":"100%"}
fields = ('name',)
def __init__(self, *args, **kwargs):
super(ClientsTable, self).__init__(*args, **kwargs)
self.counter = itertools.count()
def render_row_number(self):
return '%d' % next(self.counter)
def render_id(self, value):
return '%s' % value
Run Code Online (Sandbox Code Playgroud)
这是扩展类的方法:
def define_table(roles):
attrs = dict((r.name, tables.Column() for r in roles)
klass = type('DynamicTable', (ClientsTable,), attrs)
return klass
Run Code Online (Sandbox Code Playgroud)
当我在views.py中创建一个像这样的表:
table = define_table(roles)(queryset)
Run Code Online (Sandbox Code Playgroud)
该表显示了我想要的列,但在html代码中,我看到它忽略了attrs:
{"class": "paleblue", "orderable":"True", "width":"100%"}
Run Code Online (Sandbox Code Playgroud)
所以paleblue没有css风格,这对我很重要.我觉得它可能是Meta类的东西但是字段和模型正在工作,所以我不知道为什么没有attrs.