[英]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.