Cleanup views.py code.

- Remove unnecessary imports.
- Fix indentation in the file.
- Use some comprehensions and shortcuts like: dict(), sorted(), iteritems() ...
- Move some logic into separate functions.

@assem-ch plz test this carefully since you know the edge cases better than me.