You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
importcsvimportcStringIOasStringIOfromdjango_downloadviewimportVirtualDownloadView, DownloadMixin, VirtualFilclassCsvDownloadMixin(DownloadMixin):
"""CSV download helper."""delimiter=";"quotechar='"'quoting=csv.QUOTE_MINIMALdefget_filename(self):
"Override this if you need a specific filename"return"download.csv"defget_header(self):
"""Return a list of cells to be written into the header. Please note that this row should be a list of unicode-ready strings. """raiseNotImplementedError("You need to write the get_header() method")
defget_rows(self):
"""Return a list of rows to be written into the body of the CSV file. Please note that each row should be a list of unicode-ready strings. """raiseNotImplementedError("You need to write the get_rows() method")
defwrite_header(self, csvwriter):
"""Write headers in the CSV file."""csvwriter.writerow(self.get_header())
defwrite_rows(self, csvwriter):
"""Write rows in the CSV file."""forrowinself.get_rows():
csvwriter.writerow(row)
defget_file(self):
"""Return a VirtualFile to be downloaded as CSV."""csvfile=StringIO.StringIO()
csvwriter=csv.writer(
csvfile, delimiter=self.delimiter, quotechar=self.quotechar,
quoting=self.quoting)
self.write_header(csvwriter)
self.write_rows(csvwriter)
returnVirtualFile(csvfile, self.get_filename())
classCsvDownloadView(CsvDownloadMixin, VirtualDownloadView):
pass
Generating CSV files dynamically is a common use case for VirtualDownloadView.
Perhaps a generic view could provide base scenario.
The text was updated successfully, but these errors were encountered: