コード例 #1
0
def voter_guide_search_view(request):
    """
    Before creating a voter guide, search for an existing organization
    :param request:
    :return:
    """
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    # A positive value in google_civic_election_id means we want to create a voter guide for this org for this election
    google_civic_election_id = request.GET.get('google_civic_election_id', 0)

    messages_on_stage = get_messages(request)

    election_manager = ElectionManager()
    upcoming_election_list = []
    results = election_manager.retrieve_upcoming_elections()
    if results['success']:
        upcoming_election_list = results['election_list']

    state_list = STATE_CODE_MAP
    sorted_state_list = sorted(state_list.items())

    template_values = {
        'messages_on_stage': messages_on_stage,
        'upcoming_election_list': upcoming_election_list,
        'google_civic_election_id': google_civic_election_id,
        'state_list': sorted_state_list,
    }
    return render(request, 'voter_guide/voter_guide_search.html',
                  template_values)
コード例 #2
0
ファイル: views_admin.py プロジェクト: trinile/WeVoteServer
def organization_new_view(request):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    # A positive value in google_civic_election_id means we want to create a voter guide for this org for this election
    google_civic_election_id = request.GET.get('google_civic_election_id', 0)

    election_manager = ElectionManager()
    upcoming_election_list = []
    results = election_manager.retrieve_upcoming_elections()
    if results['success']:
        upcoming_election_list = results['election_list']

    state_list = STATE_CODE_MAP
    sorted_state_list = sorted(state_list.items())

    messages_on_stage = get_messages(request)
    template_values = {
        'messages_on_stage':        messages_on_stage,
        'upcoming_election_list':   upcoming_election_list,
        'google_civic_election_id': google_civic_election_id,
        'state_list':               sorted_state_list,
    }
    return render(request, 'organization/organization_edit.html', template_values)
コード例 #3
0
def store_results_from_google_civic_api_election_query(structured_json):
    elections_list_json = structured_json['elections']
    for one_election in elections_list_json:
        raw_ocd_division_id = one_election['ocdDivisionId']
        election_date_text = one_election['electionDay']
        google_civic_election_id = one_election['id']
        election_name = one_election['name']

        election_manager = ElectionManager()
        results = election_manager.update_or_create_election(
            google_civic_election_id, election_name, election_date_text, raw_ocd_division_id)

    return results
コード例 #4
0
def store_results_from_google_civic_api_election_query(structured_json):
    elections_list_json = structured_json['elections']
    for one_election in elections_list_json:
        raw_ocd_division_id = one_election['ocdDivisionId']
        election_date_text = one_election['electionDay']
        google_civic_election_id = one_election['id']
        election_name = one_election['name']

        election_manager = ElectionManager()
        results = election_manager.update_or_create_election(
            google_civic_election_id, election_name, election_date_text,
            raw_ocd_division_id)

    return results
コード例 #5
0
ファイル: models.py プロジェクト: nf071590/WeVoteServer
 def fetch_most_recent_google_civic_election_id(self):
     election_manager = ElectionManager()
     results = election_manager.retrieve_elections_by_date()
     if results['success']:
         election_list = results['election_list']
         for one_election in election_list:
             ballot_item_queryset = BallotItem.objects.all()
             ballot_item_queryset = ballot_item_queryset.filter(
                 google_civic_election_id=one_election.google_civic_election_id)
             number_found = ballot_item_queryset.count()
             if positive_value_exists(number_found):
                 # Since we are starting with the most recent election, as soon as we find
                 # any election with ballot items, we can exit.
                 return one_election.google_civic_election_id
     return 0
コード例 #6
0
ファイル: models.py プロジェクト: nf071590/WeVoteServer
    def retrieve_most_recent_voter_guide_for_org(self, organization_we_vote_id):
        status = 'ENTERING_RETRIEVE_MOST_RECENT_VOTER_GUIDE_FOR_ORG'
        voter_guide_found = False
        voter_guide = VoterGuide()
        voter_guide_manager = VoterGuideManager()
        for time_span in TIME_SPAN_LIST:
            voter_guide_by_time_span_results = voter_guide_manager.retrieve_voter_guide(
                vote_smart_time_span=time_span,
                organization_we_vote_id=organization_we_vote_id)
            if voter_guide_by_time_span_results['voter_guide_found']:
                voter_guide_found = True
                voter_guide = voter_guide_by_time_span_results['voter_guide']
                status = 'MOST_RECENT_VOTER_GUIDE_FOUND_FOR_ORG_BY_TIME_SPAN'
                results = {
                    'success':              voter_guide_found,
                    'status':               status,
                    'voter_guide_found':    voter_guide_found,
                    'voter_guide':          voter_guide,
                }
                return results

        election_manager = ElectionManager()
        results = election_manager.retrieve_elections_by_date()
        if results['success']:
            election_list = results['election_list']
            for one_election in election_list:
                voter_guide_results = voter_guide_manager.retrieve_voter_guide(
                    google_civic_election_id=one_election.google_civic_election_id,
                    organization_we_vote_id=organization_we_vote_id)
                if voter_guide_results['voter_guide_found']:
                    voter_guide_found = True
                    voter_guide = voter_guide_results['voter_guide']
                    status = 'MOST_RECENT_VOTER_GUIDE_FOUND_FOR_ORG_BY_ELECTION_ID'
                    results = {
                        'success':              voter_guide_found,
                        'status':               status,
                        'voter_guide_found':    voter_guide_found,
                        'voter_guide':          voter_guide,
                    }
                    return results

        results = {
            'success':              False,
            'status':               status,
            'voter_guide_found':    voter_guide_found,
            'voter_guide':          voter_guide,
        }
        return results
コード例 #7
0
def organization_edit_view(request, organization_id):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    # A positive value in google_civic_election_id means we want to create a voter guide for this org for this election
    google_civic_election_id = request.GET.get('google_civic_election_id', 0)

    messages_on_stage = get_messages(request)
    organization_id = convert_to_int(organization_id)
    organization_on_stage_found = False
    organization_manager = OrganizationManager()
    organization_on_stage = Organization()
    state_served_code = ''
    results = organization_manager.retrieve_organization(organization_id)
    if results['organization_found']:
        organization_on_stage = results['organization']
        state_served_code = organization_on_stage.state_served_code
        organization_on_stage_found = True

    election_manager = ElectionManager()
    upcoming_election_list = []
    results = election_manager.retrieve_upcoming_elections()
    if results['success']:
        upcoming_election_list = results['election_list']

    state_list = STATE_CODE_MAP
    sorted_state_list = sorted(state_list.items())

    if organization_on_stage_found:
        template_values = {
            'messages_on_stage': messages_on_stage,
            'organization': organization_on_stage,
            'upcoming_election_list': upcoming_election_list,
            'google_civic_election_id': google_civic_election_id,
            'state_list': sorted_state_list,
            'state_served_code': state_served_code,
        }
    else:
        template_values = {
            'messages_on_stage': messages_on_stage,
            'upcoming_election_list': upcoming_election_list,
            'google_civic_election_id': google_civic_election_id,
            'state_list': sorted_state_list,
        }
    return render(request, 'organization/organization_edit.html',
                  template_values)
コード例 #8
0
ファイル: views_admin.py プロジェクト: trinile/WeVoteServer
def organization_edit_view(request, organization_id):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    # A positive value in google_civic_election_id means we want to create a voter guide for this org for this election
    google_civic_election_id = request.GET.get('google_civic_election_id', 0)

    messages_on_stage = get_messages(request)
    organization_id = convert_to_int(organization_id)
    organization_on_stage_found = False
    organization_manager = OrganizationManager()
    organization_on_stage = Organization()
    state_served_code = ''
    results = organization_manager.retrieve_organization(organization_id)
    if results['organization_found']:
        organization_on_stage = results['organization']
        state_served_code = organization_on_stage.state_served_code
        organization_on_stage_found = True

    election_manager = ElectionManager()
    upcoming_election_list = []
    results = election_manager.retrieve_upcoming_elections()
    if results['success']:
        upcoming_election_list = results['election_list']

    state_list = STATE_CODE_MAP
    sorted_state_list = sorted(state_list.items())

    if organization_on_stage_found:
        template_values = {
            'messages_on_stage':        messages_on_stage,
            'organization':             organization_on_stage,
            'upcoming_election_list':   upcoming_election_list,
            'google_civic_election_id': google_civic_election_id,
            'state_list':               sorted_state_list,
            'state_served_code':        state_served_code,
        }
    else:
        template_values = {
            'messages_on_stage': messages_on_stage,
            'upcoming_election_list':   upcoming_election_list,
            'google_civic_election_id': google_civic_election_id,
            'state_list':               sorted_state_list,
        }
    return render(request, 'organization/organization_edit.html', template_values)
コード例 #9
0
def store_results_from_google_civic_api_election_query(structured_json):
    if "elections" in structured_json:
        elections_list_json = structured_json["elections"]
    else:
        elections_list_json = {}
    results = {}
    for one_election in elections_list_json:
        raw_ocd_division_id = one_election["ocdDivisionId"]
        election_date_text = one_election["electionDay"]
        google_civic_election_id = one_election["id"]
        election_name = one_election["name"]

        election_manager = ElectionManager()
        results = election_manager.update_or_create_election(
            google_civic_election_id, election_name, election_date_text, raw_ocd_division_id
        )

    return results
