fix
[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     model = models.Visits
10     permission_required = 'stats.view_visits'
11     template_name = 'stats/top.html'
12
13     def get_context_data(self, **kwargs):
14         ctx = super().get_context_data(**kwargs)
15         form = forms.VisitsForm(self.request.GET)
16         assert form.is_valid()
17         visits = self.model.objects.all()
18         if form.cleaned_data['date_since']:
19             visits = visits.filter(date__gte=form.cleaned_data['date_since'].replace(day=1))
20         if form.cleaned_data['date_until']:
21             visits = visits.filter(date__lte=form.cleaned_data['date_until'])
22         visits = visits.values('book__slug').annotate(
23             views=Sum('views'),
24             unique_views=Sum('unique_views')
25         )
26         visits = visits.order_by('-unique_views')
27         ctx['form'] = form
28         ctx['visits'] = visits
29         return ctx
30
31
32 class DailyTopView(TopView):
33     model = models.DayVisits