<commit_before>from django.db.models import Q
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.models import User
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.forms.models import inlineformset_factory
from django.shortcuts import get_object_or_404, redirect, render
from django.utils.timezone import now as now_utc

from django_statsd.clients import statsd

import forms

from remo.base.decorators import permission_check
from remo.base.utils import datetime2pdt, get_or_create_instance
from remo.voting.models import Poll, PollComment, RadioPoll, RangePoll, Vote


@permission_check()
def list_votings(request):
    """List votings view."""
    user = request.user
    polls = Poll.objects.all()
    if not user.groups.filter(name='Admin').exists():
        polls = Poll.objects.filter(valid_groups__in=user.groups.all())

    past_polls_query = polls.filter(end__lt=now_utc())
    current_polls = polls.filter(start__lt=now_utc(), end__gt=now_utc())
    future_polls = polls.filter(start__gt=now_utc())

    past_polls_paginator = Paginator(past_polls_query, settings.ITEMS_PER_PAGE)
    past_polls_page = request.GET.get('page', 1)

    try:
        past_polls = past_polls_paginator.page(past_polls_page)
    except PageNotAnInteger:
        past_polls = past_polls_paginator.page(1)
    except EmptyPage:
        past_polls = past_polls_paginator.page(past_polls_paginator.num_pages)

    return render(request, 'list_votings.html',
                  {'user': user,
                   'past_polls': past_polls,
                   'current_polls': current_polls,
                   'future_polls': future_polls})


@permission_check(permissions=['voting.add_poll', 'voting.change_poll'])
def edit_voting(request, slug=None):
    """Create/Edit voting view."""
    poll, created = get_or_create_instance(Poll, slug=slug)

    can_delete_voting = False
    extra = 0
    current_voting_edit = False
    range_poll_formset = None
    radio_poll_formset = None
    if created:
        poll.created_by = request.user
        extra = 1
    else:
        if (RangePoll.objects.filter(poll=poll).count() or
                RadioPoll.objects.filter(poll=poll).count()) == 0:
            extra = 1
        can_delete_voting = True
        date_now = datetime2pdt()
        if poll.start < date_now and poll.end > date_now:
            current_voting_edit = True

    nominee_list = User.objects.filter(
        groups__name='Rep', userprofile__registration_complete=True)
    if current_voting_edit:
        poll_form = forms.PollEditForm(request.POST or None, instance=poll)
    else:
        RangePollFormset = (inlineformset_factory(Poll, RangePoll,
                            formset=forms.BaseRangePollInlineFormSet,
                            extra=extra, can_delete=True))
        RadioPollFormset = (inlineformset_factory(Poll, RadioPoll,
                            formset=forms.BaseRadioPollInlineFormSet,
                            extra=extra, can_delete=True))

        range_poll_formset = RangePollFormset(request.POST or None,
                                              instance=poll,
                                              user_list=nominee_list)
        radio_poll_formset = RadioPollFormset(request.POST or None,
                                              instance=poll)
        poll_form = forms.PollAddForm(request.POST or None, instance=poll,
                                      radio_poll_formset=radio_poll_formset,
                                      range_poll_formset=range_poll_formset)

    if poll_form.is_valid():
        poll_form.save()

        if created:
            messages.success(request, 'Voting successfully created.')
            statsd.incr('voting.create_voting')
        else:
            messages.success(request, 'Voting successfully edited.')
            statsd.incr('voting.edit_voting')

        if not current_voting_edit:
            statsd.incr('voting.create_range_poll',
                        poll_form.radio_poll_formset.total_form_count())
            statsd.incr('voting.create_radio_poll',
                        poll_form.range_poll_formset.total_form_count())<commit_msg>[Fix bug 899090] Add extra range/radio polls when no initial available.<commit_after>from django.db.models import Q
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.models import User
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.forms.models import inlineformset_factory
from django.shortcuts import get_object_or_404, redirect, render
from django.utils.timezone import now as now_utc

