Reputation system
[oweals/karmaworld.git] / karmaworld / apps / users / views.py
1 #!/usr/bin/env python
2 # -*- coding:utf8 -*-
3 # Copyright (C) 2013  FinalsClub Foundation
4 from itertools import chain
5
6 from django.contrib.auth.models import User
7 from django.views.generic import TemplateView
8 from django.views.generic.list import MultipleObjectMixin
9 from karmaworld.apps.notes.models import Note
10 from karmaworld.apps.users.models import NoteKarmaEvent, CourseKarmaEvent, GenericKarmaEvent
11
12
13 class ProfileView(TemplateView, MultipleObjectMixin):
14     model = User
15     context_object_name = 'user' # name passed to template
16     template_name = 'user_profile.html'
17
18     @staticmethod
19     def compareProfileItems(a, b):
20         if a.__class__ == Note:
21             timestampA = a.uploaded_at
22         else:
23             timestampA = a.timestamp
24
25         if b.__class__ == Note:
26             timestampB = b.uploaded_at
27         else:
28             timestampB = b.timestamp
29
30         if timestampA < timestampB:
31             return -1
32         elif timestampA > timestampB:
33             return 1
34         else:
35             return 0
36
37     def get_context_data(self, **kwargs):
38         notes = [('note', o) for o in Note.objects.filter(user=self.request.user)]
39         generic_karma_events = [('generic_karma_events', o) for o in GenericKarmaEvent.objects.filter(user=self.request.user)]
40         note_karma_events = [('note_karma_event', o) for o in NoteKarmaEvent.objects.filter(user=self.request.user)]
41         course_karma_events = [('course_karma_event', o) for o in CourseKarmaEvent.objects.filter(user=self.request.user)]
42
43         result_list = sorted(chain(notes, generic_karma_events, note_karma_events, course_karma_events),
44                              cmp=ProfileView.compareProfileItems,
45                              key=lambda o: o[1],
46                              reverse=True)
47
48         kwargs['object_list'] = result_list
49
50         return super(ProfileView, self).get_context_data(**kwargs)
51