Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django-tables2 - how to use a custom filter in a TemplateColumn

I have a TemplateColumn in a django-tables2 table and I want to use a custom template filter (named int_to_time) to transform the data. When I use a built in filter it works fine.

What I have done until now is that I've copied the templates\django_tables2\table.html from django-tables2 to my project and included my tag library to table.html.

However, when I try to render my view, I get the following error:

TemplateSyntaxError at /details_show/2012/3/13/2
Invalid filter: 'int_to_time'

The error seems to be in line 28 of table.html

{% for column, cell in row.items %}

I can confirm that my tag library is loading because if for instance I write the name of the tag library wrong then I will get a Template library not found error.

Please help !

like image 817
Serafeim Avatar asked Dec 07 '25 07:12

Serafeim


1 Answers

Simplest solution

TemplateColumn renders the column externally to the template. Any custom filters or tags you load in the template won't be available.

You should be able to load the custom filter when you define the TemplateColumn. Something like:

name1 = tables.TemplateColumn('{% load my_filters %}{{ record.name|int_to_time }}')

Alternative (suggested by Bradley in comments)

Instead of using TemplateColumn in the class defining your table. Use a Column, but define a method render_columnname() with the formatting. Something like:

from myfilters import int_to_time

class MyTable(tables.Table):
    time = tables.Column()

    def render_time(self, value):
        return int_to_time(value)

See Table.render_FOO() Methods for more detail.

like image 75
Damien Ayers Avatar answered Dec 09 '25 00:12

Damien Ayers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!