Saturday, July 13, 2013

Generating CSV Files in Django

This is a very quick tip since it's so simple but I did run into one little wrinkle with string encoding while doing this so I thought I'd share.

I had a request to generate a CSV of all the Old Dog Haven "Walk for Old Dogs" registrants so the fine folks managing the event can do email blasts, print registration sheets, and the like.

Since Python has CSV functionality as part of the standard library the generation of the CSV data was very easy, and since the Django HTTP Response object was quite wisely designed to behave as a file-like object, writing the CSV data to the HTTP response was dead simple as well.

The only thing I ran into while writing the data to the response object was there were some non-ASCII characters in the database which threw this error:
'ascii' codec can't encode character u'\xe9' in position 4: ordinal not in range(128)
To get around this it was just a matter of tacking .encode('utf-8') to the end of the string objects when writing out the CSV data.

Here's the final result.


Juvelyn Reyes said...

This is a very helpful article. Those who are in data entry services are surely grateful of this post. Thanks for sharing.

Kylie James said...

For excellent skin care products and for anti-wrinkle properties check out how to tighten skin here.

JReyes said...

A very informative article. Those whose business support tasks include data entry and management will surely find this post useful. Thank you for posting.