Simple export of CSV

379 views
Skip to first unread message

jlwlynn

unread,
Mar 24, 2010, 4:03:42 PM3/24/10
to Django users
I'm trying to simply export CSV, but have failed miserably. First I
perform a search and the query set is displayed in a template. I want
to have an export button that will export the data on the page, but
unfortunately, I lost the query set and even if I were to have it as a
parameter, it would only see it as a string to my exportCSV function.
Any ideas? THANKS IN ADVANCE!!!!

jason

Shawn Milochik

unread,
Mar 24, 2010, 4:16:28 PM3/24/10
to django...@googlegroups.com
Have your 'export' button make an AJAX call to a view, which creates the CSV file and prompts the user to 'Save As.'

Details:

1. Use the same view you currently have, with an 'if' statement which returns a standard (html) response or a CSV file based on a slug in your URL.

2. You're going to have to re-submit the parameters in your AJAX call. I recommend just using jQuery's serialize() and .post() to do this with no sweat.

3. An HTTP response is a file-like object. Save your CSV to it. You'll also need to change the contenttype. Great example here: http://docs.djangoproject.com/en/1.1/howto/outputting-csv/

End result: Someone runs your report. They see the results. They click the 'Export CSV button/link/graphic,' and they're prompted by their browser to save a CSV file without leaving the page they're on.

I'm doing almost exactly this, with the exception that I'm providing an Excel spreadsheet (xlwt module instead of csv and a different contenttype).

Shawn

Tom Evans

unread,
Mar 25, 2010, 5:44:18 AM3/25/10
to django...@googlegroups.com

Browsers generally don't display CSV inline, they will prompt to
download, so there is no need for AJAX nonsense. Just create a link to
a download view with the appropriate arguments in your initial result
page. When the user clicks the link, their browser will prompt them to
download the file, and the browser will remain on the results page.

The download view can be the same as the results view, with an
additional argument to denote that it should return CSV.

Cheers

Tom

Alex Robbins

unread,
Mar 25, 2010, 9:58:47 AM3/25/10
to Django users
Not sure if this will help, but the docs have a pretty in-depth
explanation of doing csv export. http://docs.djangoproject.com/en/dev/howto/outputting-csv/

HTH,
Alex

Reply all
Reply to author
Forward
0 new messages