Search code examples
django-tables2

Rendering ManyToMandyColumn as individual links to each related object


I have a Unit table that has a ManyToMany relationship with Activities.

When rendering the Activities in my Unit table, I want to have each Activity be a link to its own detail view.

I have tried many methods of doing so, but have not been able to figure out the best method.

I can get the URLs using a lambda:

activities = tables.ManyToManyColumn(verbose_name='Activities', transform=lambda obj: obj.get_absolute_url,)

But I can not find a good solution for actually rendering that link.

It seems like I should be able to customize the rendering of the link by accessing each item in a render_activities() method. But the value in render_FOO() methods when using ManyToManyColumns doesn't seem to work.


Solution

  • As of django-tables2==2.0.0a5, ManyToManyColumn has a keyword argument linkify_item, which can be used like this:

    activities = tables.ManyToManyColumn(verbose_name="Activities", linkify_item=True)
    

    This will call get_absolute_url() for each related object in the ManyRelatedManager.

    For pre-2.0 versions of django-tables2, you can use the transform keyword argument to create the <a>-tags like this:

    activities = tables.ManyToManyColumn(
        verbose_name="Activities", 
        transform=lambda obj: '<a href="{}">{}</a>'.format(obj.get_absolute_url(), str(obj))
    )
    

    This slightly more verbose method also works in the 2.0.0 alpha versions.