コード例 #10
0
ファイル: views_admin.py プロジェクト: trinile/WeVoteServer
def organization_edit_process_view(request):
    """
    Process the new or edit organization forms
    :param request:
    :return:
    """
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    organization_id = convert_to_int(request.POST.get('organization_id', 0))
    organization_name = request.POST.get('organization_name', '')
    organization_twitter_handle = request.POST.get('organization_twitter_handle', False)
    organization_facebook = request.POST.get('organization_facebook', False)
    organization_website = request.POST.get('organization_website', False)
    wikipedia_page_title = request.POST.get('wikipedia_page_title', False)
    wikipedia_photo_url = request.POST.get('wikipedia_photo_url', False)
    state_served_code = request.POST.get('state_served_code', False)

    # A positive value in google_civic_election_id or add_organization_button means we want to create a voter guide
    # for this org for this election
    google_civic_election_id = request.POST.get('google_civic_election_id', 0)
    # add_organization_button = request.POST.get('add_organization_button', False)

    # Filter incoming data
    organization_twitter_handle = extract_twitter_handle_from_text_string(organization_twitter_handle)

    # Check to see if this organization is already being used anywhere
    organization_on_stage_found = False
    try:
        organization_query = Organization.objects.filter(id=organization_id)
        if organization_query.count():
            organization_on_stage = organization_query[0]
            organization_on_stage_found = True
    except Exception as e:
        handle_record_not_found_exception(e, logger=logger)

    try:
        if organization_on_stage_found:
            # Update
            if organization_name is not False:
                organization_on_stage.organization_name = organization_name
            if organization_twitter_handle is not False:
                organization_on_stage.organization_twitter_handle = organization_twitter_handle
            if organization_facebook is not False:
                organization_on_stage.organization_facebook = organization_facebook
            if organization_website is not False:
                organization_on_stage.organization_website = organization_website
            if wikipedia_page_title is not False:
                organization_on_stage.wikipedia_page_title = wikipedia_page_title
            if wikipedia_photo_url is not False:
                organization_on_stage.wikipedia_photo_url = wikipedia_photo_url
            if state_served_code is not False:
                organization_on_stage.state_served_code = state_served_code
            organization_on_stage.save()
            organization_id = organization_on_stage.id
            organization_we_vote_id = organization_on_stage.we_vote_id
            messages.add_message(request, messages.INFO, 'Organization updated.')
        else:
            # Create new

            # But first double-check that we don't have an org entry already
            organization_email = ''
            organization_list_manager = OrganizationListManager()
            results = organization_list_manager.organization_search_find_any_possibilities(
                organization_name, organization_twitter_handle, organization_website, organization_email)

            if results['organizations_found']:
                organizations_list = results['organizations_list']
                organizations_count = len(organizations_list)

                messages.add_message(request, messages.INFO, 'We found {count} existing organizations '
                                                             'that might match.'.format(count=organizations_count))
                messages_on_stage = get_messages(request)
                template_values = {
                    'messages_on_stage':            messages_on_stage,
                    'organizations_list':           organizations_list,
                    'organization_name':            organization_name,
                    'organization_twitter_handle':  organization_twitter_handle,
                    'organization_facebook':        organization_facebook,
                    'organization_website':         organization_website,
                    'wikipedia_page_title':         wikipedia_page_title,
                    'wikipedia_photo_url':          wikipedia_photo_url,
                }
                return render(request, 'organization/organization_edit.html', template_values)

            minimum_required_variables_exist = positive_value_exists(organization_name)
            if not minimum_required_variables_exist:
                messages.add_message(request, messages.INFO, 'Missing name, which is required.')
                messages_on_stage = get_messages(request)
                template_values = {
                    'messages_on_stage':            messages_on_stage,
                    'organization_name':            organization_name,
                    'organization_twitter_handle':  organization_twitter_handle,
                    'organization_facebook':        organization_facebook,
                    'organization_website':         organization_website,
                    'wikipedia_page_title':         wikipedia_page_title,
                    'wikipedia_photo_url':          wikipedia_photo_url,
                }
                return render(request, 'voter_guide/voter_guide_search.html', template_values)

            organization_on_stage = Organization(
                organization_name=organization_name,
            )
            if organization_twitter_handle is not False:
                organization_on_stage.organization_twitter_handle = organization_twitter_handle
            if organization_facebook is not False:
                organization_on_stage.organization_facebook = organization_facebook
            if organization_website is not False:
                organization_on_stage.organization_website = organization_website
            if wikipedia_page_title is not False:
                organization_on_stage.wikipedia_page_title = wikipedia_page_title
            if wikipedia_photo_url is not False:
                organization_on_stage.wikipedia_photo_url = wikipedia_photo_url
            if state_served_code is not False:
                organization_on_stage.state_served_code = state_served_code
            organization_on_stage.save()
            organization_id = organization_on_stage.id
            organization_we_vote_id = organization_on_stage.we_vote_id
            messages.add_message(request, messages.INFO, 'New organization saved.')
    except Exception as e:
        messages.add_message(request, messages.ERROR, 'Could not save organization.'
                                                      ' {error} [type: {error_type}]'.format(error=e,
                                                                                             error_type=type(e)))
        return HttpResponseRedirect(reverse('organization:organization_list', args=()))

    # Create voter_guide for this election?
    if positive_value_exists(google_civic_election_id) and positive_value_exists(organization_we_vote_id):
        election_manager = ElectionManager()
        results = election_manager.retrieve_election(google_civic_election_id)
        if results['election_found']:
            election = results['election']
            voter_guide_manager = VoterGuideManager()
            results = voter_guide_manager.update_or_create_organization_voter_guide_by_election_id(
                organization_we_vote_id, google_civic_election_id)
            if results['voter_guide_saved']:
                messages.add_message(request, messages.INFO, 'Voter guide for {election_name} election saved.'
                                                             ''.format(election_name=election.election_name))

    return HttpResponseRedirect(reverse('organization:organization_position_list', args=(organization_id,)) +
                                "?google_civic_election_id=" + str(google_civic_election_id))
コード例 #11
0
def office_edit_process_view(request):
    """
    Process the new or edit office forms
    :param request:
    :return:
    """
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    office_id = convert_to_int(request.POST.get('office_id', 0))
    office_name = request.POST.get('office_name', False)
    google_civic_election_id = request.POST.get('google_civic_election_id', 0)
    primary_party = request.POST.get('primary_party', False)
    state_code = request.POST.get('state_code', False)

    election_state = ''
    if state_code is not False:
        election_state = state_code
    elif google_civic_election_id:
        election_manager = ElectionManager()
        results = election_manager.retrieve_election(google_civic_election_id)
        if results['election_found']:
            election = results['election']
            election_state = election.get_election_state()

    # Check to see if this office is already in the database
    office_on_stage_found = False
    try:
        office_query = ContestOffice.objects.filter(id=office_id)
        if len(office_query):
            office_on_stage = office_query[0]
            office_on_stage_found = True
    except Exception as e:
        handle_record_not_found_exception(e, logger=logger)

    try:
        if office_on_stage_found:
            # Update
            # Removed for now: convert_to_int(office_on_stage.google_civic_election_id) >= 1000000 and
            if office_name is not False:
                office_on_stage.office_name = office_name
            if primary_party is not False:
                office_on_stage.primary_party = primary_party
            if positive_value_exists(election_state):
                office_on_stage.state_code = election_state
            office_on_stage.save()
            messages.add_message(request, messages.INFO, 'Office updated.')
            google_civic_election_id = office_on_stage.google_civic_election_id

            return HttpResponseRedirect(
                reverse('office:office_list', args=()) +
                "?google_civic_election_id=" + google_civic_election_id)
        else:
            # Create new
            office_on_stage = ContestOffice(
                office_name=office_name,
                google_civic_election_id=google_civic_election_id,
                state_code=election_state,
            )
            # Removing this limitation: convert_to_int(office_on_stage.google_civic_election_id) >= 1000000 and
            if primary_party is not False:
                office_on_stage.primary_party = primary_party
            office_on_stage.save()
            messages.add_message(request, messages.INFO, 'New office saved.')

            # Come back to the "Create New Office" page
            return HttpResponseRedirect(
                reverse('office:office_new', args=()) +
                "?google_civic_election_id=" + google_civic_election_id)
    except Exception as e:
        handle_record_not_saved_exception(e, logger=logger)
        messages.add_message(request, messages.ERROR, 'Could not save office.')

    return HttpResponseRedirect(
        reverse('office:office_list', args=()) + "?google_civic_election_id=" +
        google_civic_election_id)
コード例 #12
0
ファイル: views_admin.py プロジェクト: trinile/WeVoteServer
def voter_guide_search_process_view(request):
    """
    Process the new or edit organization forms
    :param request:
    :return:
    """
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    add_organization_button = request.POST.get('add_organization_button', False)
    if add_organization_button:
        return organization_edit_process_view(request)

    organization_name = request.POST.get('organization_name', '')
    organization_twitter_handle = request.POST.get('organization_twitter_handle', '')
    organization_facebook = request.POST.get('organization_facebook', '')
    organization_website = request.POST.get('organization_website', '')
    # state_served_code = request.POST.get('state_served_code', False)

    # Save this variable so we have it on the "Add New Position" page
    google_civic_election_id = request.POST.get('google_civic_election_id', 0)

    # Filter incoming data
    organization_twitter_handle = extract_twitter_handle_from_text_string(organization_twitter_handle)

    # Search for organizations that match
    organization_email = ''
    organization_list_manager = OrganizationListManager()
    results = organization_list_manager.organization_search_find_any_possibilities(
        organization_name, organization_twitter_handle, organization_website, organization_email,
        organization_facebook)

    if results['organizations_found']:
        organizations_list = results['organizations_list']
        organizations_count = len(organizations_list)

        messages.add_message(request, messages.INFO, 'We found {count} existing organization(s) '
                                                     'that might match.'.format(count=organizations_count))
    else:
        organizations_list = []
        messages.add_message(request, messages.INFO, 'No voter guides found with those search terms. '
                                                     'Please try again. ')

    election_manager = ElectionManager()
    upcoming_election_list = []
    results = election_manager.retrieve_upcoming_elections()
    if results['success']:
        upcoming_election_list = results['election_list']

    messages_on_stage = get_messages(request)
    template_values = {
        'messages_on_stage':            messages_on_stage,
        'organizations_list':           organizations_list,
        'organization_name':            organization_name,
        'organization_twitter_handle':  organization_twitter_handle,
        'organization_facebook':        organization_facebook,
        'organization_website':         organization_website,
        'upcoming_election_list':       upcoming_election_list,
        'google_civic_election_id':     google_civic_election_id,
    }
    return render(request, 'voter_guide/voter_guide_search.html', template_values)
