One cover more in the box.
[wolnelektury.git] / src / stats / views.py
1 from django.contrib.auth.mixins import PermissionRequiredMixin
2 from django.views.generic import TemplateView
3 from django.db.models import Sum
4 from . import forms
5 from . import models
6
7
8 class TopView(PermissionRequiredMixin, TemplateView):
9     permission_required = 'stats.view_visits'
10     template_name = 'stats/top.html'
11
12     def get_context_data(self, **kwargs):
13         ctx = super().get_context_data(**kwargs)
14         form = forms.VisitsForm(self.request.GET)
15         assert form.is_valid()
16         visits = models.Visits.objects.all()
17         if form.cleaned_data['date_since']:
18             visits = visits.filter(date__gte=form.cleaned_data['date_since'].replace(day=1))
19         if form.cleaned_data['date_until']:
20             visits = visits.filter(date__lte=form.cleaned_data['date_until'])
21         visits = visits.values('book__slug').annotate(
22             views=Sum('views'),
23             unique_views=Sum('unique_views')
24         )
25         visits = visits.order_by('-unique_views')
26         ctx['form'] = form
27         ctx['visits'] = visits
28         return ctx
29