Django-tables2-动态向表添加列-不向HTML中的表标记添加属性 [英] Django-tables2 - dynamically adding columns to table - not adding attrs to table tag in html

查看:94
本文介绍了Django-tables2-动态向表添加列-不向HTML中的表标记添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Django项目中,我需要有一些表,这些表是动态的,并取决于数据库中的内容。所以我在这里,它可以工作,但有一点问题。这是带有我正在动态扩展的表的类:

In my Django project I need to have tables which columns are dynamic and depend on what is in the database. So I found a solution in here and it works but with a little problem. Here's the class with a table I'm extending dynamically:

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

这是扩展类:

def define_table(roles):
    attrs = dict((r.name, tables.Column() for r in roles)
    klass = type('DynamicTable', (ClientsTable,), attrs)
    return klass

当我在views.py中创建表时,如下所示:

When I'm creating a table in views.py like this:

table = define_table(roles)(queryset)

该表显示了我想要的列,但在html中代码,我看到它忽略了attrs:

The table shows columns like I wanted, but in the html code I see that it ignored the attrs:

{"class": "paleblue", "orderable":"True", "width":"100%"}

因此,淡蓝色没有css样式,这一点很重要对我来说。
我认为可能与Meta类有关,但是字段和模型正在工作,所以我不知道为什么attrs不起作用。

So there is no css style for paleblue, which is important to me. I feel that it might be something with Meta class but fields and model are working, so I have no idea why attrs are not.

推荐答案

首先,在django中元选项未继承 -表2。因此,您可以检查问题中讨论的解决方法,以查看是否合适,或者可以将Meta类手动添加到动态表中。为此,可以这样定义自己的define_table方法:

First of all, meta options are not inherited in django-tables2. So you may check the workarounds discussed in the issue to see if something fits or you can manuall add a Meta class to your dynamic table. To do that, you can your define_table method like this:


def define_table(roles):
  attrs = dict((r.name, tables.Column() for r in roles)
  attrs['Meta'] = type('Meta', (), dict(attrs={"class":"paleblue", "orderable":"True", "width":"100%"}) )
  return klass

两年多以后,糟糕!注意到我的代码中有一个错误-我忘了在<$之前加上 klass = type('DynamicTable',(ClientsTable,),attrs)这行c $ c>返回上方的杯子。我现在添加它是为了完整性。

Oops after more than two years I noticed that there was an error in my code -- I'd forgotten to include the line klass = type('DynamicTable', (ClientsTable,), attrs) before return klass above. I'm, adding it now for completeness.

这篇关于Django-tables2-动态向表添加列-不向HTML中的表标记添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