Skip to main content

Posts

Showing posts from July, 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 objec…

Custom Managers in Django

I had to add a bit of functionality to the Old Dog Haven "Walk For Old Dogs" registration and sponsorship site today (feel free to sponsor me!), specifically a way for the good folks running the event to see an aggregate total of the sponsorship dollars by registrant.

Here's the Django models for Registrant and Sponsor:
Pretty straight-forward -- main thing to notice is that Sponsor has a foreign key relationship with Registrant as opposed to the other way around. And yes, in its current incarnation sponsors can only sponsor one registrant; if they want to sponsor multiple registrants they simply create another sponsor record. (It's agile baby -- release early and often! Multiple sponsorships can happen next year!)

While calculating the total sponsorship dollars by each registrant could be handled via the Django ORM, I decided to use the opportunity to execute SQL directly in a function in a custom manager.

You can read more about custom managers in the Django docs,…