2014-11-15 1 views
1

У меня есть table.py, где я хотел бы изменить значки для значений True и False для каждого BooleanColumn. Я знаю, что он может быть изменен параметром yesno BooleanColumn, но я не знаю, как переопределить значение по умолчанию для всех BooleanColumns. Вот Кодекс tables.py (AACSB, Amba, EQUIS, MBA, КБС, ЦКМ и doubedegree являются BooleanFields):django-tables2 изменить yesno параметр для всех BooleanColumn

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', 
       ) 

ответ

2

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) Укажите дополнительные AttrS для 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=',') 
+0

Да, вы правы, '(«».split (« „), если isinstance (“», ул) еще кортеж (» ')) == [' '] 'so' [' '] [int (not True)] ==' ''but' [' '] [int (not False)] == IndexError' – madzohan

0

Вот полный код сейчас, благодаря ответу madzohan в. Обратите внимание, что я использовал Джанго-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', 
       ) 
+0

Почему вы сохранили 'yesno', если вы его не используете? просто переопределите метод '__init__' и удалите его – madzohan

+0

Да, хорошая идея. Большое спасибо. –

 Смежные вопросы

  • Нет связанных вопросов^_^