Search code examples
pythondjangodjango-tables2

How to add GET parameters to django-tables2 LinkColumn


I am trying to set GET parameters on a LinkColumn based on Accessors with django-tables2.

Let's say:

urls.py

urlpatterns = [
...
    url(r'^rqGET$', views.rqGET, name='rqGET'),
...
]

views.py

def rqGET(request):
    #... do something with request.GET

tables.py

class MyTable(tables.Table):
    id = LinkColumn('rqGet',text='Link') # do something with Accessors to make a GET string, maybe ?id=A('pk')
    class Meta:
        model = MyModel #(has field 'id')
 

I want to use reverse to get the correct url, then construct the GET parameter string. For example /rqGET?id=1 ('1' would be different in each row).


Solution

  • That's not really how Accessors work in django-tables2. Django-tables2 uses django's reverse to generate urls. If you want reverse to be able to generate the url, you need to define the parameters in your urls, which will be passed as arguments to your view function:

    # urls.py
    
    urlpatterns = [
    ...
        url(r'^rqGET/(?P<id>\d+)$', views.rqGET, name='rqGET'),
    ...
    ]
    
    # views.py
    def rqGET(request, id):
        # do something with request/id.
    

    If you don't want to change the way your url is formatted, you can use a custom render_ function on your MyTable like this:

    # tables.py
    from django.core.urlresolvers import reverse
    
    class MyTable(tables.Table):
        id = LinkColumn('rqGet', text='Link') # do something with Accessors to make a GET string, maybe ?id=A('pk')
    
        class Meta:
            model = MyModel
    
        def render_id(self, record):
            url = reverse('rqGET')
            return format_html('<a href="{}?id={}">{}</a>', url, record.id, 'Link')
    

    This will render a link with format /rqGET/?id=<id>.