def generate_spreadsheet(request): """ Generates an Excel spreadsheet for review by a staff member. """ election = Election.objects.latest() ballots = election.ballots.all() ballots = SortedDict([(b, b.candidates.all()) for b in ballots]) # Flatten candidate list after converting QuerySets into lists candidates = sum(map(list, ballots.values()), []) votes = [(v, v.get_points_for_candidates(candidates)) for v in election.votes.all()] response = render_to_response("spreadsheet.html", { 'ballots': ballots.items(), 'votes': votes, }) filename = "election%s.xls" % (election.year_num) response['Content-Disposition'] = 'attachment; filename='+filename response['Content-Type'] = 'application/vnd.ms-excel; charset=utf-8' return response