Solved: Django-Tables2 and AJAX

Yes, I'm a big fan of django-tables2.

DjangoTables2 provides me with a very simple, semantic and Pythonic way to create data-tables that support sorting, pagination and customized column sub-classing.

While working on a recent project, I had a need to add some AJAX functionality to one of the data tables to allow the user to click on a record and have that record removed from the table without refreshing the entire table.

After a few searches and perusing some StackOverflow Django posts, I was almost about to admit that there was no good way for DjangoTables2 to handle these types of requests.

From the online developer community, many of the ideas included links to django-eztables. Apparently, this module has better support for jQuery and AJAX.

While I will dig into django-eztables for future projects, I already know the process and workflow for DjT2.

I am not one to give up easily. I know I can make this work!

SOLVED: Here is my solution.

Let me take a moment to explain what is going on in the above Gists.

First, the Alerts model is very basic. I don't think too much explanation here is required. The urls.py file maps the necessary paths I will need for viewing alerts and dismissing alerts.

I use a tables.TemplateColumn() in tables.py to create a clickable icon that my users can click on to perform the desired action.

The action__template is a snippet of HTML which contains the markup required to add a FontAwesome times-circle icon as my clickable link item. I add a .dismiss class to the icon which will be passed to my jQuery script. That will remove the row of data from my table without refreshing the entire page.

The AlertsTable Meta attributes contains a row__attrs which holds the PK value for the alert as a data-alert-pk for each record/row.

Next, in the alerts.html, we output our data and include our JS. The JS is listening for click events within our alerts container. Every row contains the PK as a 'tr' data tag.

This is a sample output of the HTML markup of the table tr tags.

<tr class="even" data-alert-pk="9323">  
   <td>...</td>
</tr>  

The AJAX request is processed and our alert is removed from the table.

I knew I could get this to work. Now that I have all of the pieces working, I wanted to share my experience with my fellow Djangonauts.

Hope this helps anyone who likes to use django-tables2 as much as I do and needs to add some basic AJAX functionality.

Until next time...

Craig Derington

Full Stack Developer. Linux, Docker, Python, Celery, Flask, Django, Go, MySQL, MongoDB and Git. Modern, secure, high-performance applications capable of processing millions of transactions a day.

comments powered by Disqus