gpt4 book ai didi

python - 如何使用 Django 和 jQuery 设置文件下载对话框?

转载 作者:太空宇宙 更新时间:2023-11-04 06:27:21 26 4
gpt4 key购买 nike

我是 jQuery 新手,我一直在尝试设置一个文件下载对话框窗口,但没有成功。如果对话窗口加载时,用户应该可以选择下载动态生成的文件。我无法设置对话窗口。

在调试时,我可以看到生成了一个有效的 http 响应。生成的内容处置数据如下:

 attachment; filename=foo.csv

用例:

我的应用程序是一个 Django 网络应用程序,用于在 Django 模板上显示从数据库中获取的数据。如果用户单击带有文本“导出到 Csv”的按钮,我想在需要时提供以 csv 格式下载显示数据的能力

代码

Javascript/HTML

/**
* Creates a file to be downloaded upon clicking a button.
*/
$('button[id*="ExportToCsv"]').click(function() {
var report_type = $(this).attr('id').split('ExportToCsv')[0];
// var report_date = '{{ report_date }}'.split('-');
$.ajax({
url: '/reports/' + report_type + '/export_to_csv/',
type: 'POST',
mimeType: 'text/csv',
data: {'report_date': '{{ report_date }}'},
success: function(data) {
return data;
}
});
});

HTML:

<button id = "ExportToCsv">Export To Csv</button>

Django:

class CsvOutputResponse(object):
"""Handles a csv file attachment object.

Attributes:
filename: String name of the csv file.
response: HttpResponse object.
writer: Csv writer object.
"""

def __init__(self, filename):
"""Initalizes the CsvOutputResponse class.

Args:
filename: String name of the csv file.
"""
self.filename = filename
self.response = self._InitializeResponse()
self.writer = csv.writer(self.response)

def _InitializeResponse(self):
"""Initialize a csv HttpResponse object.

Returns:
HttpResponse object.
"""
response = django_dep.HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = (
'attachment; filename=%s.csv' % self.filename)
return response

def WriteRow(self, content):
"""Write a single row to the csv file.

Args:
content: List of strings of csv field values.
"""
self.writer.writerow(content)

def WriteRows(self, content):
"""Write multiple row to the csv file.

Args:
content: List of lists of strings of csv field values.
"""
self.writer.writerows(content)

def GetCsvResponse(self):
"""Get the csv HttpResponse object.

Returns:
content: HttpResponse object.
"""
return self.response

urls.py

(r'^reports/(?P<report_type>\w+)/export_to_csv/$',
'myproject.myapp.views.ExportTab')

views.py

def ExportTab(request, report_type):
"""Generates a file to be exported and made available for download.

Args:
request: HttpRequest object.
report_type: String type of report to be generated.

Returns:
HttpResponse object.
"""
report_date = request.POST['report_date']
db = database.Database()
if report_type == 'Trailing':
reports = containers.GetTrailingReports()
elif report_type == 'Ytd':
reports = containers.GetYtdReports()
return CsvOutputResponse('foo.txt').writeRows(reports).GetCsvResponse()

最佳答案

不是在 AJAX 中执行 POST,而是让浏览器自然地导航到 View 。然后浏览器会提示下载。

关于python - 如何使用 Django 和 jQuery 设置文件下载对话框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6893946/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com