Exemplo n.º 1
0
def check_update_allowed(user, api, old_popit_data, new_popit_data):
    if settings.RESTRICT_RENAMES:
        allowed_by_group = user_in_group(user, TRUSTED_TO_RENAME_GROUP_NAME)
        name_the_same = old_popit_data['name'] == new_popit_data['name']
        if not (allowed_by_group or name_the_same):
            message = _("Name change from '{0}' to '{1}' by user {2} disallowed")
            raise NameChangeDisallowedException(message.format(
                old_popit_data['name'], new_popit_data['name'], user.username
            ))
    for election in Election.objects.all():
        old_allowed = get_constituency_lock_from_person_data(user, api, election.slug, old_popit_data)[1]
        new_allowed = get_constituency_lock_from_person_data(user, api, election.slug, new_popit_data)[1]
        for (field, key) in [
                ('standing_in', 'post_id'),
                ('party_memberships', 'id')
        ]:
            old_field_value = old_popit_data.get(field, {}) or {}
            new_field_value = new_popit_data.get(field, {}) or {}
            old_post_id = (old_field_value.get(election.slug, {}) or {}).get(key)
            new_post_id = (new_field_value.get(election.slug, {}) or {}).get(key)
            if not (old_allowed and new_allowed) and (old_post_id != new_post_id):
                raise ChangeToLockedConstituencyDisallowedException(
                    _("That update isn't allowed because candidates for a locked "
                    "post would be changed")
                )
Exemplo n.º 2
0
    def get_context_data(self, **kwargs):
        context = super(UpdatePersonView, self).get_context_data(**kwargs)

        person = PopItPerson.create_from_popit(self.api,
                                               self.kwargs['person_id'])
        context['person'] = person

        context['user_can_merge'] = user_in_group(self.request.user,
                                                  TRUSTED_TO_MERGE_GROUP_NAME)

        context['versions'] = get_version_diffs(person.versions)

        context['constituencies_form_fields'] = []
        for election, election_data in settings.ELECTIONS_BY_DATE:
            if not election_data.get('current'):
                continue
            context['constituencies_form_fields'].append({
                'election_name':
                election_data['name'],
                'standing':
                kwargs['form']['standing_' + election],
                'constituency':
                kwargs['form']['constituency_' + election],
                'party_fields': [
                    kwargs['form']['party_' + p['slug'] + '_' + election]
                    for p in PARTY_DATA.ALL_PARTY_SETS
                ]
            })

        return context
Exemplo n.º 3
0
def check_update_allowed(user, api, old_popit_data, new_popit_data):
    if settings.RESTRICT_RENAMES:
        allowed_by_group = user_in_group(user, TRUSTED_TO_RENAME_GROUP_NAME)
        name_the_same = old_popit_data['name'] == new_popit_data['name']
        if not (allowed_by_group or name_the_same):
            message = _(
                "Name change from '{0}' to '{1}' by user {2} disallowed")
            raise NameChangeDisallowedException(
                message.format(old_popit_data['name'], new_popit_data['name'],
                               user.username))
    for election in settings.ELECTIONS:
        old_allowed = get_constituency_lock_from_person_data(
            user, api, election, old_popit_data)[1]
        new_allowed = get_constituency_lock_from_person_data(
            user, api, election, new_popit_data)[1]
        for (field, key) in [('standing_in', 'post_id'),
                             ('party_memberships', 'id')]:
            old_field_value = old_popit_data.get(field, {}) or {}
            new_field_value = new_popit_data.get(field, {}) or {}
            old_post_id = (old_field_value.get(election, {}) or {}).get(key)
            new_post_id = (new_field_value.get(election, {}) or {}).get(key)
            if not (old_allowed
                    and new_allowed) and (old_post_id != new_post_id):
                raise ChangeToLockedConstituencyDisallowedException(
                    _("That update isn't allowed because candidates for a locked "
                      "post would be changed"))
