Search code examples
pythondjangodjango-tables2

How to Conditionally render a Link Column with Django Tables 2?


With the following table when returning the BoundColumn it is plaintext and not html.

class CarHistoryTable(tables.Table):

    edit = tables.LinkColumn(
        'Car:update',
        kwargs={'pk': A('id')},
        orderable=False,
        text='Edit'
    )

    def render_edit(self, record, value, bound_column):
        if record.state != Car.NEW:
            return ''
        return super().render_edit()

Ideally I want to return an empty text for Cars that are not NEW state. For other cars I would like to render the edit link.


Solution

  • I understand you assume you can call super().render_edit(), but that's not the case. The logic django-tables2 uses to decide what render-callable it should use looks like this:

    If a method render_<columnname> is defined on the table, it is used. In any other case, the render() method of the tables.LinkColumn() instance you assigned to edit while defining your CarHistoryTable is used.

    Now, to achieve your goal, I'd do something like this:

    class CarUpdateLinkColumn(tables.LinkColumn):
        def render(self, value, record, bound_column):
            if record.state != Car.NEW:
                return ''
            return super().render(value, record, bound_column)
    
    
    class CarHistoryTable(tables.Table):
        edit = tables.CarUpdateLinkColumn(
            'Car:update',
            kwargs={'pk': A('id')},
            orderable=False,
            text='Edit'
        )
    

    This defines a custom column derived from the LinkColumn you want in case of existing cars. The implementation of render() can call super().render() because such a method actually exists.