Ported a fix from Django

https://github.com/django/django/commit/d11038acb2ea2f59a1d00a41b553f578b5f2c59c