我有一个table.py,我想更改每个BooleanColumn的True和False值的图标。我知道它可以被BooleanColumn的yesno参数修改,但我不知道如何覆盖所有BooleanColumns的默认值。这是table.py的代码(aacsb,amba,equis,mba,bsc,msc和doubedegree是BooleanFields):
from django_tables2 import Column, Table
from manager.models import Partner
class PartnerTable(Table):
country_name = Column(accessor='country.name', verbose_name='Country')
region_name = Column(accessor='country.region.name', verbose_name='Region')
class Meta:
model = Partner
fields = ('name',
'country_name',
'region_name',
'website',
'aacsb',
'amba',
'equis',
'mba',
'bsc',
'msc',
'doubledegree',
)
答案 0 :(得分:4)
1)因此您可以简单地覆盖yesno
,其默认值为"✔,✘" (它只是str
):
some_name = BooleanColumn(yesno='1,2')
或删除文字:
some_name = BooleanColumn(yesno=',')
2)使用css
您可以指定自定义图片(不要忘记设置yesno=','
):
span.true {
background: url(../img/true.gif) top center no-repeat;
}
span.false {
background: url(../img/false.gif) top center no-repeat;
}
3)为span
指定一些额外的吸引力(但不要指定class
!):
some_name = BooleanColumn(attrs={'span': {'style': 'color:blue'}})
4)如果由于某些原因您想要更改默认课程设置行为(true
或false
) - 您应该覆盖BooleanColumn
及其方法render
from django.utils.html import escape
from django.utils.safestring import mark_safe
from django_tables2.utils import AttributeDict
class CustomBooleanColumn(BooleanColumn):
def render(self, value):
value = bool(value)
text = self.yesno[int(not value)]
html = '<span %s>%s</span>'
class_name = 'some_class_false'
if value:
class_name = 'some_class_true'
attrs = {'class': 'class_name'}
attrs.update(self.attrs.get('span', {}))
return mark_safe(html % (AttributeDict(attrs).as_html(), escape(text)))
覆盖你的字段
some_name = CustomBooleanColumn(yesno=',')
答案 1 :(得分:0)
现在这里有完整的代码,感谢madzohan的回答。请注意,我使用了django-bootstrap3,以便我可以使用引导程序图标:
from django_tables2 import BooleanColumn, Column, Table
from django.utils.safestring import mark_safe
from django_tables2.utils import AttributeDict
from manager.models import Partner
class BootstrapBooleanColumn(BooleanColumn):
def __init__(self, null=False, **kwargs):
if null:
kwargs["empty_values"] = ()
super(BooleanColumn, self).__init__(**kwargs)
def render(self, value):
value = bool(value)
html = "<span %s></span>"
class_name = "glyphicon glyphicon-remove"
if value:
class_name = "glyphicon glyphicon-ok"
attrs = {'class': class_name}
attrs.update(self.attrs.get('span', {}))
return mark_safe(html % (AttributeDict(attrs).as_html()))
class PartnerTable(Table):
country_name = Column(accessor='country.name', verbose_name='Country')
region_name = Column(accessor='country.region.name', verbose_name='Region')
aacsb = BootstrapBooleanColumn()
amba = BootstrapBooleanColumn()
equis = BootstrapBooleanColumn()
mba = BootstrapBooleanColumn()
bsc = BootstrapBooleanColumn()
msc = BootstrapBooleanColumn()
doubledegree = BootstrapBooleanColumn()
class Meta:
model = Partner
fields = ('name',
'country_name',
'region_name',
'website',
'aacsb',
'amba',
'equis',
'mba',
'bsc',
'msc',
'doubledegree',
)