Instead of using order_by here and in line 125 you can order once like this
`profiles = profiles.order_by('userprofile')`

right after the if / else clause.