from django_statsd.clients import statsd

import forms

from remo.base.decorators import permission_check
from remo.base.utils import datetime2pdt, get_or_create_instance
from remo.voting.models import Poll, PollComment, RadioPoll, RangePoll, Vote


@permission_check()
def list_votings(request):
    """List votings view."""
    user = request.user
    polls = Poll.objects.all()
    if not user.groups.filter(name='Admin').exists():
        polls = Poll.objects.filter(valid_groups__in=user.groups.all())

    past_polls_query = polls.filter(end__lt=now_utc())
    current_polls = polls.filter(start__lt=now_utc(), end__gt=now_utc())
    future_polls = polls.filter(start__gt=now_utc())

    past_polls_paginator = Paginator(past_polls_query, settings.ITEMS_PER_PAGE)
    past_polls_page = request.GET.get('page', 1)

    try:
        past_polls = past_polls_paginator.page(past_polls_page)
    except PageNotAnInteger:
        past_polls = past_polls_paginator.page(1)
    except EmptyPage:
        past_polls = past_polls_paginator.page(past_polls_paginator.num_pages)

    return render(request, 'list_votings.html',
                  {'user': user,
                   'past_polls': past_polls,
                   'current_polls': current_polls,
                   'future_polls': future_polls})


@permission_check(permissions=['voting.add_poll', 'voting.change_poll'])
def edit_voting(request, slug=None):
    """Create/Edit voting view."""
    poll, created = get_or_create_instance(Poll, slug=slug)

    can_delete_voting = False
    extra_range_polls = 0
    extra_radio_polls = 0
    current_voting_edit = False
    range_poll_formset = None
    radio_poll_formset = None

    if created:
        poll.created_by = request.user
        extra_range_polls = 1
        extra_radio_polls = 1
    else:
        if not poll.range_polls.exists():
            extra_range_polls = 1
        if not poll.radio_polls.exists():
            extra_radio_polls = 1
        can_delete_voting = True
        date_now = datetime2pdt()
        if poll.start < date_now and poll.end > date_now:
            current_voting_edit = True

    nominee_list = User.objects.filter(
        groups__name='Rep', userprofile__registration_complete=True)
    if current_voting_edit:
        poll_form = forms.PollEditForm(request.POST or None, instance=poll)
    else:
        RangePollFormset = (inlineformset_factory(Poll, RangePoll,
                            formset=forms.BaseRangePollInlineFormSet,
                            extra=extra_range_polls, can_delete=True))
        RadioPollFormset = (inlineformset_factory(Poll, RadioPoll,
                            formset=forms.BaseRadioPollInlineFormSet,
                            extra=extra_radio_polls, can_delete=True))

        range_poll_formset = RangePollFormset(request.POST or None,
                                              instance=poll,
                                              user_list=nominee_list)
        radio_poll_formset = RadioPollFormset(request.POST or None,
                                              instance=poll)
        poll_form = forms.PollAddForm(request.POST or None, instance=poll,
                                      radio_poll_formset=radio_poll_formset,
                                      range_poll_formset=range_poll_formset)

    if poll_form.is_valid():
        poll_form.save()

        if created:
            messages.success(request, 'Voting successfully created.')
            statsd.incr('voting.create_voting')
        else:
            messages.success(request, 'Voting successfully edited.')
            statsd.incr('voting.edit_voting')

        if not current_voting_edit:
            statsd.incr('voting.create_range_poll',
                        poll_form.radio_poll_formset.total_form_count())
            statsd.incr('voting.create_radio_poll',
                        poll_form.range_poll_formset.total_form_count())
{'fraction_non_alphanumeric': 0.08172242157657136, 'fraction_numerical': 0.0034726241463132307, 'mean_word_length': 2.5717238528317488, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 16, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7446351', 'n_tokens_mistral': 2615, 'n_tokens_neox': 2520, 'n_words': 464}