简体   繁体   English

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

[英]How to set up a file download dialog using Django and jQuery?

I am jQuery newbie and I have been trying to set up a file download dialog window without any success. 我是jQuery新手,我一直在尝试设置文件下载对话框窗口,但未成功。 If and when the dialog window is loaded, the user should have the option to download the dynamically generated file. 如果并且在加载对话框窗口时,用户应该可以选择下载动态生成的文件。 I am not able to set up a dialog window. 我无法设置对话框窗口。

On debugging, I can see that a valid http response is generated. 在调试时,我可以看到生成了一个有效的http响应。 Generated content disposition data is given below: 生成的内容处理数据如下:

 attachment; filename=foo.csv

Use Case: 用例:

My application is a Django web app used to display the data fetched from the database on a django template. 我的应用程序是Django Web应用程序,用于显示Django模板上从数据库获取的数据。 I want to provide the ability to download the displayed data in a csv format when required if the user clicks on a button with text 'Export To Csv' 如果用户单击带有文本“导出到Csv”的按钮,我想在需要时提供以csv格式下载显示的数据的功能

Code

Javascript/Html 使用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: HTML:

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

Django: 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 urls.py

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

views.py 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()

Instead of performing the POST in AJAX, have the browser navigate to the view naturally. 让浏览器自然地导航到视图,而不是在AJAX中执行POST。 The browser will then prompt for the download. 然后,浏览器将提示您进行下载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM