Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django-tables2 edit yesno parameter for all BooleanColumn

I have a table.py where I would like to change the icons for True and False values of each BooleanColumn. I know that it can be modified by the yesno paramter of BooleanColumn, but I do not know how to override the default for all BooleanColumns. Here is the Code of tables.py (aacsb, amba, equis, mba, bsc, msc and doubedegree are 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',
                  )
like image 207
Mike Rochov Avatar asked Nov 19 '25 03:11

Mike Rochov


1 Answers

1) So you can simply override yesno which default value is "✔,✘" (it is just str):

some_name = BooleanColumn(yesno='1,2')

or remove text:

some_name = BooleanColumn(yesno=',')

2) Using css you can specify custom images (don't forget set yesno=','):

span.true {
    background: url(../img/true.gif) top center no-repeat;
}

span.false {
    background: url(../img/false.gif) top center no-repeat;
}

3) Specify some extra attrs to span (but don't specify class !):

some_name = BooleanColumn(attrs={'span': {'style': 'color:blue'}})

4) If for some reasons you want change default class setting behaviour (true or false) - you should override BooleanColumn and it's method 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)))

And override your field

some_name = CustomBooleanColumn(yesno=',')
like image 73
madzohan Avatar answered Nov 20 '25 16:11

madzohan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!