Search code examples
djangodjango-tables2

Handle a click event in django-tables2


I am starting to use django-tables2 and I have added a column which should allow user to delete a record when the user clicks on the button. The code looks as follows:

class ReviewTable(tables.Table):

    delete = tables.LinkColumn('review_delete', args=[tables.A('pk')], orderable=False,
                               empty_values=(), verbose_name='')

    def render_delete(self, record):
        url = static('remove.png')
        href = '#'
        return mark_safe('<a href="' + href + '" Delete><img src="' + url + '"></a>')

This basically enders the image fine in a column but all I can do is set the link to it. How can I get it to call some method where I can then filter by the record ID and delete the relevant record? Is this the correct way to do this?


Solution

  • When you generate HTML from code, you still have access to onclick events.

    return mark_safe('<a href="{0}" Delete class="delete" onclick='delete_action()'><img src="{1}"></a>'.format(href, url)
    

    Now your delete_action can be a javascript function that gives you more control. Generated HTML is basically just any old type of HTML, so you can still use jquery event handlers with it

    BTW, please note how string formatting has been used in stead of concatenation. This is more pythonic