Search code examples
django-tables2

Create LinkColumn with dynamic link


How do I dynamically pass a viewname to LinkColumn, depending on the request URL? For example:

# called from example.com/foo
col = LinkColumn('foo_detail', args=[A('id')])

# called from example.com/bar
col = LinkColumn('bar_detail', args=[A('id')])

I could do something link this from the __init__() method but I need the request object to decide which viewname I need to pass to the LinkColumn and this is missing.


Solution

  • Interesting use case, I don't think there is a straightforward way to do so currently.

    A workaround would be to use get_absolute_url on the model's you are displaying, if those are different between the views. If you pass viewname=None to LinkColumn, it will use the url from record.get_absolute_url().

    The most pragmatic way to fix this would be a TemplateColumn with a small template to implement the different urls.