Modified version of http://djangosnippets.org/snippets/605/