在渲染Django table2之前访问每一行

时间:2018-08-06 16:07:59

标签: django django-tables2

我正在使用djangotables2来简单地呈现我的表,但是我想检查列的每一行的某些条件并在该值上打印一些附加内容 但无论如何我都找不到 在djangotables2中可以吗? 查看

class BowlerList(LoginRequiredMixin, PagedFilteredTableView):
    model = Bowlers
    template_name = 'bowlers_list.html'
    table_class = BowlerTable
    filter_class = BowlerListFilter
    formhelper_class = BowlerListFormHelper

    def get_context_data(self, **kwargs):
        context = super(BowlerList, self).get_context_data(**kwargs)
        context['select_list'] = UserSelect.objects.filter(user=self.request.user)
        return context

class BowlerTable(dt2.Table):
    name = tables.LinkColumn('bowler-detail', args=[A('pk')])

    class Meta:
        model = Bowlers
        fields = ('name', 'ahprank', 'pcarank')
        template_name = 'django_tables2/bootstrap-responsive.html'
        attrs = {'class': 'table table-striped table-bordered table-hover'}
        per_page = 10

模板

{% render_table table %}

我需要将“名称”列的值与我​​将在“ select_list”中获得的值进行比较,“ select_list”将作为上下文数据通过视图获取

1 个答案:

答案 0 :(得分:0)

根据文档,您可以自定义每个单元格的呈现方式。在这里检查:https://django-tables2.readthedocs.io/en/latest/pages/custom-data.html#table-render-foo-methods

基本上,您将添加render_<column_name>方法并在那里做您的工作。像这样:

class BowlerTable(dt2.Table):
    name = tables.LinkColumn('bowler-detail', args=[A('pk')])

    class Meta:
        model = Bowlers
        fields = ('name', 'ahprank', 'pcarank')
        template_name = 'django_tables2/bootstrap-responsive.html'
        attrs = {'class': 'table table-striped table-bordered table-hover'}
        per_page = 10

    def render_name(self, record):
        # Your code here

您可能唯一需要做的就是在表对象的初始化(select_list)中传递__init__,以便可以在新方法中访问它。