问题:在哪里编辑django代码以根据业务逻辑更改单个单元格的背景颜色?
在我的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 :(得分:2)
在对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'}