Test coverage report: frequently.views

# frequently.views: 127 total statements, 100.0% covered

Generated: Sat 2013-07-20 15:17 CEST

Source file: /home/tobi/Projects/django-frequently/src/frequently/views.py

Stats: 118 executed, 0 missed, 9 excluded, 95 ignored

1. `"""`
2. `Views for the ``django-frequently`` application.`
3. ``
4. `"""`
5. `from math import fsum`
6. ``
7. `from django.contrib.auth.models import User`
8. `from django.core.urlresolvers import reverse`
9. `from django.http import HttpResponse, HttpResponseNotFound`
10. `from django.template.response import TemplateResponse`
11. `from django.utils import timezone`
12. `from django.views.generic import CreateView, DetailView, ListView`
13. ``
14. `from frequently.forms import EntryForm`
15. `from frequently.models import Entry, EntryCategory, Feedback`
16. ``
17. ``
18. `class EntryMixin(object):`
19. `"""`
20. `Mixin to handle and arrange the entry list.`
21. ``
22. `"""`
23. ``
24. `def get_ordered_entries(self, queryset=False):`
25. `"""`
26. `Custom ordering. First we get the average views and rating for`
27. `the categories's entries. Second we created a rank by multiplying`
28. `both. Last, we sort categories by this rank from top to bottom.`
29. ``
30. `Example:`
31. `- Cat_1`
32. `- Entry_1 (500 Views, Rating 2)`
33. `- Entry_2 (200 Views, Rating -4)`
34. `- Entry_3 (100 Views, Rating 3)`
35. `- Cat_2`
36. `- Entry_1 (200 Views, Rating 7)`
37. `- Entry_2 (50 Views, Rating 2)`
38. ``
39. `Result:`
40. `Cat_1 has a rank by: 88.88 (avg. views: 266.66, avg. rating: 0.33)`
41. `Cat_2 has a rank by: 562.5 (avg. views: 125, avg. rating: 4.5)`
42. ``
43. `Cat_2 will be displayed at the top. The algorithm is quality-oriented,`
44. `as you can see.`
45. ``
46. `"""`
47. `if queryset:`
48. `self.queryset = queryset`
49. `else:`
50. `self.queryset = EntryCategory.objects.all()`
51. `if self.queryset:`
52. `for category in self.queryset:`
53. `entries = category.get_entries()`
54. `if entries:`
55. `amount_list = [e.amount_of_views for e in entries]`
56. `rating_list = [e.rating() for e in entries]`
57. `views_per_entry = fsum(amount_list) / len(amount_list)`
58. `rating_per_entry = fsum(rating_list) / len(rating_list)`
59. `category.last_rank = views_per_entry * rating_per_entry`
60. `category.save()`
61. `else:`
62. `self.queryset = self.queryset.exclude(pk=category.pk)`
63. `self.queryset = sorted(self.queryset, key=lambda c: c.last_rank,`
64. `reverse=True)`
65. `return self.queryset`
66. ``
67. `def post(self, request, *args, **kwargs):`
68. `if "get_answer" in request.POST.keys():`
69. `entry = Entry.objects.get(pk=request.POST['get_answer'])`
70. `entry.last_view_date = timezone.now()`
71. `entry.amount_of_views += 1`
72. `entry.save()`
73. `return TemplateResponse(`
74. `request,`
75. `'frequently/partials/answer.html',`
76. `{`
77. `'entry': entry,`
78. `'rated_entries': self.request.session.get(`
79. `'rated_entries', False),`
80. `},`
81. `)`
82. `self.feedback = Feedback()`
83. `if "user_id" in request.POST.keys():`
84. `try:`
85. `user_id = int(request.POST.get('user_id'))`
86. `try:`
87. `self.feedback.user = User.objects.get(pk=user_id)`
88. `except User.DoesNotExist:`
89. `pass`
90. `except ValueError:`
91. `pass`
92. `if 'ratingID' in request.POST.keys() and request.is_ajax():`
93. `try:`
94. `entry_id = int(request.POST.get('ratingID').replace(`
95. `'ratingID', ''))`
96. `try:`
97. `entry = Entry.objects.get(pk=entry_id)`
98. `return HttpResponse(entry.rating())`
99. `except Entry.DoesNotExist:`
100. `return HttpResponseNotFound()`
101. `except ValueError:`
102. `return HttpResponseNotFound()`
103. `for key in request.POST.keys():`
104. `if key.startswith('up') or key.startswith('down'):`
105. `try:`
106. `entry_id = int(key.replace('up', '').replace('down', ''))`
107. `try:`
108. `entry = Entry.objects.get(pk=entry_id)`
109. `except Entry.DoesNotExist:`
110. `return HttpResponseNotFound()`
111. `except ValueError:`
112. `return HttpResponseNotFound()`
113. `if not request.session.get('rated_entries', False):`
114. `request.session['rated_entries'] = []`
115. `if not entry.pk in request.session['rated_entries']:`
116. `request.session['rated_entries'].append(entry.pk)`
117. `request.session.modified = True`
118. `self.feedback.entry = entry`
119. `if key.startswith('up'):`
120. `entry.upvotes += 1`
121. `self.feedback.validation = "P"`
122. `if key.startswith('down'):`
123. `entry.downvotes += 1`
124. `self.feedback.validation = "N"`
125. `entry.save()`
126. `self.feedback.save()`
127. `if request.is_ajax():`
128. `return TemplateResponse(`
129. `request,`
130. `'frequently/partials/feedback_form.html',`
131. `{`
132. `'feedback_entry': entry.pk,`
133. `'feedback': self.feedback,`
134. `},`
135. `)`
136. `elif key.startswith('feedback'):`
137. `try:`
138. `feedback_id = int(key.replace('feedback', ''))`
139. `try:`
140. `self.feedback = Feedback.objects.get(pk=feedback_id)`
141. `except Feedback.DoesNotExist:`
142. `return HttpResponseNotFound()`
143. `except ValueError:`
144. `return HttpResponseNotFound()`
145. `self.feedback.remark = request.POST.get("remark")`
146. `self.feedback.save()`
147. `if request.is_ajax():`
148. `return TemplateResponse(`
149. `request,`
150. `'frequently/partials/feedback_form.html',`
151. `{'feedback_send': True},`
152. `)`
153. `return self.get(self, request, *args, **kwargs)`
154. ``
155. ``
156. `class EntryCategoryListView(EntryMixin, ListView):`
157. `"""`
158. `Main view to display all categories and their entries.`
159. ``
160. `"""`
161. `model = EntryCategory`
162. `template_name = "frequently/entry_list.html"`
163. ``
164. `def get_queryset(self):`
165. `"""`
166. `Customized to get the ordered categories and entries from the Mixin.`
167. ``
168. `"""`
169. `self.queryset = super(EntryCategoryListView, self).get_queryset()`
170. `return self.get_ordered_entries(self.queryset)`
171. ``
172. ``
173. `class EntryDetailView(EntryMixin, DetailView):`
174. `"""`
175. `Main view to display one entry.`
176. ``
177. `"""`
178. `model = Entry`
179. `template_name = "frequently/entry_list.html"`
180. ``
181. `def get_object(self, **kwargs):`
182. `obj = super(EntryDetailView, self).get_object(**kwargs)`
183. `obj.last_view_date = timezone.now()`
184. `obj.amount_of_views += 1`
185. `obj.save()`
186. `return obj`
187. ``
188. `def get_context_data(self, **kwargs):`
189. `context = super(EntryDetailView, self).get_context_data(**kwargs)`
190. `context.update({`
191. `'rated_entries': self.request.session.get('rated_entries', False),`
192. `'object_list': self.get_ordered_entries(),`
193. `})`
194. `for key in self.request.POST.keys():`
195. `if key.startswith('down') or key.startswith('up'):`
196. `context.update({`
197. `'feedback_entry': int(`
198. `key.replace('up', '').replace('down', '')),`
199. `'feedback': self.feedback,`
200. `})`
201. `return context`
202. `return context`
203. ``
204. ``
205. `class EntryCreateView(CreateView):`
206. `"""`
207. `Feedback submission form view.`
208. ``
209. `"""`
210. `model = Entry`
211. `form_class = EntryForm`
212. ``
213. `def get_form_kwargs(self):`
214. `kwargs = super(EntryCreateView, self).get_form_kwargs()`
215. `if self.request.user.is_authenticated():`
216. `kwargs.update({`
217. `'owner': self.request.user,`
218. `})`
219. `return kwargs`
220. ``
221. `def get_success_url(self):`
222. `return reverse('frequently_list')`