Exemplo n.º 4
0
    def get_context_data(self, **kwargs):
        context = super(UpdatePersonView, self).get_context_data(**kwargs)

        person = get_object_or_404(Person.objects.select_related("extra"), pk=self.kwargs["person_id"])
        context["person"] = person

        context["user_can_merge"] = user_in_group(self.request.user, TRUSTED_TO_MERGE_GROUP_NAME)

        context["versions"] = get_version_diffs(json.loads(person.extra.versions))

        context["constituencies_form_fields"] = []
        for election_data in Election.objects.by_date():
            if not election_data.current:
                continue
            cons_form_fields = {
                "election_name": election_data.name,
                "standing": kwargs["form"]["standing_" + election_data.slug],
                "constituency": kwargs["form"]["constituency_" + election_data.slug],
            }
            party_fields = []
            for ps in PartySet.objects.all():
                key_suffix = ps.slug + "_" + election_data.slug
                position_field = None
                if election_data.party_lists_in_use:
                    position_field = kwargs["form"]["party_list_position_" + key_suffix]
                party_position_tuple = (kwargs["form"]["party_" + key_suffix], position_field)
                party_fields.append(party_position_tuple)
            cons_form_fields["party_fields"] = party_fields
            context["constituencies_form_fields"].append(cons_form_fields)

        return context
Exemplo n.º 5
0
    def get_context_data(self, **kwargs):
        context = super(UpdatePersonView, self).get_context_data(**kwargs)

        person = get_object_or_404(
            Person.objects.select_related('extra'),
            pk=self.kwargs['person_id']
        )
        context['person'] = person

        context['user_can_merge'] = user_in_group(
            self.request.user,
            TRUSTED_TO_MERGE_GROUP_NAME
        )

        context['versions'] = get_version_diffs(
            json.loads(person.extra.versions)
        )

        context = get_person_form_fields(context, kwargs['form'])

        if 'highlight_field' in self.request.GET:
            context['couldnt_find_field_form'] = PersonTaskForm(
                instance=person, data={
                    'task_field': self.request.GET['highlight_field'],
                    'person': person.pk,
                })


        return context
Exemplo n.º 6
0
    def test_func(self, user):
        in_group = user_in_group(self.request.user,
                                 "Trusted to confirm control results")
        results_feature_active = getattr(settings, 'RESULTS_FEATURE_ACTIVE',
                                         False)

        return any((in_group, results_feature_active))
Exemplo n.º 7
0
    def get_context_data(self, **kwargs):
        context = super(UpdatePersonView, self).get_context_data(**kwargs)

        person = get_object_or_404(
            Person.objects.select_related('extra'),
            pk=self.kwargs['person_id']
        )
        context['person'] = person

        context['user_can_merge'] = user_in_group(
            self.request.user,
            TRUSTED_TO_MERGE_GROUP_NAME
        )

        context['versions'] = get_version_diffs(
            json.loads(person.extra.versions)
        )

        context = get_person_form_fields(context, kwargs['form'])

        if 'highlight_field' in self.request.GET:
            context['couldnt_find_field_form'] = PersonTaskForm(
                instance=person, data={
                    'task_field': self.request.GET['highlight_field'],
                    'person': person.pk,
                })

        return context
Exemplo n.º 8
0
    def get_context_data(self, **kwargs):
        context = super(UpdatePersonView, self).get_context_data(**kwargs)

        person = PopItPerson.create_from_popit(
            self.api,
            self.kwargs['person_id']
        )
        context['person'] = person

        context['user_can_merge'] = user_in_group(
            self.request.user,
            TRUSTED_TO_MERGE_GROUP_NAME
        )

        context['versions'] = get_version_diffs(person.versions)

        context['constituencies_form_fields'] = []
        for election, election_data in settings.ELECTIONS_BY_DATE:
            if not election_data.get('current'):
                continue
            context['constituencies_form_fields'].append(
                {
                    'election_name': election_data['name'],
                    'standing': kwargs['form']['standing_' + election],
                    'constituency': kwargs['form']['constituency_' + election],
                    'party_fields': [
                        kwargs['form']['party_' + p['slug'] + '_' + election]
                        for p in PARTY_DATA.ALL_PARTY_SETS
                    ]
                }
            )

        return context
Exemplo n.º 9
0
def raise_if_locked(request, post):
    # If you're a user who's trusted to toggle the constituency lock,
    # they're allowed to edit candidacy:
    if user_in_group(request.user, TRUSTED_TO_LOCK_GROUP_NAME):
        return
    # Otherwise, if the constituency is locked, raise an exception:
    if post.extra.candidates_locked:
        raise Exception(_("Attempt to edit a candidacy in a locked constituency"))
