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

时间:2011-08-01 03:15:40

标签: python django jquery django-templates

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

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

 attachment; filename=foo.csv

使用案例

我的应用程序是一个Django Web应用程序,用于在django模板上显示从数据库中获取的数据。我希望能够在需要时以csv格式下载显示的数据,如果用户点击带有文本'Export To 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()

1 个答案:

答案 0 :(得分:1)

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