Beispiel #1
0
def politician_statistic_view(request, politician_id):
    statistics = Statistic.get_statistics_by_politician(politician_id)

    category_list = [s.category.name for s in statistics]
    if request.GET.has_key('compare'):
        stats = get_cookie(request, 'statistics', {})
        value_list = {
            'politician' : [s.accordance for s in statistics],
            'citizen'    : [stats.get('category_%d' % s.category.id, 0) for s in statistics]
        }
    elif request.GET.has_key('evaluate'):
        value_list    = []
        category_list = []
        statistics    = get_cookie(request, 'statistics', {})
        for k, v in statistics.iteritems():
            category_id = int(re.sub('category_', '', k))
            value_list.append(Statistic.get_accordance(politician_id, category_id, (int(v)*10)))
            category_list.append(Category.objects.get(id=category_id).name)

    else:
        value_list = [s.accordance for s in statistics]

    response = {
        'categories' : category_list,
        'values'     : value_list
    }

    return JsonResponse(response)
Beispiel #2
0
def candidates_view(request):
    politician_list = (Politician.objects.filter(
        statistic__id__gt=0).distinct().order_by('first_name', 'last_name'))

    states = State.objects.all().order_by('name')
    categories = (Category.objects.filter(
        statistic__id__gt=0).order_by('name').distinct())

    category = request.GET.get('category', None)
    state = request.GET.get('state', None)
    search = request.GET.get('search', None)

    per_site = request.GET.get('per_page', 10)
    page = request.GET.get('page', 1)

    request.GET = request.GET.copy()
    stat_cookie = get_cookie(request, 'statistics', {})
    if 'evaluate' in request.GET and stat_cookie == {}:
        request.GET.pop('evaluate')

    if category and category != '0':
        if 'evaluate' in request.GET:
            stats = get_cookie(request, 'statistics', {})
            val = stats.get('category_%s' % category, 0)
        else:
            val = Question.objects.filter(category__id=category).aggregate(
                Sum('preferred_answer'))['preferred_answer__sum']

        politician_list = (Politician.get_politicians_by_category(
            category, (int(val) * 10)))

    if state and state != '0':
        politician_list = politician_list.filter(state=state)

    if search:
        politician_list = politician_list.filter(
            Q(last_name__icontains=search) | Q(first_name__icontains=search)
            | Q(state__name__icontains=search)
            | Q(party__name__icontains=search)
            | Q(party__shortname__icontains=search))

    paginator = Paginator(politician_list, per_site)

    try:
        politicians = paginator.page(page)
    except PageNotAnInteger:
        politicians = paginator.page(1)
    except EmptyPage:
        politicians = paginator.page(paginator.num_pages)

    # remove the page parameter from url
    if request.GET.get('page', None):
        request.GET.pop('page')

    return render(request, 'core/candidates/index.html', {
        'politicians': politicians,
        'categories': categories,
        'states': states,
    })
Beispiel #3
0
def compare_view(request):
    questions = Question.objects.all().order_by('question_number')
    data      = []

    session_answers    = get_cookie(request, 'answers',    {})
    session_statistics = get_cookie(request, 'statistics', {})

    if request.method == "POST":
        for question in questions:
            qid = 'question_%d' % question.id
            session_answers[qid] = request.POST.get(qid, 0)

        categories = Category.objects.all()

        for category in categories:
            cq = Question.objects.filter(category=category)
            values = []
            for question in cq:
                values.append(
                    abs(
                        question.preferred_answer -
                        int(session_answers.get(
                            'question_%d' % question.id, 0))
                    )
                )
            session_statistics['category_%d' % category.id] = (
                10 - sum(values) / float(len(cq)))

        request.COOKIES['answers'] = session_answers
        request.COOKIES['statistics'] = session_statistics
        messages.success(request, _('answers_saved_successfully_evaluate'))

    for question in questions:
        item = {
            'question' : question,
            'value'    : session_answers.get('question_%d' % question.id, 0)
        }
        data.append(item)

    if request.method == "GET":
        response = render(
            request,
            'core/compare/index.html',
            {
                'data' : data,
                'meta' : default_meta
            }
        )

    else:
        response = redirect('%s?evaluate=1' % reverse('candidates'))

    set_cookie(response, 'answers', session_answers, 30)
    set_cookie(response, 'statistics', session_statistics, 30)
    return response
