views.py 2.53 KB
Newer Older
1
2
3
from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q
luxcem's avatar
luxcem committed
4

5
from representatives.models import Representative
luxcem's avatar
luxcem committed
6
7


8
def index(request):
9
10
11
12
    representative_list = _filter_by_search(
        request,
        Representative.objects.all()
    )
luxcem's avatar
luxcem committed
13

14
    return _render_list(request, representative_list)
15
16


17
18
19
20
def by_mandate(request, mandate_kind, mandate_abbr=None, mandate_name=None):
    representative_list = Representative.objects.filter(
        mandate__group__kind=mandate_kind,
        mandate__active=True
21
    )
22
23
24
25
26
27
28
29
30
31
    if mandate_abbr:
        representative_list = representative_list.filter(
            mandate__group__abbreviation=mandate_abbr,
            mandate__active=True
        )
    if mandate_name:
        representative_list = representative_list.filter(
            Q(mandate__group__name__icontains=mandate_name),
            mandate__active=True
        )
32

33
34
35
36
    # Select distinct representatives and filter by search
    representative_list = list(set(
        _filter_by_search(request, representative_list)
    ))
37

38
39
40
41
42
43
44
45
46
47
48
49
50
    return _render_list(request, representative_list)


def _filter_by_search(request, representative_list):
    """
    Return a representative_list filtered by
    the representative name provided in search form
    """
    search = request.GET.get('search')
    if search:
        return representative_list.filter(
            Q(full_name__icontains=search)
        )
51
    else:
52
        return representative_list
53

54
55
56
57
58
59

def _render_list(request, representative_list, num_by_page=50):
    """
    Render a paginated list of representatives
    """
    paginator = Paginator(representative_list, num_by_page)
60
61
62
63
64
65
66
67
    page = request.GET.get('page')
    try:
        representatives = paginator.page(page)
    except PageNotAnInteger:
        representatives = paginator.page(1)
    except EmptyPage:
        representatives = paginator.page(paginator.num_pages)

68
69
70
71
72
73
    context = {}
    queries_without_page = request.GET.copy()
    if 'page' in queries_without_page:
        del queries_without_page['page']
    context['queries'] = queries_without_page

74
    context['representatives'] = representatives
75
    context['representative_num'] = paginator.count
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
    return render(
        request,
        'memopol_representatives/list.html',
        context
    )


def view(request, num):
    representative = get_object_or_404(Representative, pk=num)

    return render(
        request,
        'memopol_representatives/view.html',
        {'representative': representative}
    )