Exemplo n.º 10
0
def raise_if_locked(request, post, election):
    # If you're a user who's trusted to toggle the constituency lock,
    # they're allowed to edit candidacy:
    if user_in_group(request.user, TRUSTED_TO_LOCK_GROUP_NAME):
        return
    # Otherwise, if the constituency is locked, raise an exception:
    if post.ballot_set.get(election=election).candidates_locked:
        raise Exception("Attempt to edit a candidacy in a locked constituency")
Exemplo n.º 11
0
def raise_if_locked(api, request, post_id):
    # If you're a user who's trusted to toggle the constituency lock,
    # they're allowed to edit candidacy:
    if user_in_group(request.user, TRUSTED_TO_LOCK_GROUP_NAME):
        return
    # Otherwise, if the constituency is locked, raise an exception:
    data = api.posts(post_id).get(embed='')
    if data.get('candidates_locked'):
        raise Exception(_("Attempt to edit a candidacy in a locked constituency"))
Exemplo n.º 12
0
def raise_if_locked(api, request, post_id):
    # If you're a user who's trusted to toggle the constituency lock,
    # they're allowed to edit candidacy:
    if user_in_group(request.user, TRUSTED_TO_LOCK_GROUP_NAME):
        return
    # Otherwise, if the constituency is locked, raise an exception:
    data = api.posts(post_id).get(embed='')
    if data.get('candidates_locked'):
        raise Exception("Attempt to edit a candidacy in a locked constituency")
Exemplo n.º 13
0
    def test_func(self, user):
        in_group = user_in_group(self.request.user,
            "Trusted to confirm control results")
        results_feature_active = getattr(
            settings, 'RESULTS_FEATURE_ACTIVE', False)

        return any(
                (in_group, results_feature_active)
            )
def show_results_feature(request):
    in_group = user_in_group(request.user,
        "Trusted to confirm control results")
    results_feature_active = getattr(settings, 'RESULTS_FEATURE_ACTIVE', False)

    return {
        'show_results_feature': any(
            (in_group, results_feature_active)
        ),
    }
def add_group_permissions(request):
    """Add user_can_merge and user_can_review_photos"""

    return {
        context_variable: user_in_group(request.user, group_name)
        for context_variable, group_name in (
            ('user_can_upload_documents', DOCUMENT_UPLOADERS_GROUP_NAME),
            ('user_can_merge', TRUSTED_TO_MERGE_GROUP_NAME),
            ('user_can_review_photos', PHOTO_REVIEWERS_GROUP_NAME),
            ('user_can_lock', TRUSTED_TO_LOCK_GROUP_NAME),
        )
    }
Exemplo n.º 16
0
    def get_constituency_lock(self, post_id):
        """Return whether the constituency is locked and whether this user can edit"""

        if not post_id:
            return False, True
        # Use the cached version because it'll be faster than going to
        # PopIt, even if it brings in embeds that we don't need:
        post_data = get_post_cached(self.api, post_id)['result']
        candidates_locked = bool(post_data.get('candidates_locked'))
        edits_allowed = (
            user_in_group(self.request.user, TRUSTED_TO_LOCK_GROUP_NAME) or
            not candidates_locked
        )
        return candidates_locked, edits_allowed
Exemplo n.º 17
0
    def get_context_data(self, **kwargs):

        context = super().get_context_data(**kwargs)

        person = get_object_or_404(Person, pk=self.kwargs["person_id"])
        context["person"] = person

        context["user_can_merge"] = user_in_group(self.request.user,
                                                  TRUSTED_TO_MERGE_GROUP_NAME)

        context["versions"] = get_version_diffs(json.loads(person.versions))

        context = get_person_form_fields(context, context["form"])

        return context
Exemplo n.º 18
0
def add_group_permissions(request):
    """Add user_can_merge and user_can_review_photos"""

    result = {
        context_variable: user_in_group(request.user, group_name)
        for context_variable, group_name in (
            ('user_can_upload_documents', DOCUMENT_UPLOADERS_GROUP_NAME),
            ('user_can_merge', TRUSTED_TO_MERGE_GROUP_NAME),
            ('user_can_review_photos', PHOTO_REVIEWERS_GROUP_NAME),
            ('user_can_lock', TRUSTED_TO_LOCK_GROUP_NAME),
            ('user_can_rename', TRUSTED_TO_RENAME_GROUP_NAME),
            ('user_can_record_results', RESULT_RECORDERS_GROUP_NAME),
        )
    }
    result['user_can_edit'] = settings.EDITS_ALLOWED or request.user.is_staff
    return result