コード例 #13
0
def voter_ballot_items_retrieve_for_api(voter_device_id,
                                        google_civic_election_id):
    status = ''

    # We retrieve voter_device_link
    voter_device_link_manager = VoterDeviceLinkManager()
    voter_device_link_results = voter_device_link_manager.retrieve_voter_device_link(
        voter_device_id)
    if not voter_device_link_results['voter_device_link_found']:
        status += "VALID_VOTER_DEVICE_ID_MISSING "
        error_json_data = {
            'status': status,
            'success': False,
            'voter_device_id': voter_device_id,
            'ballot_found': False,
            'ballot_item_list': [],
            'google_civic_election_id': google_civic_election_id,
            'text_for_map_search': '',
            'substituted_address_nearby': '',
            'ballot_caveat': '',
            'is_from_substituted_address': False,
            'is_from_test_ballot': False,
        }
        return error_json_data

    voter_device_link = voter_device_link_results['voter_device_link']
    voter_id = voter_device_link.voter_id

    if not positive_value_exists(voter_id):
        status += " " + "VALID_VOTER_ID_MISSING"
        error_json_data = {
            'status': status,
            'success': False,
            'voter_device_id': voter_device_id,
            'ballot_found': False,
            'ballot_item_list': [],
            'google_civic_election_id': google_civic_election_id,
            'text_for_map_search': '',
            'substituted_address_nearby': '',
            'ballot_caveat': '',
            'is_from_substituted_address': False,
            'is_from_test_ballot': False,
        }
        return error_json_data

    voter_address_manager = VoterAddressManager()
    voter_address_id = 0
    address_type = BALLOT_ADDRESS
    voter_address_results = voter_address_manager.retrieve_address(
        voter_address_id, voter_id, address_type)
    status += " " + voter_address_results['status']
    if not positive_value_exists(
            voter_address_results['voter_address_has_value']):
        error_json_data = {
            'status': status,
            'success': voter_address_results['success'],
            'voter_device_id': voter_device_id,
            'ballot_found': False,
            'ballot_item_list': [],
            'google_civic_election_id': 0,
            'text_for_map_search': '',
            'substituted_address_nearby': '',
            'ballot_caveat': '',
            'is_from_substituted_address': False,
            'is_from_test_ballot': False,
        }
        return error_json_data

    voter_address = voter_address_results['voter_address']

    results = choose_election_and_prepare_ballot_data(
        voter_device_link, google_civic_election_id, voter_address)
    status += " " + results['status']
    if not results['voter_ballot_saved_found']:
        if positive_value_exists(voter_address.text_for_map_search):
            ballot_caveat = "We could not find a ballot near '{text_for_map_search}'.".format(
                text_for_map_search=voter_address.text_for_map_search)
        else:
            ballot_caveat = "Please save your address so we can find your ballot."

        error_json_data = {
            'status': status,
            'success': True,
            'voter_device_id': voter_device_id,
            'ballot_found': False,
            'ballot_item_list': [],
            'google_civic_election_id': 0,
            'text_for_map_search': voter_address.text_for_map_search,
            'substituted_address_nearby': '',
            'ballot_caveat': ballot_caveat,
            'is_from_substituted_address': False,
            'is_from_test_ballot': False,
        }
        return error_json_data

    google_civic_election_id = results['google_civic_election_id']
    voter_ballot_saved = results['voter_ballot_saved']

    # Update voter_device_link
    if voter_device_link.google_civic_election_id != google_civic_election_id:
        voter_device_link_manager.update_voter_device_link_with_election_id(
            voter_device_link, google_civic_election_id)

    # Update voter_address to include matching google_civic_election_id and voter_ballot_saved entry
    if positive_value_exists(google_civic_election_id):
        voter_address.google_civic_election_id = google_civic_election_id
        voter_address_manager.update_existing_voter_address_object(
            voter_address)

        # Get and return the ballot_item_list
        results = voter_ballot_items_retrieve_for_one_election_for_api(
            voter_device_id, voter_id, google_civic_election_id)

        if not positive_value_exists(voter_ballot_saved.election_description_text) \
                or not positive_value_exists(voter_ballot_saved.election_date_text()):
            try:
                election_manager = ElectionManager()
                election_results = election_manager.retrieve_election(
                    google_civic_election_id)
                if election_results['election_found']:
                    election = election_results['election']
                    if not positive_value_exists(
                            voter_ballot_saved.election_description_text):
                        voter_ballot_saved.election_description_text = election.election_name
                    if not positive_value_exists(
                            voter_ballot_saved.election_date_text()):
                        voter_ballot_saved.election_date = \
                            datetime.strptime(election.election_day_text, "%Y-%m-%d").date()
                    voter_ballot_saved.save()
            except Exception as e:
                status += "Failed to update election_name"

        status += " " + results['status']
        json_data = {
            'status': status,
            'success': True,
            'voter_device_id': voter_device_id,
            'ballot_found': True,
            'ballot_item_list': results['ballot_item_list'],
            'google_civic_election_id': google_civic_election_id,
            'election_name': voter_ballot_saved.election_description_text,
            'election_date': voter_ballot_saved.election_date_text(),
            'text_for_map_search':
            voter_ballot_saved.original_text_for_map_search,
            'substituted_address_nearby':
            voter_ballot_saved.substituted_address_nearby,
            'ballot_caveat': voter_ballot_saved.ballot_caveat(),
            'is_from_substituted_address':
            voter_ballot_saved.is_from_substituted_address,
            'is_from_test_ballot': voter_ballot_saved.is_from_test_ballot,
        }
        return json_data

    status += " " + "NO_VOTER_BALLOT_SAVED_FOUND"
    error_json_data = {
        'status': status,
        'success': True,
        'voter_device_id': voter_device_id,
        'ballot_found': False,
        'ballot_item_list': [],
        'google_civic_election_id': 0,
        'text_for_map_search': '',
        'substituted_address_nearby': '',
        'ballot_caveat': '',
        'is_from_substituted_address': False,
        'is_from_test_ballot': False,
    }
    return error_json_data
コード例 #14
0
def voter_guide_search_process_view(request):
    """
    Process the new or edit organization forms
    :param request:
    :return:
    """
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    add_organization_button = request.POST.get('add_organization_button',
                                               False)
    if add_organization_button:
        return organization_edit_process_view(request)

    organization_name = request.POST.get('organization_name', '')
    organization_twitter_handle = request.POST.get(
        'organization_twitter_handle', '')
    organization_facebook = request.POST.get('organization_facebook', '')
    organization_website = request.POST.get('organization_website', '')
    # state_served_code = request.POST.get('state_served_code', False)

    # Save this variable so we have it on the "Add New Position" page
    google_civic_election_id = request.POST.get('google_civic_election_id', 0)

    # Filter incoming data
    organization_twitter_handle = extract_twitter_handle_from_text_string(
        organization_twitter_handle)

    # Search for organizations that match
    organization_email = ''
    organization_list_manager = OrganizationListManager()
    results = organization_list_manager.organization_search_find_any_possibilities(
        organization_name, organization_twitter_handle, organization_website,
        organization_email, organization_facebook)

    if results['organizations_found']:
        organizations_list = results['organizations_list']
        organizations_count = len(organizations_list)

        messages.add_message(
            request, messages.INFO,
            'We found {count} existing organization(s) '
            'that might match.'.format(count=organizations_count))
    else:
        organizations_list = []
        messages.add_message(
            request, messages.INFO,
            'No voter guides found with those search terms. '
            'Please try again. ')

    election_manager = ElectionManager()
    upcoming_election_list = []
    results = election_manager.retrieve_upcoming_elections()
    if results['success']:
        upcoming_election_list = results['election_list']

    messages_on_stage = get_messages(request)
    template_values = {
        'messages_on_stage': messages_on_stage,
        'organizations_list': organizations_list,
        'organization_name': organization_name,
        'organization_twitter_handle': organization_twitter_handle,
        'organization_facebook': organization_facebook,
        'organization_website': organization_website,
        'upcoming_election_list': upcoming_election_list,
        'google_civic_election_id': google_civic_election_id,
    }
    return render(request, 'voter_guide/voter_guide_search.html',
                  template_values)
