cell color Django-Tables2

[亡魂溺海] 提交于 2019-12-08 12:02:49

问题


Question: Where do I edit my django code to change the background color of individual cells based on business logic?

In my views.py I have logic that captures the max value of column '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,
})

How can I render any cell with the max value in that column a bgcolor = 'green'? I currently have a simple table that displays like so:

class SimpleTable(TableReport):

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

回答1:


After more research looking into the Django-Tables2 API Docs I found that the Table.render_foo methods is what was needed in my case. This changes how the column is rendered. Make sure to set the column.attrs and not self.attrs because in my experience this is how I was able to set the individual cell style.

#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'}


来源:https://stackoverflow.com/questions/38757887/cell-color-django-tables2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!