Beispiel #4
0
def compare_view(request):
    questions = Question.objects.all().order_by('question_number')
    data      = []

    session_answers    = get_cookie(request, 'answers',    {})
    session_statistics = get_cookie(request, 'statistics', {})

    if request.POST:
        for question in questions:
            qid = 'question_%d' % question.id
            session_answers[qid] = request.POST.get(qid, 0)

        categories = Category.objects.all()

        for category in categories:
            cq = Question.objects.filter(category=category)
            values = []
            for question in cq:
                values.append(
                    abs(
                        question.preferred_answer -
                        int(session_answers.get(
                            'question_%d' % question.id, 0))
                    )
                )
            session_statistics['category_%d' % category.id] = (
                10 - sum(values) / float(len(cq)))

        request.COOKIES['answers'] = session_answers
        request.COOKIES['statistics'] = session_statistics
        messages.success(request, _('answers_saved_successfully_evaluate'))

    for question in questions:
        item = {
            'question' : question,
            'value'    : session_answers.get('question_%d' % question.id, 0)
        }
        data.append(item)

    response = render(
        request,
        'core/compare/index.html',
        {
            'data' : data
        }
    )

    set_cookie(response, 'answers', session_answers, 30)
    set_cookie(response, 'statistics', session_statistics, 30)

    return response
Beispiel #5
0
def politician_view(request, politician_id):
    politician = get_object_or_404(
        Politician.objects.filter(statistic__id__gt=0).distinct(),
        pk=politician_id)

    answers    = (
        Answer.objects.
        filter(politician=politician).
        order_by('question__question_number'))
    links      = (
        Link.objects.filter(politician=politician).
        order_by('type__name'))
    cookie     = get_cookie(request, 'answers', {})
    answer_obs = []

    for a in answers:
        answer_obs.append({
            'own_ans': cookie.get('question_%s' % a.question.id, None),
            'politician_ans': a
        })

    return render(
        request,
        'core/profile/index.html',
        {
            'politician' : politician,
            'answers'    : answer_obs,
            'links'      : links
        }
    )
Beispiel #6
0
def politician_view(request, politician_id):
    politician = get_object_or_404(
        Politician.objects.filter(statistic__id__gt=0).distinct(),
        pk=politician_id)

    answers    = (
        Answer.objects.
        filter(politician=politician).
        order_by('question__question_number'))
    links      = (
        Link.objects.filter(politician=politician))
    cookie     = get_cookie(request, 'answers', {})
    answer_obs = []

    for a in answers:
        answer_obs.append({
            'own_ans': cookie.get('question_%s' % a.question.id, None),
            'politician_ans': a
        })
    embed_url_reverse = reverse('politician_statistic_spider_embed', kwargs={'politician_id':politician_id})
    embed_url_absolute = request.build_absolute_uri(embed_url_reverse)
    return render(
        request,
        'core/profile/index.html',
        {
            'politician' : politician,
            'answers'    : answer_obs,
            'links'      : links,
            'embed_url'  : embed_url_absolute,
            'meta'       : default_meta
        }
    )
Beispiel #7
0
def politician_statistic_spider_view(request, politician_id):
    statistics = Statistic.get_statistics_by_politician(politician_id)
    stats = get_cookie(request, 'statistics', {})
    values = {
        'politician': [s.accordance for s in statistics],
        'citizen':
        [stats.get('category_%d' % s.category.id, 0) for s in statistics]
    }

    return JsonResponse({
        'categories': [s.category.name for s in statistics],
        'values': values
    })
Beispiel #8
0
def candidates_view(request):
    states = State.objects.all().order_by('sort', 'name')
    parties = Party.objects.all().order_by('name')
    categories = (Category.objects.filter(
        statistic__id__gt=0).order_by('name').distinct())

    category = request.GET.get('category', None)
    state = request.GET.get('state', None)
    search = request.GET.get('search', None)

    session_answers = get_cookie(request, 'answers', {})
    session_statistics = get_cookie(request, 'statistics', {})

    has_cookie = len(session_answers) > 0 and len(session_statistics) > 0

    context = {
        'categories': categories,
        'states': states,
        'parties': parties,
        'meta': default_meta,
        'has_cookie': has_cookie,
    }

    if has_cookie:
        query_params = {}

        for k, v in session_statistics.items():
            query_params['statistics_{0}'.format(k)] = v

        for k, v in session_answers.items():
            query_params['answers_{0}'.format(k)] = v

        formatted_query_params = urlencode(query_params)

        context['share_url'] = '{0}/share?{1}'.format(settings.BASE_URL,
                                                      formatted_query_params)

    return render(request, 'core/candidates/index.html', context)
Beispiel #9
0
def politician_statistic_spider_view(request, politician_id):
    statistics = Statistic.get_statistics_by_politician(politician_id)
    stats      = get_cookie(request, 'statistics', {})
    values     = {
        'politician' : [s.accordance for s in statistics],
        'citizen'    : [
            stats.get('category_%d' % s.category.id, 0)
            for s in statistics]
    }

    return JsonResponse({
        'categories': [
            s.category.name
            for s in statistics
        ],
        'values': values
    })
