Question

I'm a heavy django-tables2 user and I've thought of adding a generic extension to the django-table: I want to allow the user to be able to export all the table data to excel (using xlwt) or csv just by clicking a button that would be somewhere near the table.

Now, I've implemented this in a non generic way, meaning that I've included a POST form and a button in my template and add a check to see if the button has been clicked the view that fills the table. If the button is clicked return the xls instead of the normal template. Also I've implemented a generic function that gets a django-table2 table (any table) and converts it to an xlwt sheet (in order to put it to a workbook).

This is working fine but since I will use this button to all my tables, I don't want to add the export form and button to all my html templates that would contain a table. Also I don't want to add the POST checks to all my views ! This is definitely not DRY :(

Ideally, I'd like to have a class let's say it ExportTable that would extend the Table class of django-tables2 and would be usable as a replacement - when I'd create my table using the ExportTable as a base class then the button and the view would have the required components to export the table. From what I can understand, this is not possible :(

Can somebody propose to me which way should I go to extend django-tables2 in order to be able to add the "export" functionality in the most DRY way possible ? Meaning that I'd be able to use only the {% render_table table %} tag in my templates (or an extension to that) and without the need to add checks to my views to see if the user has clicked the export button (and of course without the need to add extra views and url routes just to handle that). Is generic class views the way to go ?

I will accept the most DRY and complete (I'd like to have some source code with comments please) answer :)

Was it helpful?

Solution

I use django-tables2-reports to export tables2 data to csv and xls. I'm having issues with the xls at the mo (reported here) but I'm sure a solution will pop up soon.

OTHER TIPS

For anyone who stumbles across this question, Django-tables2 has a section dedicated to exporting in various formats simply using the tablib package. (exists since v1.8.0)

https://django-tables2.readthedocs.io/en/latest/pages/export.html

...

Now, if you append _export=csv to the query string, the browser will download a csv file containing your data. Supported export formats are:

csv, json, latex, ods, tsv, xls, xlsx, yml

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top