Search code examples
pythondjangodjango-tables2

How to pass data to django_tables2's LinkColumn


My urlconf snippet is:

url(r'^play/(?P<songid>\d+)', 'playid', name="playsongid")

the playid is a view function, it's definition like this:

def playid(request, songid):
    #do something

I use the django-tables2 library, their tutorial is [django-tables2][1]. My table sinppet is:

import django_tables2 as tables

class TestTable(tables.Table)
    links = tables.LinkColumn("playsongid", kwargs={"songid": ...})

the "..." is my confused position. How I pass a variety of songid data to it in my view function(this view function isn't playid, it's another view function)? I want the django-tables2 can render data like this:

column
<a href="/play/1">aaa</a>
<a href="/play/2">bbb</a>
<a href="/play/3">ccc</a>


Solution

  • Finally I get it to work by myself! tables.py finally like this:

    import django_tables2 as tables
    from django_tables2.utils import Accessor
    
    class TestTable(tables.Table)
        songid = tables.Column()
        links = tables.LinkColumn("playsongid", kwargs={"songid": Accessor("songid")})
    

    In my view function I pass data to it like this

        playlist = conn.playlistinfo()
        table_data = []
        for info in playlist:
            tmp_dict = {"songid": info.id}
            tmp_dict["links"] = "%s - %s" % (get_attr(info, "artist"), get_attr(info, "title"))
            table_data.append(tmp_dict)
            del tmp_dict
        variables["table"] = PlaylistTable(table_data)