Mostly copy and pasted from django and style changes applied.
