home.py 1.75 KB
Newer Older
Nicolas Joyard's avatar
Nicolas Joyard committed
1 2
# coding: utf-8

Nicolas Joyard's avatar
Nicolas Joyard committed
3 4 5
import datetime
import random

Nicolas Joyard's avatar
Nicolas Joyard committed
6
from django.db.models import Q, Count
Nicolas Joyard's avatar
Nicolas Joyard committed
7 8
from django.views import generic

Nicolas Joyard's avatar
Nicolas Joyard committed
9
from representatives.models import Representative
Nicolas Joyard's avatar
Nicolas Joyard committed
10
from representatives_positions.views import PositionFormMixin
11
from representatives_votes.models import Proposal
Nicolas Joyard's avatar
Nicolas Joyard committed
12

13
from memopol_settings.models import Setting
Nicolas Joyard's avatar
Nicolas Joyard committed
14 15
from memopol_themes.models import Theme

Nicolas Joyard's avatar
Nicolas Joyard committed
16 17
from .representative_mixin import RepresentativeViewMixin

Nicolas Joyard's avatar
Nicolas Joyard committed
18

Nicolas Joyard's avatar
Nicolas Joyard committed
19 20
class HomeView(PositionFormMixin, RepresentativeViewMixin,
               generic.TemplateView):
Nicolas Joyard's avatar
Nicolas Joyard committed
21
    template_name = 'home.html'
Nicolas Joyard's avatar
Nicolas Joyard committed
22 23 24 25

    def get_context_data(self, **kwargs):
        c = super(HomeView, self).get_context_data(**kwargs)

Nicolas Joyard's avatar
Nicolas Joyard committed
26 27
        # Today's mep

Nicolas Joyard's avatar
Nicolas Joyard committed
28 29 30 31 32 33 34 35 36 37 38
        qs = Representative.objects
        qs = qs.filter(Q(representative_score__score__lt=0) |
                       Q(representative_score__score__gt=0))
        qs = self.prefetch_for_representative_country_and_main_mandate(qs)

        random.seed(datetime.date.today().isoformat())
        index = random.randint(0, qs.count() - 1)
        c['todays_mep'] = qs.all()[index]

        self.add_representative_country_and_main_mandate(c['todays_mep'])

Nicolas Joyard's avatar
Nicolas Joyard committed
39 40 41 42 43 44 45 46 47 48 49
        # Featured themes

        c['featured_themes'] = Theme.objects \
            .filter(featured=True) \
            .annotate(
                nb_links=Count('links', distinct=True),
                nb_dossiers=Count('dossiers', distinct=True),
                nb_proposals=Count('proposals', distinct=True),
                nb_positions=Count('positions', distinct=True)
            )

50 51 52 53 54 55 56
        # Last votes

        num = int(Setting.objects.get(pk='HOMEPAGE_LATEST_VOTES').value)
        c['latest_votes'] = Proposal.objects \
            .filter(recommendation__isnull=False) \
            .order_by('-datetime')[0:num]

Nicolas Joyard's avatar
Nicolas Joyard committed
57
        return c