Search code examples
djangodjango-tables2

Using Django tables 2, how do you cut off a long text field with an ellipsis?


I am using django-tables2 and I have a field that has really long text.

django-table2 long text

Which I would like to truncate like this:

django-table2 shortened text

It is a bootstrap table:

class EntryRecordTable(tables.Table):
    ...
    comment = tables.Column(accessor=A('Comment'))

    class Meta:
        template_name = 'django_tables2/bootstrap-responsive.html'
        attrs = {'class': 'table table-bordered'}
        orderable = False
        empty_text = 'No entries for selected dates'

I have tried this answer about truncating text in a bootstrap table, but it makes all rows a single line and truncates a bit too much. How can I do this in code?


Solution

  • You can do this by extending Column and overriding the render method:

    class TruncatedTextColumn(tables.Column):
        '''A Column to limit to 100 characters and add an ellipsis'''
        def render(self, value):
            if len(value) > 102:
                return value[0:99] + '...'
            return str(value)
    

    and usage:

    comment = TruncatedTextColumn(accessor=A('Comment'))