Beispiel #10
0
def politician_view(request, politician_id):
    politician = get_object_or_404(
        Politician.objects.filter(statistic__id__gt=0).distinct(),
        pk=politician_id)

    answers = (Answer.objects.filter(
        politician=politician).order_by('question__question_number'))
    links = (Link.objects.filter(politician=politician))
    cookie = get_cookie(request, 'answers', {})
    answer_obs = []

    for a in answers:
        answer_obs.append({
            'own_ans':
            cookie.get('question_%s' % a.question.id, None),
            'politician_ans':
            a
        })
    embed_url_reverse = reverse('politician_statistic_spider_embed',
                                kwargs={'politician_id': politician_id})
    embed_url_absolute = request.build_absolute_uri(embed_url_reverse)

    meta = Meta(
        title=u'{0} {1}'.format(politician.first_name, politician.last_name),
        image=get_thumbnailer(politician.image)['large'].url
        if politician.image else None,
        description=_("%(first_name)s %(last_name)s on Freedomvote") % {
            'first_name': politician.first_name,
            'last_name': politician.last_name
        },
        url=request.build_absolute_uri(
            reverse('politician', kwargs={'politician_id': politician.id})))

    return render(
        request, 'core/profile/index.html', {
            'politician': politician,
            'answers': answer_obs,
            'links': links,
            'embed_url': embed_url_absolute,
            'meta': meta,
            'base_url': settings.BASE_URL
        })
Beispiel #11
0
def politician_view(request, politician_id):
    politician = get_object_or_404(Politician, id=politician_id)
    answers    = Answer.objects.filter(politician=politician).order_by('question__question_number')
    links      = Link.objects.filter(politician=politician).order_by('type__name')
    cookie     = get_cookie(request, 'answers', {})
    answer_obs = []

    for a in answers:
        answer_obs.append({
            'own_ans': cookie.get('question_%s' % a.question.id, None),
            'politician_ans': a
        })

    return render(
        request,
        'core/profile/index.html',
        {
            'politician' : politician,
            'answers'    : answer_obs,
            'links'      : links
        }
    )
Beispiel #12
0
def politician_statistic_view(request, politician_id):
    category_id = int(request.GET.get('category', False))
    titles = [force_text(_('total'))]

    if category_id:
        category = get_object_or_404(Category, id=category_id)
        titles.append(category.name)

    if 'evaluate' in request.GET:
        cat_by_id = {cat.id: cat for cat in Category.objects.all()}

        pol_answers = Answer.objects.filter(politician_id=politician_id)
        pairs = []
        answers = get_cookie(request, 'answers', {})

        delta_by_cat = collections.defaultdict(lambda: [])
        for ans in pol_answers:
            voter_value = int(answers.get('question_%s' % ans.question_id, 0))
            delta = abs(ans.agreement_level - voter_value)
            delta_by_cat[ans.question.category_id].append(delta)

        for cid, cat in cat_by_id.items():
            if not len(delta_by_cat[cid]):
                continue

            pairs.append({
                'category':
                cat.name,
                'value':
                (10 - sum(delta_by_cat[cid]) / float(len(delta_by_cat[cid])))
            })

        sorted_pairs = sorted(pairs, key=lambda k: k['category'])

        detail = {
            'categories': [i['category'] for i in sorted_pairs],
            'values': [i['value'] for i in sorted_pairs]
        }

        total = sum(detail['values']) / len(detail['values'])
        pos = [total]
        neg = [(10 - total)]

        if category_id:
            val = 10 - (sum(delta_by_cat[category_id]) /
                        float(len(delta_by_cat[category_id])))
            pos.append(val)
            neg.append(10 - val)

        summary = {
            'titles': titles,
            'values': {
                'positive': pos,
                'negative': neg
            }
        }

    else:
        statistics = Statistic.get_statistics_by_politician(politician_id)
        values = [s.accordance for s in statistics]
        total = sum(values) / len(values)

        # pos is the green part (agreement level) of the graph,
        # neg is the "rest" (red)
        pos = [total]
        neg = [(10 - total)]

        if category_id:
            # if category_id is given, the graph should display this
            # category in addition to the summary view
            statistic = Statistic.objects.get(politician_id=politician_id,
                                              category=category)
            pos.append(statistic.value / 10)
            neg.append(10 - statistic.value / 10)

        summary = {
            'titles': titles,
            'values': {
                'positive': pos,
                'negative': neg
            }
        }

        detail = {
            'categories': [s.category.name for s in statistics],
            'values': values
        }

    return JsonResponse({'summary': summary, 'detail': detail})
