Search code examples
django-tables2

Pass additional parameters to django_table2 TemplateColumn


In my django project I have a lot of tables which return models. The last column is mostly an Action-Column where users may edit or delete an instance. How do I proceed if I want to pass additional arguments to TemplateColumn if in some tables I want an edit and delete button and in other tables I only need an edit and info button? I want to use the same template.html but with conditions in it. Here what I have in Table:

import django_tables2 as tables
from select_tool.models import DefactoCapability

class DefactoCapabilityTable(tables.Table):

    my_column = tables.TemplateColumn(verbose_name='Actions', template_name='core/actionColumnTable.html')

    class Meta:
         model = DefactoCapability
         template_name = 'django_tables2/bootstrap-responsive.html'
         attrs = {'class': 'table table-xss table-hover'}
         exclude = ( 'body', )
         orderable = False

And how do I check perms on the actions in order to display the button or not?


Solution

  • Quoting the TemplateColumn docs

    A Template object is created [...] and rendered with a context containing:

    • record – data record for the current row
    • value – value from record that corresponds to the current column
    • default – appropriate default value to use as fallback
    • row_counter – The number of the row this cell is being rendered in.
    • any context variables passed using the extra_context argument to TemplateColumn.

    So you could do something like this:

    my_column = tables.TemplateColumn(
        template_name='core/actionColumnTable.html',
        extra_context={
            'edit_button': True,
        }
    )
    

    The context also contains the complete context of the template from where {% render_table %} is called. So if you have 'django.template.context_processors.request' in your context_processors, you can access the current user using {{ request.user }}.