Search code examples
pythondjangodjango-tables2

django-tables2 Adding template column, which content depends on condition


Working with

  • Django framework
  • django-tables2

I have a table for which I add 2 additional template columns (buttons). I want to display only these buttons depending on the condition on other column. Lets say grade is G2 then edit/delete buttons are visible or active. Else they are not displayed or disabled. Here it how it looks now:

enter image description here

Is it possible to do that in table class? Or do I need to write some fancy jquery code?

Here is my tables.py

import django_tables2 as tables
from .models import Person
from django.urls import reverse_lazy


class PersonTable(tables.Table):

    T1     = '<button type="button" class="btn js-update" update-link="{{ record.get_absolute_url_update }}">update</button>'
    T2     = '<button type="button" class="btn js-delete" delete-link="{{ record.get_absolute_url_delete }}">delete</button>'
    edit   = tables.TemplateColumn(T1)
    delete = tables.TemplateColumn(T2)

    class Meta:
        model = Person
        fields        = ('name','surname','city','grade',)
        template_name = 'django_tables2/bootstrap4.html'

Solution

  • I think you can try like this:

    First Override TemplateColumn's render method:

    class CustomTemplateColumn(tables.TemplateColumn):
        def render(self, record, table, value, bound_column, **kwargs):
             if record.grade == "G2":
                 return ''
             return super(CustomTemplateColumn, self).render(record, table, value, bound_column, **kwargs)
    

    Then use it in the Table class:

    class PersonTable(tables.Table):
    
        T1     = '<button type="button" class="btn js-update" update-link="{{ record.get_absolute_url_update }}">update</button>'
        T2     = '<button type="button" class="btn js-delete" delete-link="{{ record.get_absolute_url_delete }}">delete</button>'
        edit   = CustomTemplateColumn(T1)
        delete = CustomTemplateColumn(T2)
    
        class Meta:
            model = Person
            fields        = ('name','surname','city','grade',)
            template_name = 'django_tables2/bootstrap4.html'