【问题标题】:How to export .csv with Django-Tables2?如何使用 Django-Tables2 导出 .csv?
【发布时间】:2019-06-05 15:23:04
【问题描述】:

我正在尝试使用 Django-Tables2 导出 .csv 中的表,到目前为止我已经完成了以下操作。

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>

但我收到此错误Invalid block tag on line 56: 'export_url', expected 'endblock'. Did you forget to register or load this tag?

如果我删除 {% export_url "csv" %},错误将停止出现,但我没有链接。

【问题讨论】:

  • export_url 是 url 的名称吗?如果是这样,您需要{% url 'export_url' csv %}。如果没有,则需要加载相关的templatetags文件{% load name-of-templatetags-file %}
  • 我按照文档做了。 “您可以使用 django_tables2 中包含的查询字符串模板标签来呈现将数据导出为 csv 的链接:{% export_url "csv"%} 这将确保保留任何其他查询字符串参数,例如在过滤表项时组合使用。” @HenryM
  • 您是否在模板顶部添加了{% load django_tables2 %}?
  • @HenryM - 当我添加 {% load django_tables2 %} 时,我收到此错误 ClientsView' object has no attribute 'get_table'

标签: django python-3.x django-tables2


【解决方案1】:

在template.html 我添加了{% load django_tables2%}

我将SingleTableMixin 作为“ClientsView”参数传递。

在ClientTable 我添加了export_formats = ['csv', 'xlsx']

这解决了我的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-20
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多