Exemplo n.º 19
0
def check_update_allowed(user, old_name, new_name):
    # Check whether an unauthorized user has tried to rename someone
    # while RESTRICT_RENAMES is set:
    if settings.RESTRICT_RENAMES:
        allowed_by_group = user_in_group(user, TRUSTED_TO_RENAME_GROUP_NAME)
        name_the_same = old_name == new_name
        if not (allowed_by_group or name_the_same):
            message = _("Name change from '{0}' to '{1}' by user {2} disallowed")
            raise NameChangeDisallowedException(message.format(
                old_name, new_name, user.username
            ))
    
    # TODO: Check if Posts are Locked
    # old_memberships and new_memberships

    '''
Exemplo n.º 20
0
    def get_context_data(self, **kwargs):
        context = super(UpdatePersonView, self).get_context_data(**kwargs)

        person = get_object_or_404(Person.objects.select_related('extra'),
                                   pk=self.kwargs['person_id'])
        context['person'] = person

        context['user_can_merge'] = user_in_group(self.request.user,
                                                  TRUSTED_TO_MERGE_GROUP_NAME)

        context['versions'] = get_version_diffs(
            json.loads(person.extra.versions))

        context = get_person_form_fields(context, kwargs['form'])

        return context
Exemplo n.º 21
0
def add_group_permissions(request):
    """Add user_can_merge and user_can_review_photos"""

    result = {
        context_variable: user_in_group(request.user, group_name)
        for context_variable, group_name in (
            ('user_can_upload_documents', DOCUMENT_UPLOADERS_GROUP_NAME),
            ('user_can_merge', TRUSTED_TO_MERGE_GROUP_NAME),
            ('user_can_review_photos', PHOTO_REVIEWERS_GROUP_NAME),
            ('user_can_lock', TRUSTED_TO_LOCK_GROUP_NAME),
            ('user_can_rename', TRUSTED_TO_RENAME_GROUP_NAME),
            ('user_can_record_results', RESULT_RECORDERS_GROUP_NAME),
        )
    }
    result['user_can_edit'] = settings.EDITS_ALLOWED or request.user.is_staff
    return result
Exemplo n.º 22
0
    def get_context_data(self, **kwargs):
        context = super(UpdatePersonView, self).get_context_data(**kwargs)

        person = get_object_or_404(
            Person.objects.select_related('extra'),
            pk=self.kwargs['person_id']
        )
        context['person'] = person

        context['user_can_merge'] = user_in_group(
            self.request.user,
            TRUSTED_TO_MERGE_GROUP_NAME
        )

        context['versions'] = get_version_diffs(
            json.loads(person.extra.versions)
        )

        context['extra_fields'] = get_extra_fields(person)
        for k, v in context['extra_fields'].items():
            v['form_field'] = kwargs['form'][k]

        context['constituencies_form_fields'] = []
        for election_data in Election.objects.by_date():
            if not election_data.current:
                continue
            cons_form_fields = {
                'election_name': election_data.name,
                'standing': kwargs['form']['standing_' + election_data.slug],
                'constituency': kwargs['form']['constituency_' + election_data.slug],
            }
            party_fields = []
            for ps in PartySet.objects.all():
                key_suffix = ps.slug + '_' + election_data.slug
                position_field = None
                if election_data.party_lists_in_use:
                    position_field = kwargs['form']['party_list_position_' + key_suffix]
                party_position_tuple = (
                    kwargs['form']['party_' + key_suffix],
                    position_field
                )
                party_fields.append(party_position_tuple)
            cons_form_fields['party_fields'] = party_fields
            context['constituencies_form_fields'].append(cons_form_fields)

        return context
Exemplo n.º 23
0
def check_update_allowed(
    user, old_name, old_candidacies, new_name, new_candidacies
):
    # Check whether an unauthorized user has tried to rename someone
    # while RESTRICT_RENAMES is set:
    if settings.RESTRICT_RENAMES:
        allowed_by_group = user_in_group(user, TRUSTED_TO_RENAME_GROUP_NAME)
        name_the_same = old_name == new_name
        if not (allowed_by_group or name_the_same):
            message = "Name change from '{0}' to '{1}' by user {2} disallowed"
            raise NameChangeDisallowedException(
                message.format(old_name, new_name, user.username)
            )
    # Check that none of the posts that the person's leaving or
    # joining were locked:
    old_posts = {(c.post, c.ballot.election) for c in old_candidacies}
    new_posts = {(c.post, c.ballot.election) for c in new_candidacies}
    for post, election in old_posts ^ new_posts:
        dummy, edits_allowed = get_constituency_lock(user, post, election)
        if not edits_allowed:
            raise ChangeToLockedConstituencyDisallowedException(
                (
                    "That update isn't allowed because candidates for a locked "
                    "post ({post_label}) would be changed"
                ).format(post_label=post.label)
            )
    # Now check that they're not changing party in a locked
    # constituency:
    for post, election in old_posts & new_posts:
        old_party = next(c.party for c in old_candidacies if c.post == post)
        new_party = next(c.party for c in new_candidacies if c.post == post)
        dummy, edits_allowed = get_constituency_lock(user, post, election)
        if not edits_allowed and (old_party != new_party):
            raise ChangeToLockedConstituencyDisallowedException(
                (
                    "That update isn't allowed because you can't change the party "
                    "(in this case from {old_party} to {new_party}) for a candidate "
                    "in a locked post ({post_label})"
                ).format(
                    old_party=old_party.name,
                    new_party=new_party.name,
                    post_label=post.label,
                )
            )
Exemplo n.º 24
0
    def get_context_data(self, **kwargs):
        context = super(UpdatePersonView, self).get_context_data(**kwargs)

        person = get_object_or_404(
            Person.objects.select_related('extra'),
            pk=self.kwargs['person_id']
        )
        context['person'] = person

        context['user_can_merge'] = user_in_group(
            self.request.user,
            TRUSTED_TO_MERGE_GROUP_NAME
        )

        context['versions'] = get_version_diffs(
            json.loads(person.extra.versions)
        )

        context = get_person_form_fields(context, kwargs['form'])

        return context
Exemplo n.º 25
0
    def get_context_data(self, **kwargs):
        context = super(UpdatePersonView, self).get_context_data(**kwargs)

        person = PopItPerson.create_from_popit(
            self.api,
            self.kwargs['person_id']
        )
        context['person'] = person

        context['user_can_merge'] = user_in_group(
            self.request.user,
            TRUSTED_TO_MERGE_GROUP_NAME
        )

        context['versions'] = get_version_diffs(person.versions)

        context['constituencies_form_fields'] = []
        for election_data in Election.objects.by_date():
            if not election_data.current:
                continue
            cons_form_fields = {
                'election_name': election_data.name,
                'standing': kwargs['form']['standing_' + election_data.slug],
                'constituency': kwargs['form']['constituency_' + election_data.slug],
            }
            party_fields = []
            for ps in PARTY_DATA.ALL_PARTY_SETS:
                key_suffix = ps['slug'] + '_' + election_data.slug
                position_field = None
                if election_data.party_lists_in_use:
                    position_field = kwargs['form']['party_list_position_' + key_suffix]
                party_position_tuple = (
                    kwargs['form']['party_' + key_suffix],
                    position_field
                )
                party_fields.append(party_position_tuple)
            cons_form_fields['party_fields'] = party_fields
            context['constituencies_form_fields'].append(cons_form_fields)

        return context
Exemplo n.º 26
0
def check_update_allowed(user, old_name, old_candidacies, new_name, new_candidacies):
    # Check whether an unauthorized user has tried to rename someone
    # while RESTRICT_RENAMES is set:
    usersettings = get_current_usersettings()
    if usersettings.RESTRICT_RENAMES:
        allowed_by_group = user_in_group(user, TRUSTED_TO_RENAME_GROUP_NAME)
        name_the_same = old_name == new_name
        if not (allowed_by_group or name_the_same):
            message = _("Name change from '{0}' to '{1}' by user {2} disallowed")
            raise NameChangeDisallowedException(message.format(
                old_name, new_name, user.username
            ))
    # Check that none of the posts that the person's leaving or
    # joining were locked:
    old_posts = set(c.post for c in old_candidacies)
    new_posts = set(c.post for c in new_candidacies)
    for post in old_posts ^ new_posts:
        dummy, edits_allowed = get_constituency_lock(user, post)
        if not edits_allowed:
            raise ChangeToLockedConstituencyDisallowedException(
                _("That update isn't allowed because candidates for a locked "
                  "post ({post_label}) would be changed").format(
                      post_label=post.label
                  )
            )
    # Now check that they're not changing party in a locked
    # constituency:
    for post in old_posts & new_posts:
        old_party = next(c.on_behalf_of for c in old_candidacies if c.post == post)
        new_party = next(c.on_behalf_of for c in new_candidacies if c.post == post)
        dummy, edits_allowed = get_constituency_lock(user, post)
        if not edits_allowed and (old_party != new_party):
            raise ChangeToLockedConstituencyDisallowedException(
                _("That update isn't allowed because you can't change the party "
                  "(in this case from {old_party} to {new_party}) for a candidate "
                  "in a locked post ({post_label})").format(
                      old_party=old_party.name, new_party=new_party.name,
                      post_label=post.label
                  )
            )
Exemplo n.º 27
0
    def get_context_data(self, **kwargs):
        context = super(UpdatePersonView, self).get_context_data(**kwargs)

        person = get_object_or_404(Person.objects.select_related('extra'),
                                   pk=self.kwargs['person_id'])
        context['person'] = person

        context['user_can_merge'] = user_in_group(self.request.user,
                                                  TRUSTED_TO_MERGE_GROUP_NAME)

        context['versions'] = get_version_diffs(
            json.loads(person.extra.versions))

        context['constituencies_form_fields'] = []
        for election_data in Election.objects.by_date():
            if not election_data.current:
                continue
            cons_form_fields = {
                'election_name':
                election_data.name,
                'standing':
                kwargs['form']['standing_' + election_data.slug],
                'constituency':
                kwargs['form']['constituency_' + election_data.slug],
            }
            party_fields = []
            for ps in PartySet.objects.all():
                key_suffix = ps.slug + '_' + election_data.slug
                position_field = None
                if election_data.party_lists_in_use:
                    position_field = kwargs['form']['party_list_position_' +
                                                    key_suffix]
                party_position_tuple = (kwargs['form']['party_' + key_suffix],
                                        position_field)
                party_fields.append(party_position_tuple)
            cons_form_fields['party_fields'] = party_fields
            context['constituencies_form_fields'].append(cons_form_fields)

        return context
Exemplo n.º 28
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        person = get_object_or_404(Person, pk=self.kwargs["person_id"])
        context["person"] = person

        context["user_can_merge"] = user_in_group(self.request.user,
                                                  TRUSTED_TO_MERGE_GROUP_NAME)

        context["versions"] = get_version_diffs(json.loads(person.versions))

        context = get_person_form_fields(context, context["form"])

        if "highlight_field" in self.request.GET:
            context["couldnt_find_field_form"] = PersonTaskForm(
                instance=person,
                data={
                    "task_field": self.request.GET["highlight_field"],
                    "person": person.pk,
                },
            )

        return context
Exemplo n.º 29
0
    def get_context_data(self, **kwargs):
        context = super(ConstituencyDetailView, self).get_context_data(**kwargs)

        context['mapit_area_id'] = mapit_area_id = kwargs['mapit_area_id']
        context['constituency_name'] = \
            get_constituency_name_from_mapit_id(mapit_area_id)

        if not context['constituency_name']:
            raise Http404("Constituency not found")

        context['electionleaflets_url'] = \
            get_electionleaflets_url(mapit_area_id, context['constituency_name'])

        context['meetyournextmp_url'] = \
            u'https://meetyournextmp.com/linktoseat.html?mapitid={}'.format(mapit_area_id)

        context['redirect_after_login'] = \
            urlquote(reverse('constituency', kwargs={
                'mapit_area_id': mapit_area_id,
                'ignored_slug': slugify(context['constituency_name'])
            }))

        context['nomination_papers'] = OfficialDocument.objects.filter(
            document_type=OfficialDocument.NOMINATION_PAPER,
            mapit_id=mapit_area_id,
        )

        mp_post = get_post_cached(self.api, mapit_area_id)

        context['candidates_locked'] = mp_post['result'].get(
            'candidates_locked', False
        )
        context['lock_form'] = ToggleLockForm(
            initial={
                'post_id': mapit_area_id,
                'lock': not context['candidates_locked'],
            },
        )
        context['candidate_list_edits_allowed'] = \
            self.request.user.is_authenticated() and (
                user_in_group(self.request.user, TRUSTED_TO_LOCK_GROUP_NAME) or
                (not context['candidates_locked'])
            )

        current_candidates = set()
        past_candidates = set()

        for membership in mp_post['result']['memberships']:
            if not membership['role'] == "Candidate":
                continue
            person = PopItPerson.create_from_dict(membership['person_id'])
            if membership_covers_date(membership, election_date_2010):
                past_candidates.add(person)
            elif membership_covers_date(membership, election_date_2015):
                current_candidates.add(person)
            else:
                raise ValueError("Candidate membership doesn't cover any \
                                  known election date")

        context['candidates_2010_standing_again'] = \
            past_candidates.intersection(current_candidates)

        other_candidates_2010 = past_candidates - current_candidates

        # Now split those candidates into those that we know aren't
        # standing again, and those that we just don't know about:
        context['candidates_2010_not_standing_again'] = \
            set(p for p in other_candidates_2010 if p.not_standing_in_2015)

        context['candidates_2010_might_stand_again'] = \
            set(p for p in other_candidates_2010 if not p.known_status_in_2015)

        context['candidates_2015'] = sorted(
            current_candidates,
            key=lambda c: c.last_name
        )

        context['add_candidate_form'] = NewPersonForm(
            initial={'constituency': mapit_area_id}
        )

        return context
Exemplo n.º 30
0
def get_edits_allowed(user, candidates_locked):
    return user.is_authenticated() and (user_in_group(
        user, TRUSTED_TO_LOCK_GROUP_NAME) or (not candidates_locked))
Exemplo n.º 31
0
    def get_context_data(self, **kwargs):
        context = super(UpdatePersonView, self).get_context_data(**kwargs)

        person = get_object_or_404(
            Person.objects.select_related('extra'),
            pk=self.kwargs['person_id']
        )
        context['person'] = person

        memberships = Membership.objects.select_related('post', 'organization', 'area').filter(person_id=person.id)
        memberships = sortMemberships(memberships)
        context['last_membership'] = memberships[0] if len(memberships) > 0 else None
        context['old_memberships'] = memberships[1:] if len(memberships) > 1 else []

        context['user_can_merge'] = user_in_group(
            self.request.user,
            TRUSTED_TO_MERGE_GROUP_NAME
        )

        context['versions'] = get_version_diffs(
            json.loads(person.extra.versions)
        )

        personal_fields, demographic_fields = get_field_groupings()

        context['personal_fields'] = []
        context['demographic_fields'] = []
        simple_fields = SimplePopoloField.objects.order_by('order').all()
        for field in simple_fields:
            if field.name in personal_fields:
                context['personal_fields'].append(kwargs['form'][field.name])

            if field.name in demographic_fields:
                context['demographic_fields'].append(kwargs['form'][field.name])

        context['extra_fields'] = get_extra_fields(person)
        for k, v in context['extra_fields'].items():
            v['form_field'] = kwargs['form'][k]

        '''
        context['constituencies_form_fields'] = []
        for election_data in Election.objects.by_date():
            if not election_data.current:
                continue
            cons_form_fields = {
                'election_name': election_data.name,
                'standing': kwargs['form']['standing_' + election_data.slug],
                'constituency': kwargs['form']['constituency_' + election_data.slug],
            }
            party_fields = []
            for ps in PartySet.objects.all():
                key_suffix = ps.slug + '_' + election_data.slug
                position_field = None
                if election_data.party_lists_in_use:
                    position_field = kwargs['form']['party_list_position_' + key_suffix]
                party_position_tuple = (
                    kwargs['form']['party_' + key_suffix],
                    position_field
                )
                party_fields.append(party_position_tuple)
            cons_form_fields['party_fields'] = party_fields
            context['constituencies_form_fields'].append(cons_form_fields)
        '''
        context['all_areas'] = Area.objects.all();

        return context
Exemplo n.º 32
0
def get_edits_allowed(user, candidates_locked):
    return user.is_authenticated() and (
        user_in_group(user, TRUSTED_TO_LOCK_GROUP_NAME) or
        (not candidates_locked)
    )