How to export .csv with Django-Tables2?

大憨熊 提交于 2020-06-01 06:22:10

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/56463489/how-to-export-csv-with-django-tables2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!