单元格颜色Django-Tables2

问题描述:

问题:我在哪里编辑我的django代码以根据业务逻辑更改单个单元格的背景颜色?单元格颜色Django-Tables2

在我的views.py我有捕获列的“PTS”的最大值逻辑:

def show_teams(request): 
reg = Teamoffense.objects.filter(~Q(rk='RK')) 
pts = Teamoffense.objects.filter(~Q(pts='PTS')).values('pts') 
seq = [item['pts'] for item in pts] 
maxseq = max(seq) 

table = SimpleTable(reg) 
table_to_report = RequestConfig(request).configure(table) 
if table_to_report: 
    return create_report_http_response(table_to_report, request) 
return render(request, 'index.html', { 
    'table': table, 
    'reg': reg, 
    'maxseq': maxseq, 
}) 

我怎样才能使任何单元格与该列中的bgcolor最大值=“绿色“?我现在有一个显示像这样一个简单的表:

class SimpleTable(TableReport): 

class Meta: 
    model = Teamoffense 
    exclude = ("column1","column2") 
    exclude_from_report = ("column1","column2") 
    attrs = {'class': 'paleblue'} 
+0

@Jieter有没有办法做的是在这里完成:http://*.com/questions/37513463/how-to-change-color-of-django-tables-row与单个细胞? – Krusaderjake

经过研究展望Django-Tables2 API Docs我发现Table.render_foo methods是什么,需要在我的情况。这改变了列的呈现方式。请务必设置column.attrs而不是self.attrs,因为根据我的经验,这是我能够设置单个单元格样式的方式。

#tables.py 
import django_tables2 as tables 
from .models import MyTable 
from MyApp import views 


class SimpleTable(tables.Table): 


    def __init__(self, *args, **kwargs): 
     super(SimpleTable, self).__init__(*args, **kwargs) 
     self.maxpts = views.maxpts 

    #render_foo example method 
    def render_pts(self, value, column): 
     if value == self.maxpts: 
      column.attrs = {'td': {'bgcolor': 'lightgreen'}} 
     else: 
      column.attrs = {'td': {}} 
     return value 


    class Meta: 
     model = MyTable 
     attrs = {'class': 'paleblue'}