Search code examples
djangopython-3.xdjango-tables2

How to export .csv with Django-Tables2?


I'm trying to export a table in .csv with Django-Tables2, I've done the following so far.

tables.py

class ClientTable(ColumnShiftTable):

    class Meta:
        model = Client
        sequence = ('id', 'nome_razao_social', 'cpf', 'cnpj', 'sit_fiscal')
        template_name = 'django_tables2/bootstrap.html'

views.py


class ClientsView(ExportMixin, CustomListView):
    template_name = 'relatorios/clients/geral.html'
    model = Client
    table_class = ClientTable
    context_object_name = 'all_clients'
    permission_codename = 'view_clients'

    def get_context_data(self, **kwargs):
        context = super(RelatorioClientsView,
                        self).get_context_data(**kwargs)

        table = ClientTable(Client.objects.all())
        table.paginate(page=self.request.GET.get('page', 1), per_page=15)

        context['table'] = table
        RequestConfig(self.request).configure(table)

        export_format = self.request.GET.get('_export', None)
        if TableExport.is_valid_format(export_format):
            exporter = TableExport(export_format, table)
            return exporter.response('table.{}'.format(export_format))

        return context

template.html

<div class="tabel" style="overflow-x: auto; white-space: nowrap;">
    {% load render_table from django_tables2 %}
    {% render_table table %}

    {% export_url "csv" %}
</div>

But I get this error Invalid block tag on line 56: 'export_url', expected 'endblock'. Did you forget to register or load this tag?

if I remove {% export_url "csv" %} the error stops appearing, but I do not have the link.


Solution

  • In template.html I added {% load django_tables2%}

    I passed SingleTableMixin as the 'ClientsView' parameter.

    In ClientTable I added export_formats = ['csv', 'xlsx']

    This solved my problem.