Backported for Django 1.4 compatibility 

Thanks @tinnet for doing all the real work