コード例 #15
0
def election_migration_view(request):
    authority_required = {'admin'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    messages_on_stage = get_messages(request)
    election_manager = ElectionManager()
    we_vote_election = Election()
    office_list_manager = ContestOfficeListManager()
    candidate_list_manager = CandidateCampaignListManager()
    position_list_manager = PositionListManager()
    we_vote_election_office_list = []
    google_civic_election_office_list = []

    results = election_manager.retrieve_we_vote_elections()
    we_vote_election_list = results['election_list']
    state_code_list = []
    for election in we_vote_election_list:
        if election.state_code not in state_code_list:
            state_code_list.append(election.state_code)

    google_civic_election = Election()
    results = election_manager.retrieve_google_civic_elections_in_state_list(state_code_list)
    google_civic_election_list = results['election_list']

    we_vote_election_id = convert_to_int(request.GET.get('we_vote_election_id', 0))
    if not positive_value_exists(we_vote_election_id):
        we_vote_election_id = convert_to_int(request.POST.get('we_vote_election_id', 0))
    if positive_value_exists(we_vote_election_id):
        results = election_manager.retrieve_election(we_vote_election_id)
        if results['election_found']:
            we_vote_election = results['election']

            return_list_of_objects = True
            results = office_list_manager.retrieve_all_offices_for_upcoming_election(we_vote_election_id,
                                                                                     return_list_of_objects)
            if results['office_list_found']:
                we_vote_election_office_list = results['office_list_objects']

    # Go through each office and attach a list of candidates under this office
    we_vote_election_office_list_new = []
    for one_office in we_vote_election_office_list:
        candidate_results = candidate_list_manager.retrieve_all_candidates_for_office(0, one_office.we_vote_id)
        if candidate_results['candidate_list_found']:
            candidate_list = candidate_results['candidate_list']
            new_candidate_list = []
            # Go through candidate_list and find the number of positions saved for each candidate
            for candidate in candidate_list:
                retrieve_public_positions = True  # The alternate is positions for friends-only
                position_list = position_list_manager.retrieve_all_positions_for_candidate_campaign(
                    retrieve_public_positions, 0, candidate.we_vote_id)
                candidate.position_count = len(position_list)  # This is wasteful (instead of using count), but ok

                # Now find the candidates from the Google Civic Election that we might want to transfer data to

                new_candidate_list.append(candidate)

            one_office.candidate_list = new_candidate_list
        else:
            one_office.candidate_list = []
        we_vote_election_office_list_new.append(one_office)

    google_civic_election_id = convert_to_int(request.GET.get('google_civic_election_id', 0))
    if not positive_value_exists(google_civic_election_id):
        google_civic_election_id = convert_to_int(request.POST.get('google_civic_election_id', 0))
    if positive_value_exists(google_civic_election_id):
        results = election_manager.retrieve_election(google_civic_election_id)
        if results['election_found']:
            google_civic_election = results['election']

            return_list_of_objects = True
            results = office_list_manager.retrieve_all_offices_for_upcoming_election(google_civic_election_id,
                                                                                     return_list_of_objects)
            if results['office_list_found']:
                google_civic_election_office_list = results['office_list_objects']

    # We want to transfer the
    transfer_array = {}
    transfer_array['wv01off1461'] = "wv02off269"

    template_values = {
        'messages_on_stage':                    messages_on_stage,
        'we_vote_election':                     we_vote_election,
        'we_vote_election_id':                  we_vote_election_id,
        'we_vote_election_list':                we_vote_election_list,
        'we_vote_election_office_list':         we_vote_election_office_list_new,
        'google_civic_election':                google_civic_election,
        'google_civic_election_id':             google_civic_election_id,
        'google_civic_election_list':           google_civic_election_list,
        'google_civic_election_office_list':    google_civic_election_office_list,
    }

    return render(request, 'election/election_migration.html', template_values)
コード例 #16
0
def ballot_item_list_edit_process_view(request):
    """
    Process the new or edit ballot form
    :param request:
    :return:
    """
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    ballot_returned_id = convert_to_int(
        request.POST.get('ballot_returned_id', 0))
    google_civic_election_id = request.POST.get('google_civic_election_id', 0)
    polling_location_id = convert_to_int(
        request.POST.get('polling_location_id', 0))
    polling_location_city = request.POST.get('polling_location_city', '')
    polling_location_zip = request.POST.get('polling_location_zip', '')
    contest_office1_id = request.POST.get('contest_office1_id', 0)
    contest_office1_order = request.POST.get('contest_office1_order', 0)
    contest_measure1_id = request.POST.get('contest_measure1_id', 0)

    election_local_id = 0

    # Find existing ballot_returned
    ballot_returned_found = False
    ballot_returned = BallotReturned()
    if positive_value_exists(ballot_returned_id):
        try:
            ballot_returned_query = BallotReturned.objects.filter(
                id=ballot_returned_id)
            if len(ballot_returned_query):
                ballot_returned = ballot_returned_query[0]
                ballot_returned_found = True
        except Exception as e:
            pass

    election_manager = ElectionManager()
    polling_location_manager = PollingLocationManager()
    polling_location = PollingLocation()
    polling_location_found = False
    try:
        if ballot_returned_found:
            # Update

            # Check to see if this is a We Vote-created election
            is_we_vote_google_civic_election_id = True \
                if convert_to_int(ballot_returned.google_civic_election_id) >= 1000000 \
                else False

            results = election_manager.retrieve_election(
                ballot_returned.google_civic_election_id)
            if results['election_found']:
                election = results['election']
                election_local_id = election.id

            # polling_location must be found
            # We cannot change a polling location once saved, so we ignore the incoming polling_location_id here
            results = polling_location_manager.retrieve_polling_location_by_id(
                0, ballot_returned.polling_location_we_vote_id)
            if results['polling_location_found']:
                polling_location = results['polling_location']
                polling_location_found = True
        else:
            # Create new ballot_returned entry
            # election must be found
            election_results = election_manager.retrieve_election(
                google_civic_election_id)
            if election_results['election_found']:
                election = election_results['election']
                election_local_id = election.id
                state_code = election.get_election_state()
            else:
                messages.add_message(
                    request, messages.ERROR, 'Could not find election -- '
                    'required to save ballot_returned.')
                return HttpResponseRedirect(
                    reverse('ballot:ballot_item_list_edit',
                            args=(ballot_returned_id, )) +
                    "?google_civic_election_id=" +
                    str(google_civic_election_id) + "&polling_location_id=" +
                    str(polling_location_id) + "&polling_location_city=" +
                    polling_location_city + "&polling_location_zip=" +
                    str(polling_location_zip))

            # polling_location must be found
            if positive_value_exists(polling_location_id):
                results = polling_location_manager.retrieve_polling_location_by_id(
                    polling_location_id)
                if results['polling_location_found']:
                    polling_location = results['polling_location']
                    polling_location_found = True

            if not polling_location_found:
                messages.add_message(
                    request, messages.ERROR,
                    'Could not find polling_location -- '
                    'required to save ballot_returned.')
                return HttpResponseRedirect(
                    reverse('ballot:ballot_item_list_edit',
                            args=(ballot_returned_id, )) +
                    "?google_civic_election_id=" +
                    str(google_civic_election_id) + "&polling_location_id=" +
                    str(polling_location_id) + "&polling_location_city=" +
                    polling_location_city + "&polling_location_zip=" +
                    str(polling_location_zip))

            ballot_returned = BallotReturned(
                election_date=election.election_day_text,
                election_description_text=election.election_name,
                google_civic_election_id=google_civic_election_id,
                polling_location_we_vote_id=polling_location.we_vote_id,
                normalized_city=polling_location.city,
                normalized_line1=polling_location.line1,
                normalized_line2=polling_location.line2,
                normalized_state=polling_location.state,
                normalized_zip=polling_location.get_formatted_zip(),
                text_for_map_search=polling_location.get_text_for_map_search(),
            )
            ballot_returned.save()
            ballot_returned_id = ballot_returned.id
            ballot_returned_found = True
            messages.add_message(request, messages.INFO,
                                 'New ballot_returned saved.')

        # #######################################
        # Make sure we have saved a latitude and longitude for the ballot_returned entry
        if ballot_returned_found and positive_value_exists(
                ballot_returned.text_for_map_search):
            if not ballot_returned.latitude or not ballot_returned.longitude:
                google_client = get_geocoder_for_service('google')()
                location = google_client.geocode(
                    ballot_returned.text_for_map_search)
                if location is None:
                    status = 'Could not find location matching "{}"'.format(
                        ballot_returned.text_for_map_search)
                else:
                    ballot_returned.latitude = location.latitude
                    ballot_returned.longitude = location.longitude
                    ballot_returned.save()

        # #######################################
        # Now create new ballot_item entries

        # Contest Office 1
        ballot_item_manager = BallotItemManager()
        contest_office_manager = ContestOfficeManager()
        results = contest_office_manager.retrieve_contest_office(
            contest_office1_id)
        if results['contest_office_found']:
            contest_office = results['contest_office']
            ballot_item_display_name = contest_office.office_name

            google_ballot_placement = 0
            measure_subtitle = ''
            local_ballot_order = contest_office1_order if positive_value_exists(
                contest_office1_order) else 0

            results = ballot_item_manager.update_or_create_ballot_item_for_polling_location(
                polling_location.we_vote_id, google_civic_election_id,
                google_ballot_placement, ballot_item_display_name,
                measure_subtitle, local_ballot_order, contest_office.id,
                contest_office.we_vote_id)

            if results['new_ballot_item_created']:
                messages.add_message(request, messages.INFO, 'Office 1 added.')
            else:
                messages.add_message(request, messages.ERROR,
                                     'Office 1 could not be added.')

        # Contest Measure 1
        ballot_item_manager = BallotItemManager()
        contest_measure_manager = ContestMeasureManager()
        results = contest_measure_manager.retrieve_contest_measure(
            contest_measure1_id)
        if results['contest_measure_found']:
            contest_measure = results['contest_measure']

            google_ballot_placement = 0
            ballot_item_display_name = contest_measure.measure_title
            contest_office_id = 0
            contest_office_we_vote_id = ''
            local_ballot_order = 0

            ballot_item_manager.update_or_create_ballot_item_for_polling_location(
                polling_location.we_vote_id, google_civic_election_id,
                google_ballot_placement, ballot_item_display_name,
                contest_measure.measure_subtitle, local_ballot_order,
                contest_office_id, contest_office_we_vote_id,
                contest_measure.id)
    except Exception as e:
        messages.add_message(request, messages.ERROR,
                             'Could not save ballot_returned.')

    return HttpResponseRedirect(
        reverse('ballot:ballot_item_list_edit', args=(ballot_returned_id, )) +
        "?google_civic_election_id=" + str(google_civic_election_id) +
        "&polling_location_id=" + str(polling_location_id) +
        "&polling_location_city=" + polling_location_city +
        "&polling_location_zip=" + str(polling_location_zip))
コード例 #17
0
def ballot_item_list_edit_view(request, ballot_returned_id):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    # We can accept either, but give preference to polling_location_id
    polling_location_id = request.GET.get('polling_location_id', 0)
    polling_location_we_vote_id = request.GET.get(
        'polling_location_we_vote_id', '')
    polling_location_city = request.GET.get('polling_location_city', '')
    polling_location_zip = request.GET.get('polling_location_zip', '')

    ballot_returned_found = False
    ballot_returned = BallotReturned()

    ballot_returned_manager = BallotReturnedManager()
    results = ballot_returned_manager.retrieve_existing_ballot_returned_by_identifier(
        ballot_returned_id)
    if results['ballot_returned_found']:
        ballot_returned = results['ballot_returned']
        ballot_returned_found = True
        google_civic_election_id = ballot_returned.google_civic_election_id
    else:
        google_civic_election_id = request.GET.get('google_civic_election_id',
                                                   0)
        google_civic_election_id = convert_to_int(google_civic_election_id)

    election = Election()
    election_state = ''
    contest_measure_list = []
    contest_office_list = []
    if google_civic_election_id:
        election_manager = ElectionManager()
        results = election_manager.retrieve_election(google_civic_election_id)
        if results['election_found']:
            election = results['election']
            election_state = election.get_election_state()

        # Get a list of offices for this election so we can create drop downs
        try:
            contest_office_list = ContestOffice.objects.order_by('office_name')
            contest_office_list = contest_office_list.filter(
                google_civic_election_id=google_civic_election_id)
        except Exception as e:
            contest_office_list = []

        # Get a list of measures for this election so we can create drop downs
        try:
            contest_measure_list = ContestMeasure.objects.order_by(
                'measure_title')
            contest_measure_list = contest_measure_list.filter(
                google_civic_election_id=google_civic_election_id)
        except Exception as e:
            contest_measure_list = []
    else:
        messages.add_message(
            request, messages.ERROR,
            'In order to create a \'ballot_returned\' entry, '
            'a google_civic_election_id is required.')

    polling_location_found = False
    polling_location = PollingLocation()
    polling_location_manager = PollingLocationManager()
    if positive_value_exists(polling_location_id):
        results = polling_location_manager.retrieve_polling_location_by_id(
            polling_location_id)
        if results['polling_location_found']:
            polling_location = results['polling_location']
            polling_location_found = True
    if not polling_location_found and positive_value_exists(
            polling_location_we_vote_id):
        results = polling_location_manager.retrieve_polling_location_by_id(
            0, polling_location_we_vote_id)
        if results['polling_location_found']:
            polling_location = results['polling_location']
            polling_location_found = True

    polling_location_list = []
    if not polling_location_found:
        results = polling_location_manager.retrieve_polling_locations_in_city_or_state(
            election_state, polling_location_city, polling_location_zip)
        if results['polling_location_list_found']:
            polling_location_list = results['polling_location_list']

    messages_on_stage = get_messages(request)
    ballot_item_list = []
    if ballot_returned_found:
        # Get a list of ballot_items stored at this location
        ballot_item_list_manager = BallotItemListManager()
        if positive_value_exists(ballot_returned.polling_location_we_vote_id):
            results = ballot_item_list_manager.retrieve_all_ballot_items_for_polling_location(
                ballot_returned.polling_location_we_vote_id,
                google_civic_election_id)
            if results['ballot_item_list_found']:
                ballot_item_list = results['ballot_item_list']

    template_values = {
        'messages_on_stage': messages_on_stage,
        'ballot_returned': ballot_returned,
        'ballot_returned_id': ballot_returned_id,
        'election': election,
        'measure_list': contest_measure_list,
        'office_list': contest_office_list,
        'polling_location_we_vote_id': polling_location_we_vote_id,
        'polling_location_found': polling_location_found,
        'polling_location': polling_location,
        'polling_location_list': polling_location_list,
        'polling_location_city': polling_location_city,
        'polling_location_zip': polling_location_zip,
        'ballot_item_list': ballot_item_list,
        'google_civic_election_id': google_civic_election_id,
    }
    return render(request, 'ballot/ballot_item_list_edit.html',
                  template_values)
コード例 #18
0
def election_migration_view(request):
    authority_required = {'admin'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    messages_on_stage = get_messages(request)
    election_manager = ElectionManager()
    we_vote_election = Election()
    office_list_manager = ContestOfficeListManager()
    candidate_list_manager = CandidateCampaignListManager()
    position_list_manager = PositionListManager()
    we_vote_election_office_list = []
    google_civic_election_office_list = []

    results = election_manager.retrieve_we_vote_elections()
    we_vote_election_list = results['election_list']
    state_code_list = []
    for election in we_vote_election_list:
        if election.state_code not in state_code_list:
            state_code_list.append(election.state_code)

    google_civic_election = Election()
    results = election_manager.retrieve_google_civic_elections_in_state_list(
        state_code_list)
    google_civic_election_list = results['election_list']

    we_vote_election_id = convert_to_int(
        request.GET.get('we_vote_election_id', 0))
    if not positive_value_exists(we_vote_election_id):
        we_vote_election_id = convert_to_int(
            request.POST.get('we_vote_election_id', 0))
    if positive_value_exists(we_vote_election_id):
        results = election_manager.retrieve_election(we_vote_election_id)
        if results['election_found']:
            we_vote_election = results['election']

            return_list_of_objects = True
            results = office_list_manager.retrieve_all_offices_for_upcoming_election(
                we_vote_election_id, return_list_of_objects)
            if results['office_list_found']:
                we_vote_election_office_list = results['office_list_objects']

    # Go through each office and attach a list of candidates under this office
    we_vote_election_office_list_new = []
    for one_office in we_vote_election_office_list:
        candidate_results = candidate_list_manager.retrieve_all_candidates_for_office(
            0, one_office.we_vote_id)
        if candidate_results['candidate_list_found']:
            candidate_list = candidate_results['candidate_list']
            new_candidate_list = []
            # Go through candidate_list and find the number of positions saved for each candidate
            for candidate in candidate_list:
                retrieve_public_positions = True  # The alternate is positions for friends-only
                position_list = position_list_manager.retrieve_all_positions_for_candidate_campaign(
                    retrieve_public_positions, 0, candidate.we_vote_id)
                candidate.position_count = len(
                    position_list
                )  # This is wasteful (instead of using count), but ok

                # Now find the candidates from the Google Civic Election that we might want to transfer data to

                new_candidate_list.append(candidate)

            one_office.candidate_list = new_candidate_list
        else:
            one_office.candidate_list = []
        we_vote_election_office_list_new.append(one_office)

    google_civic_election_id = convert_to_int(
        request.GET.get('google_civic_election_id', 0))
    if not positive_value_exists(google_civic_election_id):
        google_civic_election_id = convert_to_int(
            request.POST.get('google_civic_election_id', 0))
    if positive_value_exists(google_civic_election_id):
        results = election_manager.retrieve_election(google_civic_election_id)
        if results['election_found']:
            google_civic_election = results['election']

            return_list_of_objects = True
            results = office_list_manager.retrieve_all_offices_for_upcoming_election(
                google_civic_election_id, return_list_of_objects)
            if results['office_list_found']:
                google_civic_election_office_list = results[
                    'office_list_objects']

    # We want to transfer the
    transfer_array = {}
    transfer_array['wv01off1461'] = "wv02off269"

    template_values = {
        'messages_on_stage': messages_on_stage,
        'we_vote_election': we_vote_election,
        'we_vote_election_id': we_vote_election_id,
        'we_vote_election_list': we_vote_election_list,
        'we_vote_election_office_list': we_vote_election_office_list_new,
        'google_civic_election': google_civic_election,
        'google_civic_election_id': google_civic_election_id,
        'google_civic_election_list': google_civic_election_list,
        'google_civic_election_office_list': google_civic_election_office_list,
    }

    return render(request, 'election/election_migration.html', template_values)
コード例 #19
0
def ballot_item_list_edit_view(request, ballot_returned_id):
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    # We can accept either, but give preference to polling_location_id
    polling_location_id = request.GET.get('polling_location_id', 0)
    polling_location_we_vote_id = request.GET.get('polling_location_we_vote_id', '')
    polling_location_city = request.GET.get('polling_location_city', '')
    polling_location_zip = request.GET.get('polling_location_zip', '')

    ballot_returned_found = False
    ballot_returned = BallotReturned()

    ballot_returned_manager = BallotReturnedManager()
    results = ballot_returned_manager.retrieve_existing_ballot_returned_by_identifier(ballot_returned_id)
    if results['ballot_returned_found']:
        ballot_returned = results['ballot_returned']
        ballot_returned_found = True
        google_civic_election_id = ballot_returned.google_civic_election_id
    else:
        google_civic_election_id = request.GET.get('google_civic_election_id', 0)
        google_civic_election_id = convert_to_int(google_civic_election_id)

    election = Election()
    election_state = ''
    contest_measure_list = []
    contest_office_list = []
    if google_civic_election_id:
        election_manager = ElectionManager()
        results = election_manager.retrieve_election(google_civic_election_id)
        if results['election_found']:
            election = results['election']
            election_state = election.get_election_state()

        # Get a list of offices for this election so we can create drop downs
        try:
            contest_office_list = ContestOffice.objects.order_by('office_name')
            contest_office_list = contest_office_list.filter(google_civic_election_id=google_civic_election_id)
        except Exception as e:
            contest_office_list = []

        # Get a list of measures for this election so we can create drop downs
        try:
            contest_measure_list = ContestMeasure.objects.order_by('measure_title')
            contest_measure_list = contest_measure_list.filter(google_civic_election_id=google_civic_election_id)
        except Exception as e:
            contest_measure_list = []
    else:
        messages.add_message(request, messages.ERROR, 'In order to create a \'ballot_returned\' entry, '
                                                      'a google_civic_election_id is required.')

    polling_location_found = False
    polling_location = PollingLocation()
    polling_location_manager = PollingLocationManager()
    if positive_value_exists(polling_location_id):
        results = polling_location_manager.retrieve_polling_location_by_id(polling_location_id)
        if results['polling_location_found']:
            polling_location = results['polling_location']
            polling_location_found = True
    if not polling_location_found and positive_value_exists(polling_location_we_vote_id):
        results = polling_location_manager.retrieve_polling_location_by_id(0, polling_location_we_vote_id)
        if results['polling_location_found']:
            polling_location = results['polling_location']
            polling_location_found = True

    polling_location_list = []
    if not polling_location_found:
        results = polling_location_manager.retrieve_polling_locations_in_city_or_state(
            election_state, polling_location_city, polling_location_zip)
        if results['polling_location_list_found']:
            polling_location_list = results['polling_location_list']

    messages_on_stage = get_messages(request)
    ballot_item_list = []
    if ballot_returned_found:
        # Get a list of ballot_items stored at this location
        ballot_item_list_manager = BallotItemListManager()
        if positive_value_exists(ballot_returned.polling_location_we_vote_id):
            results = ballot_item_list_manager.retrieve_all_ballot_items_for_polling_location(
                ballot_returned.polling_location_we_vote_id, google_civic_election_id)
            if results['ballot_item_list_found']:
                ballot_item_list = results['ballot_item_list']

    template_values = {
        'messages_on_stage':            messages_on_stage,
        'ballot_returned':              ballot_returned,
        'ballot_returned_id':           ballot_returned_id,
        'election':                     election,
        'measure_list':                 contest_measure_list,
        'office_list':                  contest_office_list,
        'polling_location_we_vote_id':  polling_location_we_vote_id,
        'polling_location_found':       polling_location_found,
        'polling_location':             polling_location,
        'polling_location_list':        polling_location_list,
        'polling_location_city':        polling_location_city,
        'polling_location_zip':         polling_location_zip,
        'ballot_item_list':             ballot_item_list,
        'google_civic_election_id':     google_civic_election_id,
    }
    return render(request, 'ballot/ballot_item_list_edit.html', template_values)
コード例 #20
0
ファイル: views_admin.py プロジェクト: trinile/WeVoteServer
def office_edit_process_view(request):
    """
    Process the new or edit office forms
    :param request:
    :return:
    """
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    office_id = convert_to_int(request.POST.get('office_id', 0))
    office_name = request.POST.get('office_name', False)
    google_civic_election_id = request.POST.get('google_civic_election_id', 0)
    primary_party = request.POST.get('primary_party', False)

    election_state = ''
    if google_civic_election_id:
        election_manager = ElectionManager()
        results = election_manager.retrieve_election(google_civic_election_id)
        if results['election_found']:
            election = results['election']
            election_state = election.get_election_state()

    # Check to see if this office is already in the database
    office_on_stage_found = False
    try:
        office_query = ContestOffice.objects.filter(id=office_id)
        if len(office_query):
            office_on_stage = office_query[0]
            office_on_stage_found = True
    except Exception as e:
        handle_record_not_found_exception(e, logger=logger)

    try:
        if office_on_stage_found:
            # Update
            if convert_to_int(office_on_stage.google_civic_election_id) >= 1000000 and office_name is not False:
                office_on_stage.office_name = office_name
            if convert_to_int(office_on_stage.google_civic_election_id) >= 1000000 and primary_party is not False:
                office_on_stage.primary_party = primary_party
            if positive_value_exists(election_state):
                office_on_stage.state_code = election_state
            office_on_stage.save()
            messages.add_message(request, messages.INFO, 'Office updated.')
            google_civic_election_id = office_on_stage.google_civic_election_id

            return HttpResponseRedirect(reverse('office:office_list', args=()) +
                                        "?google_civic_election_id=" + google_civic_election_id)
        else:
            # Create new
            office_on_stage = ContestOffice(
                office_name=office_name,
                google_civic_election_id=google_civic_election_id,
                state_code=election_state,
            )
            if convert_to_int(office_on_stage.google_civic_election_id) >= 1000000 and primary_party is not False:
                office_on_stage.primary_party = primary_party
            office_on_stage.save()
            messages.add_message(request, messages.INFO, 'New office saved.')

            # Come back to the "Create New Office" page
            new_office_id = 0
            return HttpResponseRedirect(reverse('office:office_new', args=()) +
                                        "?google_civic_election_id=" + google_civic_election_id)
    except Exception as e:
        handle_record_not_saved_exception(e, logger=logger)
        messages.add_message(request, messages.ERROR, 'Could not save office.')

    return HttpResponseRedirect(reverse('office:office_list', args=()) +
                                "?google_civic_election_id=" + google_civic_election_id)
コード例 #21
0
def ballot_item_list_edit_process_view(request):
    """
    Process the new or edit ballot form
    :param request:
    :return:
    """
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    ballot_returned_id = convert_to_int(request.POST.get('ballot_returned_id', 0))
    google_civic_election_id = request.POST.get('google_civic_election_id', 0)
    polling_location_id = convert_to_int(request.POST.get('polling_location_id', 0))
    polling_location_city = request.POST.get('polling_location_city', '')
    polling_location_zip = request.POST.get('polling_location_zip', '')
    contest_office1_id = request.POST.get('contest_office1_id', 0)
    contest_office1_order = request.POST.get('contest_office1_order', 0)
    contest_measure1_id = request.POST.get('contest_measure1_id', 0)

    election_local_id = 0

    # Find existing ballot_returned
    ballot_returned_found = False
    ballot_returned = BallotReturned()
    if positive_value_exists(ballot_returned_id):
        try:
            ballot_returned_query = BallotReturned.objects.filter(id=ballot_returned_id)
            if len(ballot_returned_query):
                ballot_returned = ballot_returned_query[0]
                ballot_returned_found = True
        except Exception as e:
            pass

    election_manager = ElectionManager()
    polling_location_manager = PollingLocationManager()
    polling_location = PollingLocation()
    polling_location_found = False
    try:
        if ballot_returned_found:
            # Update

            # Check to see if this is a We Vote-created election
            is_we_vote_google_civic_election_id = True \
                if convert_to_int(ballot_returned.google_civic_election_id) >= 1000000 \
                else False

            results = election_manager.retrieve_election(ballot_returned.google_civic_election_id)
            if results['election_found']:
                election = results['election']
                election_local_id = election.id

            # polling_location must be found
            # We cannot change a polling location once saved, so we ignore the incoming polling_location_id here
            results = polling_location_manager.retrieve_polling_location_by_id(
                0, ballot_returned.polling_location_we_vote_id)
            if results['polling_location_found']:
                polling_location = results['polling_location']
                polling_location_found = True
        else:
            # Create new ballot_returned entry
            # election must be found
            election_results = election_manager.retrieve_election(google_civic_election_id)
            if election_results['election_found']:
                election = election_results['election']
                election_local_id = election.id
                state_code = election.get_election_state()
            else:
                messages.add_message(request, messages.ERROR, 'Could not find election -- '
                                                              'required to save ballot_returned.')
                return HttpResponseRedirect(reverse('ballot:ballot_item_list_edit', args=(ballot_returned_id,)) +
                                            "?google_civic_election_id=" + str(google_civic_election_id) +
                                            "&polling_location_id=" + str(polling_location_id) +
                                            "&polling_location_city=" + polling_location_city +
                                            "&polling_location_zip=" + str(polling_location_zip)
                                            )

            # polling_location must be found
            if positive_value_exists(polling_location_id):
                results = polling_location_manager.retrieve_polling_location_by_id(polling_location_id)
                if results['polling_location_found']:
                    polling_location = results['polling_location']
                    polling_location_found = True

            if not polling_location_found:
                messages.add_message(request, messages.ERROR, 'Could not find polling_location -- '
                                                              'required to save ballot_returned.')
                return HttpResponseRedirect(reverse('ballot:ballot_item_list_edit', args=(ballot_returned_id,)) +
                                            "?google_civic_election_id=" + str(google_civic_election_id) +
                                            "&polling_location_id=" + str(polling_location_id) +
                                            "&polling_location_city=" + polling_location_city +
                                            "&polling_location_zip=" + str(polling_location_zip)
                                            )

            ballot_returned = BallotReturned(
                election_date=election.election_day_text,
                election_description_text=election.election_name,
                google_civic_election_id=google_civic_election_id,
                polling_location_we_vote_id=polling_location.we_vote_id,
                normalized_city=polling_location.city,
                normalized_line1=polling_location.line1,
                normalized_line2=polling_location.line2,
                normalized_state=polling_location.state,
                normalized_zip=polling_location.get_formatted_zip(),
                text_for_map_search=polling_location.get_text_for_map_search(),
            )
            ballot_returned.save()
            ballot_returned_id = ballot_returned.id
            ballot_returned_found = True
            messages.add_message(request, messages.INFO, 'New ballot_returned saved.')

        # #######################################
        # Make sure we have saved a latitude and longitude for the ballot_returned entry
        if ballot_returned_found and positive_value_exists(ballot_returned.text_for_map_search):
            if not ballot_returned.latitude or not ballot_returned.longitude:
                google_client = get_geocoder_for_service('google')()
                location = google_client.geocode(ballot_returned.text_for_map_search)
                if location is None:
                    status = 'Could not find location matching "{}"'.format(ballot_returned.text_for_map_search)
                else:
                    ballot_returned.latitude = location.latitude
                    ballot_returned.longitude = location.longitude
                    ballot_returned.save()

        # #######################################
        # Now create new ballot_item entries

        # Contest Office 1
        ballot_item_manager = BallotItemManager()
        contest_office_manager = ContestOfficeManager()
        results = contest_office_manager.retrieve_contest_office(contest_office1_id)
        if results['contest_office_found']:
            contest_office = results['contest_office']
            ballot_item_display_name = contest_office.office_name

            google_ballot_placement = 0
            measure_subtitle = ''
            local_ballot_order = contest_office1_order if positive_value_exists(contest_office1_order) else 0

            results = ballot_item_manager.update_or_create_ballot_item_for_polling_location(
                polling_location.we_vote_id, google_civic_election_id, google_ballot_placement,
                ballot_item_display_name, measure_subtitle, local_ballot_order,
                contest_office.id, contest_office.we_vote_id)

            if results['new_ballot_item_created']:
                messages.add_message(request, messages.INFO, 'Office 1 added.')
            else:
                messages.add_message(request, messages.ERROR, 'Office 1 could not be added.')

        # Contest Measure 1
        ballot_item_manager = BallotItemManager()
        contest_measure_manager = ContestMeasureManager()
        results = contest_measure_manager.retrieve_contest_measure(contest_measure1_id)
        if results['contest_measure_found']:
            contest_measure = results['contest_measure']

            google_ballot_placement = 0
            ballot_item_display_name = contest_measure.measure_title
            contest_office_id = 0
            contest_office_we_vote_id = ''
            local_ballot_order = 0

            ballot_item_manager.update_or_create_ballot_item_for_polling_location(
                polling_location.we_vote_id, google_civic_election_id, google_ballot_placement,
                ballot_item_display_name, contest_measure.measure_subtitle, local_ballot_order,
                contest_office_id, contest_office_we_vote_id,
                contest_measure.id)
    except Exception as e:
        messages.add_message(request, messages.ERROR, 'Could not save ballot_returned.')

    return HttpResponseRedirect(reverse('ballot:ballot_item_list_edit', args=(ballot_returned_id,)) +
                                "?google_civic_election_id=" + str(google_civic_election_id) +
                                "&polling_location_id=" + str(polling_location_id) +
                                "&polling_location_city=" + polling_location_city +
                                "&polling_location_zip=" + str(polling_location_zip)
                                )
コード例 #22
0
def voter_ballot_items_retrieve_for_api(voter_device_id, google_civic_election_id):
    status = ''

    # We retrieve voter_device_link
    voter_device_link_manager = VoterDeviceLinkManager()
    voter_device_link_results = voter_device_link_manager.retrieve_voter_device_link(voter_device_id)
    if not voter_device_link_results['voter_device_link_found']:
        status += "VALID_VOTER_DEVICE_ID_MISSING "
        error_json_data = {
            'status':                       status,
            'success':                      False,
            'voter_device_id':              voter_device_id,
            'ballot_found':                 False,
            'ballot_item_list':             [],
            'google_civic_election_id':     google_civic_election_id,
            'text_for_map_search':          '',
            'substituted_address_nearby':   '',
            'ballot_caveat':                '',
            'is_from_substituted_address':  False,
            'is_from_test_ballot':          False,
        }
        return error_json_data

    voter_device_link = voter_device_link_results['voter_device_link']
    voter_id = voter_device_link.voter_id

    if not positive_value_exists(voter_id):
        status += " " + "VALID_VOTER_ID_MISSING"
        error_json_data = {
            'status':                       status,
            'success':                      False,
            'voter_device_id':              voter_device_id,
            'ballot_found':                 False,
            'ballot_item_list':             [],
            'google_civic_election_id':     google_civic_election_id,
            'text_for_map_search':          '',
            'substituted_address_nearby':   '',
            'ballot_caveat':                '',
            'is_from_substituted_address':  False,
            'is_from_test_ballot':          False,
        }
        return error_json_data

    voter_address_manager = VoterAddressManager()
    voter_address_id = 0
    address_type = BALLOT_ADDRESS
    voter_address_results = voter_address_manager.retrieve_address(voter_address_id, voter_id, address_type)
    status += " " + voter_address_results['status']
    if not positive_value_exists(voter_address_results['voter_address_has_value']):
        error_json_data = {
            'status':                       status,
            'success':                      voter_address_results['success'],
            'voter_device_id':              voter_device_id,
            'ballot_found':                 False,
            'ballot_item_list':             [],
            'google_civic_election_id':     0,
            'text_for_map_search':          '',
            'substituted_address_nearby':   '',
            'ballot_caveat':                '',
            'is_from_substituted_address':  False,
            'is_from_test_ballot':          False,
        }
        return error_json_data

    voter_address = voter_address_results['voter_address']

    results = choose_election_and_prepare_ballot_data(voter_device_link, google_civic_election_id, voter_address)
    status += " " + results['status']
    if not results['voter_ballot_saved_found']:
        if positive_value_exists(voter_address.text_for_map_search):
            ballot_caveat = "We could not find a ballot near '{text_for_map_search}'.".format(
                text_for_map_search=voter_address.text_for_map_search)
        else:
            ballot_caveat = "Please save your address so we can find your ballot."

        error_json_data = {
            'status':                       status,
            'success':                      True,
            'voter_device_id':              voter_device_id,
            'ballot_found':                 False,
            'ballot_item_list':             [],
            'google_civic_election_id':     0,
            'text_for_map_search':          voter_address.text_for_map_search,
            'substituted_address_nearby':   '',
            'ballot_caveat':                ballot_caveat,
            'is_from_substituted_address':  False,
            'is_from_test_ballot':          False,
        }
        return error_json_data

    google_civic_election_id = results['google_civic_election_id']
    voter_ballot_saved = results['voter_ballot_saved']

    # Update voter_device_link
    if voter_device_link.google_civic_election_id != google_civic_election_id:
        voter_device_link_manager.update_voter_device_link_with_election_id(voter_device_link, google_civic_election_id)

    # Update voter_address to include matching google_civic_election_id and voter_ballot_saved entry
    if positive_value_exists(google_civic_election_id):
        voter_address.google_civic_election_id = google_civic_election_id
        voter_address_manager.update_existing_voter_address_object(voter_address)

        # Get and return the ballot_item_list
        results = voter_ballot_items_retrieve_for_one_election_for_api(voter_device_id, voter_id,
                                                                       google_civic_election_id)

        if not positive_value_exists(voter_ballot_saved.election_description_text) \
                or not positive_value_exists(voter_ballot_saved.election_date_text()):
            try:
                election_manager = ElectionManager()
                election_results = election_manager.retrieve_election(google_civic_election_id)
                if election_results['election_found']:
                    election = election_results['election']
                    if not positive_value_exists(voter_ballot_saved.election_description_text):
                        voter_ballot_saved.election_description_text = election.election_name
                    if not positive_value_exists(voter_ballot_saved.election_date_text()):
                        voter_ballot_saved.election_date = \
                            datetime.strptime(election.election_day_text, "%Y-%m-%d").date()
                    voter_ballot_saved.save()
            except Exception as e:
                status += "Failed to update election_name"

        status += " " + results['status']
        json_data = {
            'status':                       status,
            'success':                      True,
            'voter_device_id':              voter_device_id,
            'ballot_found':                 True,
            'ballot_item_list':             results['ballot_item_list'],
            'google_civic_election_id':     google_civic_election_id,
            'election_name':                voter_ballot_saved.election_description_text,
            'election_date':                voter_ballot_saved.election_date_text(),
            'text_for_map_search':          voter_ballot_saved.original_text_for_map_search,
            'substituted_address_nearby':   voter_ballot_saved.substituted_address_nearby,
            'ballot_caveat':                voter_ballot_saved.ballot_caveat(),
            'is_from_substituted_address':  voter_ballot_saved.is_from_substituted_address,
            'is_from_test_ballot':          voter_ballot_saved.is_from_test_ballot,
        }
        return json_data

    status += " " + "NO_VOTER_BALLOT_SAVED_FOUND"
    error_json_data = {
        'status':                       status,
        'success':                      True,
        'voter_device_id':              voter_device_id,
        'ballot_found':                 False,
        'ballot_item_list':             [],
        'google_civic_election_id':     0,
        'text_for_map_search':          '',
        'substituted_address_nearby':   '',
        'ballot_caveat':                '',
        'is_from_substituted_address':  False,
        'is_from_test_ballot':          False,
    }
    return error_json_data
コード例 #23
0
def organization_edit_process_view(request):
    """
    Process the new or edit organization forms
    :param request:
    :return:
    """
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    organization_id = convert_to_int(request.POST.get('organization_id', 0))
    organization_name = request.POST.get('organization_name', '')
    organization_twitter_handle = request.POST.get('organization_twitter_handle', False)
    organization_facebook = request.POST.get('organization_facebook', False)
    organization_website = request.POST.get('organization_website', False)
    wikipedia_page_title = request.POST.get('wikipedia_page_title', False)
    wikipedia_photo_url = request.POST.get('wikipedia_photo_url', False)
    state_served_code = request.POST.get('state_served_code', False)

    # A positive value in google_civic_election_id or add_organization_button means we want to create a voter guide
    # for this org for this election
    google_civic_election_id = request.POST.get('google_civic_election_id', 0)
    # add_organization_button = request.POST.get('add_organization_button', False)

    # Filter incoming data
    organization_twitter_handle = extract_twitter_handle_from_text_string(organization_twitter_handle)

    # Check to see if this organization is already being used anywhere
    organization_on_stage_found = False
    try:
        organization_query = Organization.objects.filter(id=organization_id)
        if organization_query.count():
            organization_on_stage = organization_query[0]
            organization_on_stage_found = True
    except Exception as e:
        handle_record_not_found_exception(e, logger=logger)

    try:
        if organization_on_stage_found:
            # Update
            if organization_name is not False:
                organization_on_stage.organization_name = organization_name
            if organization_twitter_handle is not False:
                organization_on_stage.organization_twitter_handle = organization_twitter_handle
            if organization_facebook is not False:
                organization_on_stage.organization_facebook = organization_facebook
            if organization_website is not False:
                organization_on_stage.organization_website = organization_website
            if wikipedia_page_title is not False:
                organization_on_stage.wikipedia_page_title = wikipedia_page_title
            if wikipedia_photo_url is not False:
                organization_on_stage.wikipedia_photo_url = wikipedia_photo_url
            if state_served_code is not False:
                organization_on_stage.state_served_code = state_served_code
            organization_on_stage.save()
            organization_id = organization_on_stage.id
            organization_we_vote_id = organization_on_stage.we_vote_id
            messages.add_message(request, messages.INFO, 'Organization updated.')
        else:
            # Create new

            # But first double-check that we don't have an org entry already
            organization_email = ''
            organization_list_manager = OrganizationListManager()
            results = organization_list_manager.organization_search_find_any_possibilities(
                organization_name, organization_twitter_handle, organization_website, organization_email)

            if results['organizations_found']:
                organizations_list = results['organizations_list']
                organizations_count = len(organizations_list)

                messages.add_message(request, messages.INFO, 'We found {count} existing organizations '
                                                             'that might match.'.format(count=organizations_count))
                messages_on_stage = get_messages(request)
                template_values = {
                    'messages_on_stage':            messages_on_stage,
                    'organizations_list':           organizations_list,
                    'organization_name':            organization_name,
                    'organization_twitter_handle':  organization_twitter_handle,
                    'organization_facebook':        organization_facebook,
                    'organization_website':         organization_website,
                    'wikipedia_page_title':         wikipedia_page_title,
                    'wikipedia_photo_url':          wikipedia_photo_url,
                }
                return render(request, 'organization/organization_edit.html', template_values)

            minimum_required_variables_exist = positive_value_exists(organization_name)
            if not minimum_required_variables_exist:
                messages.add_message(request, messages.INFO, 'Missing name, which is required.')
                messages_on_stage = get_messages(request)
                template_values = {
                    'messages_on_stage':            messages_on_stage,
                    'organization_name':            organization_name,
                    'organization_twitter_handle':  organization_twitter_handle,
                    'organization_facebook':        organization_facebook,
                    'organization_website':         organization_website,
                    'wikipedia_page_title':         wikipedia_page_title,
                    'wikipedia_photo_url':          wikipedia_photo_url,
                }
                return render(request, 'voter_guide/voter_guide_search.html', template_values)

            organization_on_stage = Organization(
                organization_name=organization_name,
            )
            if organization_twitter_handle is not False:
                organization_on_stage.organization_twitter_handle = organization_twitter_handle
            if organization_facebook is not False:
                organization_on_stage.organization_facebook = organization_facebook
            if organization_website is not False:
                organization_on_stage.organization_website = organization_website
            if wikipedia_page_title is not False:
                organization_on_stage.wikipedia_page_title = wikipedia_page_title
            if wikipedia_photo_url is not False:
                organization_on_stage.wikipedia_photo_url = wikipedia_photo_url
            if state_served_code is not False:
                organization_on_stage.state_served_code = state_served_code
            organization_on_stage.save()
            organization_id = organization_on_stage.id
            organization_we_vote_id = organization_on_stage.we_vote_id
            messages.add_message(request, messages.INFO, 'New organization saved.')
    except Exception as e:
        messages.add_message(request, messages.ERROR, 'Could not save organization.'
                                                      ' {error} [type: {error_type}]'.format(error=e,
                                                                                             error_type=type(e)))
        return HttpResponseRedirect(reverse('organization:organization_list', args=()))

    # Create voter_guide for this election?
    if positive_value_exists(google_civic_election_id) and positive_value_exists(organization_we_vote_id):
        election_manager = ElectionManager()
        results = election_manager.retrieve_election(google_civic_election_id)
        if results['election_found']:
            election = results['election']
            voter_guide_manager = VoterGuideManager()
            results = voter_guide_manager.update_or_create_organization_voter_guide_by_election_id(
                organization_we_vote_id, google_civic_election_id)
            if results['voter_guide_saved']:
                messages.add_message(request, messages.INFO, 'Voter guide for {election_name} election saved.'
                                                             ''.format(election_name=election.election_name))

    return HttpResponseRedirect(reverse('organization:organization_position_list', args=(organization_id,)) +
                                "?google_civic_election_id=" + str(google_civic_election_id))
コード例 #24
0
ファイル: views_admin.py プロジェクト: trinile/WeVoteServer
def candidate_edit_process_view(request):
    """
    Process the new or edit candidate forms
    :param request:
    :return:
    """
    authority_required = {'verified_volunteer'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    candidate_id = convert_to_int(request.POST['candidate_id'])
    candidate_name = request.POST.get('candidate_name', False)
    candidate_twitter_handle = request.POST.get('candidate_twitter_handle', False)
    if positive_value_exists(candidate_twitter_handle):
        candidate_twitter_handle = extract_twitter_handle_from_text_string(candidate_twitter_handle)
    candidate_url = request.POST.get('candidate_url', False)
    contest_office_id = request.POST.get('contest_office_id', False)
    ballot_guide_official_statement = request.POST.get('ballot_guide_official_statement', False)
    party = request.POST.get('party', False)

    remove_duplicate_process = request.POST.get('remove_duplicate_process', False)
    google_civic_election_id = request.POST.get('google_civic_election_id', 0)

    # Check to see if this candidate is already being used anywhere
    candidate_on_stage_found = False
    candidate_on_stage = CandidateCampaign()
    if positive_value_exists(candidate_id):
        try:
            candidate_query = CandidateCampaign.objects.filter(id=candidate_id)
            if len(candidate_query):
                candidate_on_stage = candidate_query[0]
                candidate_on_stage_found = True
        except Exception as e:
            handle_record_not_found_exception(e, logger=logger)

    contest_office_we_vote_id = ''
    if positive_value_exists(contest_office_id):
        contest_office_manager = ContestOfficeManager()
        results = contest_office_manager.retrieve_contest_office_from_id(contest_office_id)
        if results['contest_office_found']:
            contest_office = results['contest_office']
            contest_office_we_vote_id = contest_office.we_vote_id

    try:
        if candidate_on_stage_found:
            # Update
            if candidate_twitter_handle is not False:
                candidate_on_stage.candidate_twitter_handle = candidate_twitter_handle
            if candidate_url is not False:
                candidate_on_stage.candidate_url = candidate_url
            if ballot_guide_official_statement is not False:
                candidate_on_stage.ballot_guide_official_statement = ballot_guide_official_statement
            if party is not False:
                candidate_on_stage.party = party

            # Check to see if this is a We Vote-created election
            # is_we_vote_google_civic_election_id = True \
            #     if convert_to_int(candidate_on_stage.google_civic_election_id) >= 1000000 \
            #     else False

            if contest_office_id is not False:
                # We only allow updating of candidates within the We Vote Admin in
                candidate_on_stage.contest_office_id = contest_office_id
                candidate_on_stage.contest_office_we_vote_id = contest_office_we_vote_id
            candidate_on_stage.save()
            messages.add_message(request, messages.INFO, 'Candidate Campaign updated.')
        else:
            # Create new
            # election must be found
            election_manager = ElectionManager()
            election_results = election_manager.retrieve_election(google_civic_election_id)
            if election_results['election_found']:
                election = election_results['election']
                state_code = election.get_election_state()
            else:
                messages.add_message(request, messages.ERROR, 'Could not find election -- required to save candidate.')
                return HttpResponseRedirect(reverse('candidate:candidate_edit', args=(candidate_id,)))

            required_candidate_variables = True \
                if positive_value_exists(candidate_name) and positive_value_exists(contest_office_id) \
                else False
            if required_candidate_variables:
                candidate_on_stage = CandidateCampaign(
                    candidate_name=candidate_name,
                    google_civic_election_id=google_civic_election_id,
                    contest_office_id=contest_office_id,
                    contest_office_we_vote_id=contest_office_we_vote_id,
                    state_code=state_code,
                )
                if candidate_twitter_handle is not False:
                    candidate_on_stage.candidate_twitter_handle = candidate_twitter_handle
                if candidate_url is not False:
                    candidate_on_stage.candidate_url = candidate_url
                if ballot_guide_official_statement is not False:
                    candidate_on_stage.ballot_guide_official_statement = ballot_guide_official_statement
                if party is not False:
                    candidate_on_stage.party = party
                candidate_on_stage.save()
                candidate_id = candidate_on_stage.id
                messages.add_message(request, messages.INFO, 'New candidate saved.')
            else:
                messages.add_message(request, messages.INFO, 'Could not save -- missing required variables.')
                if positive_value_exists(candidate_id):
                    return HttpResponseRedirect(reverse('candidate:candidate_edit', args=(candidate_id,)) +
                                                "?google_civic_election_id=" + str(google_civic_election_id) +
                                                "&contest_office_id=" + str(contest_office_id)
                                                )
                else:
                    return HttpResponseRedirect(reverse('candidate:candidate_new', args=()) +
                                                "?google_civic_election_id=" + str(google_civic_election_id) +
                                                "&contest_office_id=" + str(contest_office_id)
                                                )

    except Exception as e:
        handle_record_not_saved_exception(e, logger=logger)
        messages.add_message(request, messages.ERROR, 'Could not save candidate.')
        return HttpResponseRedirect(reverse('candidate:candidate_edit', args=(candidate_id,)))

    if remove_duplicate_process:
        return HttpResponseRedirect(reverse('candidate:find_and_remove_duplicate_candidates', args=()) +
                                    "?google_civic_election_id=" + str(google_civic_election_id))
    else:
        return HttpResponseRedirect(reverse('candidate:candidate_edit', args=(candidate_id,)))