[英]Django: export csv file with django_table2
我想要一个下载按钮 html 页面,该页面呈现 django 表。
我遵循了 django2 的文档和这篇文章How to export.csv with Django-Tables2? 很有帮助,但无法成功。
我觉得我做的一切都正确(根据我的初学者技能),没有错误但没有下载按钮。
我想知道是否有人对此有任何帮助
表.py
class AnormalTable(tables.Table):
class Meta:
model = stock_anormal
template_name = "django_tables2/bootstrap4.html"
export_formats = ['csv', 'xlsx']
视图.py
@method_decorator(login_required, name='dispatch')
class PostDetailalerte_negat(LoginRequiredMixin,APIView, tables.SingleTableMixin, ExportMixin):
def get(self, request):
queryset = stock_negatif.objects.all()
table = NegatTable(queryset)
RequestConfig(request).configure(table)
export_format = 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 render(request, 'detailstocknegat.html', {'table':table})
html 狙击手
<div class="d-sm-flex align-items-center justify-content-between mb-4">
<h1 class="h3 mb-0 text-gray-800">ITEMS IN ALERTE SAFETY STOCK LEVEL</h1>
<div>
{% for format in view.export_formart %}
<a href="{% export_url "csv" %}" class="d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm"><i class="fas fa-download fa-sm text-white-50"></i> Generate Report</a>
{% endfor %}
</div>
</div>
<table>
{% load django_tables2 %}
{% render_table table %}
</table>
我不确定这是否会解决这个特定问题,但我遇到了基本相同的问题,这就是我解决它的方法:
我将最初在 table.py 中的export_formats = ['csv', 'xlsx']
移动到我的表的视图中(本例中为 view.py)。 然后我通过更改 views.py 中的返回代码将 export_formats 直接传递给 html: return render(request, 'detailstocknegat.html', {'table':table, 'export_formats':export_formats})
。 然后在我的表的 html 中(本例中的 html 片段)我将 for 语句更改为:
{%for format in export_formats %}>
<a href="{% export_url format %}">
download <code>.{{ format }}</code>
</a>
{% endfor %}
我希望这可以帮助那里的人!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.