我希望在模板中单击一个按钮,以将当前选定的记录导出到.csv文件。
这是我的部分模板,其中包括表单元素:
<form method="get">
<p>{{ summary_filter.form }}
<button type="submit">Search</button></p>
<button type="submit" name="period" value="current_month" class="btn btn-sm btn-outline-secondary">
Current Month
</button>
<button type="submit" name="period" value="last_month" class="btn btn-sm btn-outline-secondary">
Last Month
</button>
<button type="submit" name="period" value="current_qtr" class="btn btn-sm btn-outline-secondary">
Current Quarter
</button>
<button type="submit" name="period" value="last_qtr" class="btn btn-sm btn-outline-secondary">
Last Quarter
</button>
<button type="submit" name="export_data" value="export_data" class="btn btn-sm btn-outline-secondary">
Export messages
</button>
</form>
这是我对特定页面的看法:
def summary(request):
""" Summary page - Displays summary of data by day in tables """
all_messages = Message.objects.all()
summary_filter = SummaryFilter(request.GET, queryset=all_messages)
if request.GET:
filter_messages = summary_filter.qs
messages = data_filter(request.GET.get('period'), filter_messages)
else:
messages = data_filter("current_month", all_messages)
df = pd.DataFrame.from_records(messages.values())
if request.GET.get('export_data'):
filename = "message_export"
sio = io.BytesIO()
sheetname = "Messages"
writer = pd.ExcelWriter(sio, engine='xlsxwriter')
df.to_excel(writer, index=False, sheet_name=sheetname)
writer.save()
sio.seek(0)
response = StreamingHttpResponse(sio, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=%s.xlsx' % filename
return response
例如,我通过单击current_qtr按钮过滤到“当前季度”。该页面显示已正确过滤。然后,我想单击“导出数据”按钮,保留当前季度(和其他可能的过滤器)并通过同一视图导出。