Beispiel #13
0
def candidates_view(request):
    politician_list = (
        Politician.objects.
        filter(statistic__id__gt=0).distinct().
        order_by('first_name', 'last_name'))

    states          = State.objects.all().order_by('name')
    categories      = (
        Category.objects.filter(statistic__id__gt=0).
        order_by('name').distinct())

    category = request.GET.get('category', None)
    state    = request.GET.get('state', None)
    search   = request.GET.get('search', None)

    per_site = request.GET.get('per_page', 10)
    page     = request.GET.get('page',      1)

    request.GET = request.GET.copy()
    stat_cookie = get_cookie(request, 'statistics', {})
    if 'evaluate' in request.GET and stat_cookie == {}:
        request.GET.pop('evaluate')

    if category and category != '0':
        if 'evaluate' in request.GET:
            stats = get_cookie(request, 'statistics', {})
            val = stats.get('category_%s' % category, 0)
        else:
            val = Question.objects.filter(
                category__id=category
            ).aggregate(Sum('preferred_answer'))['preferred_answer__sum']

        politician_list = (
            Politician.get_politicians_by_category(
                category, (int(val) * 10)))

    if state and state != '0':
        politician_list = politician_list.filter(state=state)

    if search:
        politician_list = politician_list.filter(
            Q(last_name__icontains=search) |
            Q(first_name__icontains=search) |
            Q(state__name__icontains=search) |
            Q(party__name__icontains=search) |
            Q(party__shortname__icontains=search)
        )

    paginator = Paginator(politician_list, per_site)

    try:
        politicians = paginator.page(page)
    except PageNotAnInteger:
        politicians = paginator.page(1)
    except EmptyPage:
        politicians = paginator.page(paginator.num_pages)

    # remove the page parameter from url
    if request.GET.get('page', None):
        request.GET.pop('page')

    return render(
        request,
        'core/candidates/index.html',
        {
            'politicians' : politicians,
            'categories'  : categories,
            'states'      : states,
        }
    )
Beispiel #14
0
def politician_statistic_view(request, politician_id):
    category_id = int(request.GET.get('category', False))
    titles  = [force_unicode(_('total'))]

    if category_id:
        category = get_object_or_404(Category, id=category_id)
        titles.append(category.name)

    if 'evaluate' in request.GET:
        cat_by_id = {
            cat.id: cat
            for cat
            in Category.objects.all()
        }

        pol_answers = Answer.objects.filter(politician_id=politician_id)
        pairs = []
        answers    = get_cookie(request, 'answers',    {})

        delta_by_cat = collections.defaultdict(lambda: [])
        for ans in pol_answers:
            voter_value = int(answers.get('question_%s' % ans.question_id, 0))
            delta       = abs(ans.agreement_level - voter_value)
            delta_by_cat[ans.question.category_id].append(delta)

        for cid, cat in cat_by_id.iteritems():
            pairs.append({
                'category': cat.name,
                'value':    (
                    10 - sum(delta_by_cat[cid]) /
                    float(len(delta_by_cat[cid]))
                )
            })

        sorted_pairs = sorted(pairs, key=lambda k: k['category'])

        detail = {
            'categories' : [i['category'] for i in sorted_pairs],
            'values'     : [i['value']    for i in sorted_pairs]
        }

        total = sum(detail['values']) / len(detail['values'])
        pos     = [total]
        neg     = [(10 - total)]

        if category_id:
            val = 10 - (
                sum(delta_by_cat[category_id]) /
                float(len(delta_by_cat[category_id])))
            pos.append(val)
            neg.append(10 - val)

        summary = {
            'titles' : titles,
            'values' : {
                'positive' : pos,
                'negative' : neg
            }
        }

    else:
        statistics = Statistic.get_statistics_by_politician(politician_id)
        values  = [s.accordance for s in statistics]
        total   = sum(values) / len(values)

        # pos is the green part (agreement level) of the graph,
        # neg is the "rest" (red)
        pos     = [total]
        neg     = [(10 - total)]

        if category_id:
            # if category_id is given, the graph should display this
            # category in addition to the summary view
            statistic = Statistic.objects.get(
                politician_id=politician_id, category=category)
            pos.append(statistic.value / 10)
            neg.append(10 - statistic.value / 10)

        summary = {
            'titles' : titles,
            'values' : {
                'positive' : pos,
                'negative' : neg
            }
        }

        detail  = {
            'categories' : [s.category.name for s in statistics],
            'values'     : values
        }

    return JsonResponse({'summary': summary, 'detail': detail})