示例#1
0
    def update_voter_photos(self, voter_id, facebook_profile_image_url_https, facebook_photo_variable_exists):
        results = self.retrieve_voter(voter_id)

        if results["voter_found"]:
            voter = results["voter"]

            try:
                if facebook_photo_variable_exists:
                    voter.facebook_profile_image_url_https = facebook_profile_image_url_https
                voter.save()
                status = "SAVED_VOTER_PHOTOS"
                success = True
            except Exception as e:
                status = "UNABLE_TO_SAVE_VOTER_PHOTOS"
                success = False
                handle_record_not_saved_exception(e, logger=logger, exception_message_optional=status)

        else:
            # If here, we were unable to find pre-existing Voter
            status = "UNABLE_TO_FIND_VOTER_FOR_UPDATE_VOTER_PHOTOS"
            voter = Voter()
            success = False

        results = {"status": status, "success": success, "voter": voter}
        return results
示例#2
0
def polling_location_edit_process_view(request):
    """
    Process the new or edit polling_location forms
    :param request:
    :return:
    """
    polling_location_id = convert_to_int(request.POST['polling_location_id'])
    polling_location_name = request.POST['polling_location_name']

    # Check to see if this polling_location is already being used anywhere
    polling_location_on_stage_found = False
    try:
        polling_location_query = PollingLocation.objects.filter(id=polling_location_id)
        if len(polling_location_query):
            polling_location_on_stage = polling_location_query[0]
            polling_location_on_stage_found = True
    except Exception as e:
        handle_record_not_found_exception(e, logger=logger)

    try:
        if polling_location_on_stage_found:
            # Update
            polling_location_on_stage.polling_location_name = polling_location_name
            polling_location_on_stage.save()
            messages.add_message(request, messages.INFO, 'PollingLocation updated.')
        else:
            # Create new
            messages.add_message(request, messages.INFO, 'We do not support adding new polling locations.')
    except Exception as e:
        handle_record_not_saved_exception(e, logger=logger)
        messages.add_message(request, messages.ERROR, 'Could not save polling_location.')

    return HttpResponseRedirect(reverse('polling_location:polling_location_list', args=()))
示例#3
0
    def save_twitter_user_values(self, voter, twitter_user_object):
        try:
            # 'id': 132728535,
            voter.twitter_id = twitter_user_object.id
            # 'id_str': '132728535',
            # 'utc_offset': 32400,
            # 'description': "Cars, Musics, Games, Electronics, toys, food, etc... I'm just a typical boy!",
            # 'profile_image_url': 'http://a1.twimg.com/profile_images/1213351752/_2_2__normal.jpg',
            voter.twitter_profile_image_url_https = twitter_user_object.profile_image_url_https
            # 'profile_background_image_url': 'http://a2.twimg.com/a/1294785484/images/themes/theme15/bg.png',
            # 'screen_name': 'jaeeeee',
            voter.twitter_screen_name = twitter_user_object.screen_name
            # 'lang': 'en',
            # 'name': 'Jae Jung Chung',
            # 'url': 'http://www.carbonize.co.kr',
            # 'time_zone': 'Seoul',
            voter.save()
            success = True
            status = "SAVED_VOTER_TWITTER_VALUES"
        except Exception as e:
            status = "UNABLE_TO_SAVE_VOTER_TWITTER_VALUES"
            success = False
            handle_record_not_saved_exception(e, logger=logger, exception_message_optional=status)

        results = {"status": status, "success": success, "voter": voter}
        return results
示例#4
0
    def toggle_voter_following_organization(self, voter_id, organization_id, following_status):
        # Does a follow_organization entry exist from this voter already exist?
        follow_organization_manager = FollowOrganizationManager()
        results = follow_organization_manager.retrieve_follow_organization(0, voter_id, organization_id)

        follow_organization_on_stage_found = False
        follow_organization_on_stage_id = 0
        follow_organization_on_stage = FollowOrganization()
        if results['follow_organization_found']:
            follow_organization_on_stage = results['follow_organization']

            # Update this follow_organization entry with new values - we do not delete because we might be able to use
            try:
                follow_organization_on_stage.following_status = following_status
                # We don't need to update here because set set auto_now=True in the field
                # follow_organization_on_stage.date_last_changed =
                follow_organization_on_stage.save()
                follow_organization_on_stage_id = follow_organization_on_stage.id
                follow_organization_on_stage_found = True
                status = 'UPDATE ' + following_status
            except Exception as e:
                status = 'FAILED_TO_UPDATE ' + following_status
                handle_record_not_saved_exception(e, logger=logger, exception_message_optional=status)
        elif results['MultipleObjectsReturned']:
            logger.warn("follow_organization: delete all but one and take it over?")
            status = 'TOGGLE_FOLLOWING MultipleObjectsReturned ' + following_status
        elif results['DoesNotExist']:
            try:
                # Create new follow_organization entry
                # First make sure that organization_id is for a valid organization
                organization_manager = OrganizationManager()
                results = organization_manager.retrieve_organization(organization_id)
                if results['organization_found']:
                    follow_organization_on_stage = FollowOrganization(
                        voter_id=voter_id,
                        organization_id=organization_id,
                        following_status=following_status,
                        # We don't need to update here because set set auto_now=True in the field
                        # date_last_changed =
                    )
                    follow_organization_on_stage.save()
                    follow_organization_on_stage_id = follow_organization_on_stage.id
                    follow_organization_on_stage_found = True
                    status = 'CREATE ' + following_status
                else:
                    status = 'ORGANIZATION_NOT_FOUND_ON_CREATE ' + following_status
            except Exception as e:
                status = 'FAILED_TO_UPDATE ' + following_status
                handle_record_not_saved_exception(e, logger=logger, exception_message_optional=status)
        else:
            status = results['status']

        results = {
            'success':                      True if follow_organization_on_stage_found else False,
            'status':                       status,
            'follow_organization_found':    follow_organization_on_stage_found,
            'follow_organization_id':       follow_organization_on_stage_id,
            'follow_organization':          follow_organization_on_stage,
        }
        return results
示例#5
0
def election_edit_process_view(request):
    """
    Process the new or edit election forms
    :param request:
    :return:
    """
    election_id = convert_to_int(request.POST["election_id"])
    election_name = request.POST["election_name"]

    # Check to see if this election is already being used anywhere
    election_on_stage_found = False
    try:
        election_query = Election.objects.filter(id=election_id)
        if len(election_query):
            election_on_stage = election_query[0]
            election_on_stage_found = True
    except Exception as e:
        handle_record_not_found_exception(e, logger=logger)

    try:
        if election_on_stage_found:
            # Update
            election_on_stage.election_name = election_name
            election_on_stage.save()
            messages.add_message(request, messages.INFO, "Election updated.")
        else:
            # Create new
            election_on_stage = Election(election_name=election_name)
            election_on_stage.save()
            messages.add_message(request, messages.INFO, "New election saved.")
    except Exception as e:
        handle_record_not_saved_exception(e, logger=logger)
        messages.add_message(request, messages.ERROR, "Could not save election.")

    return HttpResponseRedirect(reverse("election:election_list", args=()))
示例#6
0
 def create_organization(
     self,
     organization_name,
     organization_website,
     organization_twitter_handle,
     organization_email="",
     organization_facebook="",
     organization_image="",
 ):
     try:
         organization = self.create(
             organization_name=organization_name,
             organization_website=organization_website,
             organization_twitter_handle=organization_twitter_handle,
             organization_email=organization_email,
             organization_facebook=organization_facebook,
             organization_image=organization_image,
         )
         status = "CREATE_ORGANIZATION_SUCCESSFUL"
         success = True
     except Exception as e:
         handle_record_not_saved_exception(e, logger=logger)
         organization = Organization
         status = "CREATE_ORGANIZATION_FAILED"
         success = False
     results = {"success": success, "status": status, "organization": organization}
     return results
示例#7
0
    def save_facebook_user_values(self, voter, facebook_id, facebook_email=''):
        try:
            if facebook_id == 0:
                voter.facebook_id = 0
            elif positive_value_exists(facebook_id):
                voter.facebook_id = facebook_id

            if facebook_email == '' or facebook_email is False:
                voter.facebook_email = ''
            elif positive_value_exists(facebook_email):
                voter.facebook_email = facebook_email

            voter.save()
            success = True
            status = "SAVED_VOTER_FACEBOOK_VALUES"
        except Exception as e:
            status = "UNABLE_TO_SAVE_VOTER_FACEBOOK_VALUES"
            success = False
            handle_record_not_saved_exception(e, logger=logger, exception_message_optional=status)

        results = {
            'status':   status,
            'success':  success,
            'voter':    voter,
        }
        return results
示例#8
0
    def update_voter_address_with_normalized_values(self, voter_id, voter_address_dict):
        voter_address_id = 0
        address_type = BALLOT_ADDRESS
        results = self.retrieve_address(voter_address_id, voter_id, address_type)

        if results['success']:
            voter_address = results['voter_address']

            try:
                voter_address.normalized_line1 = voter_address_dict['line1']
                voter_address.normalized_city = voter_address_dict['city']
                voter_address.normalized_state = voter_address_dict['state']
                voter_address.normalized_zip = voter_address_dict['zip']
                voter_address.save()
                status = "SAVED_VOTER_ADDRESS_WITH_NORMALIZED_VALUES"
                success = True
            except Exception as e:
                status = "UNABLE_TO_SAVE_VOTER_ADDRESS_WITH_NORMALIZED_VALUES"
                success = False
                handle_record_not_saved_exception(e, logger=logger, exception_message_optional=status)

        else:
            # If here, we were unable to find pre-existing VoterAddress
            voter_address = VoterAddress()  # TODO DALE Finish this for "create new"

        results = {
            'status':   status,
            'success':  success,
            'voter_address': voter_address,
        }
        return results
示例#9
0
    def update_existing_voter_address_object(self, voter_address_object):
        results = self.retrieve_address(voter_address_object.id)

        if results['success']:
            try:
                voter_address_object.save()  # Save the incoming object
                status = "UPDATED_EXISTING_VOTER_ADDRESS"
                success = True
                voter_address_found = True
            except Exception as e:
                status = "UNABLE_TO_UPDATE_EXISTING_VOTER_ADDRESS"
                success = False
                voter_address_found = False
                handle_record_not_saved_exception(e, logger=logger, exception_message_optional=status)
        else:
            # If here, we were unable to find pre-existing VoterAddress
            status = "UNABLE_TO_FIND_AND_UPDATE_VOTER_ADDRESS"
            voter_address_object = None
            success = False
            voter_address_found = False

        results = {
            'status':               status,
            'success':              success,
            'voter_address':        voter_address_object,
            'voter_address_found':  voter_address_found,
        }
        return results
示例#10
0
    def save_new_voter_device_link(self, voter_device_id, voter_id):
        error_result = False
        exception_record_not_saved = False
        missing_required_variables = False
        voter_device_link_on_stage = VoterDeviceLink()
        voter_device_link_id = 0

        try:
            if voter_device_id is not '' and voter_id > 0:
                voter_device_link_on_stage.voter_device_id = voter_device_id
                voter_device_link_on_stage.voter_id = voter_id
                voter_device_link_on_stage.save()

                voter_device_link_id = voter_device_link_on_stage.id
            else:
                missing_required_variables = True
                voter_device_link_id = 0
        except Exception as e:
            handle_record_not_saved_exception(e, logger=logger)
            error_result = True
            exception_record_not_saved = True

        results = {
            'error_result': error_result,
            'missing_required_variables': missing_required_variables,
            'RecordNotSaved': exception_record_not_saved,
            'voter_device_link_created':
            True if voter_device_link_id > 0 else False,
            'voter_device_link': voter_device_link_on_stage,
        }
        return results
示例#11
0
    def create_voter(self, email=None, password=None):
        email = self.normalize_email(email)
        email_not_valid = False
        password_not_valid = False

        voter = Voter()
        voter_id = 0
        try:
            if validate_email(email):
                voter.email = email
            else:
                email_not_valid = True

            if password:
                voter.set_password(password)
            else:
                password_not_valid = True
            voter.save()
            voter_id = voter.id
        except Exception as e:
            handle_record_not_saved_exception(e, logger=logger)

        results = {
            'email_not_valid':      email_not_valid,
            'password_not_valid':   password_not_valid,
            'voter_created':        True if voter_id > 0 else False,
            'voter':                voter,
        }
        return results
示例#12
0
    def save_new_voter_device_link(self, voter_device_id, voter_id):
        error_result = False
        exception_record_not_saved = False
        missing_required_variables = False
        voter_device_link_on_stage = VoterDeviceLink()
        voter_device_link_id = 0

        try:
            if voter_device_id is not '' and voter_id > 0:
                voter_device_link_on_stage.voter_device_id = voter_device_id
                voter_device_link_on_stage.voter_id = voter_id
                voter_device_link_on_stage.save()

                voter_device_link_id = voter_device_link_on_stage.id
            else:
                missing_required_variables = True
                voter_device_link_id = 0
        except Exception as e:
            handle_record_not_saved_exception(e, logger=logger)
            error_result = True
            exception_record_not_saved = True

        results = {
            'error_result':                 error_result,
            'missing_required_variables':   missing_required_variables,
            'RecordNotSaved':               exception_record_not_saved,
            'voter_device_link_created':    True if voter_device_link_id > 0 else False,
            'voter_device_link':            voter_device_link_on_stage,
        }
        return results
示例#13
0
def voter_edit_process_view(request):
    """
    Process the new or edit voter forms
    :param request:
    :return:
    """
    voter_id = convert_to_int(request.POST['voter_id'])
    voter_name = request.POST['voter_name']

    # Check to see if this voter is already being used anywhere
    voter_on_stage_found = False
    try:
        voter_query = Voter.objects.filter(id=voter_id)
        if len(voter_query):
            voter_on_stage = voter_query[0]
            voter_on_stage_found = True
    except Exception as e:
        handle_record_not_found_exception(e, logger=logger)

    try:
        if voter_on_stage_found:
            # Update
            voter_on_stage.voter_name = voter_name
            voter_on_stage.save()
            messages.add_message(request, messages.INFO, 'Voter updated.')
        else:
            # Create new
            messages.add_message(request, messages.INFO, 'We do not support adding new Voters.')
    except Exception as e:
        handle_record_not_saved_exception(e, logger=logger)
        messages.add_message(request, messages.ERROR, 'Could not save voter.')

    return HttpResponseRedirect(reverse('voter:voter_list', args=()))
示例#14
0
    def update_voter_address_with_normalized_values(self, voter_id, voter_address_dict):
        voter_address_id = 0
        address_type = BALLOT_ADDRESS
        results = self.retrieve_address(voter_address_id, voter_id, address_type)

        if results["success"]:
            voter_address = results["voter_address"]

            try:
                voter_address.normalized_line1 = voter_address_dict["line1"]
                voter_address.normalized_city = voter_address_dict["city"]
                voter_address.normalized_state = voter_address_dict["state"]
                voter_address.normalized_zip = voter_address_dict["zip"]
                voter_address.refreshed_from_google = True
                voter_address.save()
                status = "SAVED_VOTER_ADDRESS_WITH_NORMALIZED_VALUES"
                success = True
            except Exception as e:
                status = "UNABLE_TO_SAVE_VOTER_ADDRESS_WITH_NORMALIZED_VALUES"
                success = False
                handle_record_not_saved_exception(e, logger=logger, exception_message_optional=status)

        else:
            # If here, we were unable to find pre-existing VoterAddress
            status = "UNABLE_TO_FIND_VOTER_ADDRESS"
            voter_address = VoterAddress()  # TODO Finish this for "create new" case
            success = False

        results = {"status": status, "success": success, "voter_address": voter_address}
        return results
示例#15
0
    def create_voter(self, email=None, password=None):
        email = self.normalize_email(email)
        email_not_valid = False
        password_not_valid = False

        voter = Voter()
        voter_id = 0
        try:
            if validate_email(email):
                voter.email = email
            else:
                email_not_valid = True

            if password:
                voter.set_password(password)
            else:
                password_not_valid = True
            voter.save()
            voter_id = voter.id
        except Exception as e:
            handle_record_not_saved_exception(e, logger=logger)

        results = {
            'email_not_valid': email_not_valid,
            'password_not_valid': password_not_valid,
            'voter_created': True if voter_id > 0 else False,
            'voter': voter,
        }
        return results
示例#16
0
文件: models.py 项目: zvxr/WeVoteBase
    def save_setting(self, setting_name, setting_value, value_type=None):
        accepted_value_types = ["bool", "int", "str"]

        if value_type is None:
            if type(setting_value).__name__ == "bool":
                value_type = WeVoteSetting.BOOLEAN
            elif type(setting_value).__name__ == "int":
                value_type = WeVoteSetting.INTEGER
            elif type(setting_value).__name__ == "str":
                value_type = WeVoteSetting.STRING
            elif type(setting_value).__name__ == "list":
                print "setting is a list. To be developed"
                value_type = WeVoteSetting.STRING
            else:
                value_type = WeVoteSetting.STRING
        elif value_type not in accepted_value_types:
            # Not a recognized value_type, save as a str
            value_type = WeVoteSetting.STRING

        # Does this setting already exist?
        we_vote_setting = WeVoteSetting()
        we_vote_setting_id = 0
        we_vote_setting_exists = False
        we_vote_setting_does_not_exist = False
        try:
            we_vote_setting = WeVoteSetting.objects.get(name=setting_name)
            we_vote_setting_exists = True
        except WeVoteSetting.MultipleObjectsReturned as e:
            handle_record_found_more_than_one_exception(e)
        except WeVoteSetting.DoesNotExist as e:
            handle_exception_silently(e)
            we_vote_setting_does_not_exist = True

        we_vote_setting_manager = WeVoteSettingsManager()
        if we_vote_setting_exists:
            # Update this position with new values
            try:
                we_vote_setting.value_type = value_type
                we_vote_setting = we_vote_setting_manager.set_setting_value_by_type(
                    we_vote_setting, setting_value, value_type
                )
                we_vote_setting.save()
                we_vote_setting_id = we_vote_setting.id
            except Exception as e:
                handle_record_not_saved_exception(e)
        elif we_vote_setting_does_not_exist:
            try:
                # Create new
                we_vote_setting = WeVoteSetting(value_type=value_type, name=setting_name)
                we_vote_setting = we_vote_setting_manager.set_setting_value_by_type(
                    we_vote_setting, setting_value, value_type
                )
                we_vote_setting.save()
                we_vote_setting_id = we_vote_setting.id
            except Exception as e:
                handle_record_not_saved_exception(e)

        results = {"success": True if we_vote_setting_id else False, "we_vote_setting": we_vote_setting}
        return results
示例#17
0
def google_civic_get_or_create_candidate_campaign_basic(
        google_civic_candidate_campaign_entry):
    """
    Search the CandidateCampaign table to see if we already have an entry for this election
    :param google_civic_candidate_campaign_entry:
    :return:
    """
    error_result = False
    candidate_campaign_exists_locally = False
    candidate_campaign_on_stage = CandidateCampaign()
    candidate_campaign_created = False
    politician_link_needed = True
    try:
        # Try to find earlier version based on the google_civic_election_id identifier
        candidate_campaign_query = CandidateCampaign.objects.all()
        candidate_campaign_query = candidate_campaign_query.filter(
            google_civic_election_id__exact=
            google_civic_candidate_campaign_entry.google_civic_election_id)
        # TODO: If the name from Google Civic changes slightly, we would create a new campaign entry
        # (which would not be correct) We should make this more robust and error-proof
        candidate_campaign_query = candidate_campaign_query.filter(
            candidate_name__exact=google_civic_candidate_campaign_entry.name)

        # Was at least one existing entry found based on the above criteria?
        if len(candidate_campaign_query):
            candidate_campaign_on_stage = candidate_campaign_query[0]
            candidate_campaign_exists_locally = True
            # Is a Politician linked to this candidate_campaign_on_stage
            if candidate_campaign_on_stage.politician_id:
                politician_link_needed = False
    except Exception as e:
        error_result = True
        handle_record_not_found_exception(e, logger=logger)

    if not candidate_campaign_exists_locally:
        # An entry in the local CandidateCampaign table was not found
        # ...so create a new entry
        try:
            candidate_campaign_on_stage = CandidateCampaign(
                google_civic_election_id=google_civic_candidate_campaign_entry.
                google_civic_election_id,
                candidate_name=google_civic_candidate_campaign_entry.name,
                party=google_civic_candidate_campaign_entry.party,
            )
            candidate_campaign_on_stage.save()
            candidate_campaign_created = True
        except Exception as e:
            error_result = True
            handle_record_not_saved_exception(e, logger=logger)

    results = {
        'error_result': error_result,
        'politician_link_needed': politician_link_needed,
        'candidate_campaign_created': candidate_campaign_created,
        'candidate_campaign_on_stage': candidate_campaign_on_stage,
    }

    return results
示例#18
0
def voter_change_authority_process_view(request):
    """
    Grant or remove an existing account volunteer or admin rights
    :param request:
    :return:
    """
    authority_required = {'admin'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    voter_on_stage = Voter()
    authority_changed = False

    voter_id = request.GET.get('voter_id', 0)
    voter_id = convert_to_int(voter_id)
    authority_granted = request.GET.get('authority_granted', False)
    authority_removed = request.GET.get('authority_removed', False)

    # Check to see if this voter is already being used anywhere
    voter_on_stage_found = False
    try:
        voter_query = Voter.objects.filter(id=voter_id)
        if len(voter_query):
            voter_on_stage = voter_query[0]
            voter_on_stage_found = True
    except Exception as e:
        handle_record_not_found_exception(e, logger=logger)

    if voter_on_stage_found:
        try:
            if authority_granted == 'verified_volunteer':
                voter_on_stage.is_verified_volunteer = True
                authority_changed = True
            elif authority_granted == 'admin':
                voter_on_stage.is_admin = True
                authority_changed = True

            if authority_removed == 'verified_volunteer':
                voter_on_stage.is_verified_volunteer = False
                authority_changed = True
            elif authority_removed == 'admin':
                voter_on_stage.is_admin = False
                authority_changed = True

            if authority_changed:
                voter_on_stage.save()

            messages.add_message(request, messages.INFO,
                                 'Voter authority updated.')
        except Exception as e:
            handle_record_not_saved_exception(e, logger=logger)
            messages.add_message(request, messages.ERROR,
                                 'Could not save voter.')
    else:
        messages.add_message(request, messages.ERROR,
                             'Could not save change to authority.')

    return HttpResponseRedirect(reverse('voter:voter_edit', args=(voter_id, )))
示例#19
0
    def toggle_voter_starred_item(self, voter_id, star_status,
                                  candidate_campaign_id=0, contest_office_id=0, contest_measure_id=0):
        # Does a star_item entry exist from this voter already exist?
        star_item_manager = StarItemManager()
        star_item_id = 0
        results = star_item_manager.retrieve_star_item(star_item_id, voter_id,
                                                       contest_office_id, candidate_campaign_id, contest_measure_id)

        star_item_on_stage_found = False
        star_item_on_stage_id = 0
        star_item_on_stage = StarItem()
        if results['star_item_found']:
            star_item_on_stage = results['star_item']

            # Update this star_item entry with new values - we do not delete because we might be able to use
            try:
                star_item_on_stage.star_status = star_status
                # We don't need to update date_last_changed here because set set auto_now=True in the field
                star_item_on_stage.save()
                star_item_on_stage_id = star_item_on_stage.id
                star_item_on_stage_found = True
                status = 'UPDATE ' + star_status
            except Exception as e:
                status = 'FAILED_TO_UPDATE ' + star_status
                handle_record_not_saved_exception(e, logger=logger, exception_message_optional=status)
        elif results['MultipleObjectsReturned']:
            logger.warn("star_item: delete all but one and take it over?")
            status = 'TOGGLE_ITEM_STARRED MultipleObjectsReturned ' + star_status
        elif results['DoesNotExist']:
            try:
                # Create new star_item entry
                # NOTE: For speed purposes, we are not validating the existence of the items being starred
                star_item_on_stage = StarItem(
                    voter_id=voter_id,
                    candidate_campaign_id=candidate_campaign_id,
                    contest_office_id=contest_office_id,
                    contest_measure_id=contest_measure_id,
                    star_status=star_status,
                    # We don't need to update date_last_changed here because set set auto_now=True in the field
                )
                star_item_on_stage.save()
                star_item_on_stage_id = star_item_on_stage.id
                star_item_on_stage_found = True
                status = 'CREATE ' + star_status
            except Exception as e:
                status = 'FAILED_TO_UPDATE ' + star_status
                handle_record_not_saved_exception(e, logger=logger, exception_message_optional=status)
        else:
            status = results['status']

        results = {
            'success':            True if star_item_on_stage_found else False,
            'status':             status,
            'star_item_found':    star_item_on_stage_found,
            'star_item_id':       star_item_on_stage_id,
            'star_item':          star_item_on_stage,
        }
        return results
示例#20
0
def google_civic_save_election():
    # Bring in the GoogleCivicElection and save the Election
    google_civic_query1 = GoogleCivicElection.objects.all()
    # Only retrieve entries that haven't been processed yet
    # google_civic_query1 = google_civic_query1.filter(was_processed=False)

    for google_civic_election_entry in google_civic_query1:
        election_exists_locally = False

        #########################
        # Search the Election table to see if we already have an entry for this election
        if google_civic_election_entry.google_civic_election_id != "":
            try:
                # Try to find earlier version based on the google_civic_election_id identifier
                query1 = Election.objects.all()
                query1 = query1.filter(
                    google_civic_election_id__exact=google_civic_election_entry
                    .google_civic_election_id)

                # Was at least one existing entry found based on the above criteria?
                if len(query1):
                    election_entry = query1[0]
                    election_exists_locally = True
            except Exception as e:
                handle_record_not_found_exception(e)
                continue

        try:
            if election_exists_locally:
                # Update the values
                election_entry.google_civic_election_id = google_civic_election_entry.google_civic_election_id
                election_entry.name = google_civic_election_entry.name + "TEST"
                election_entry.election_date_text = google_civic_election_entry.election_day
            else:
                # An entry in the local Election was not found based on google_civic_election_id
                # ...so create a new entry
                election_entry = Election(
                    google_civic_election_id=google_civic_election_entry.
                    google_civic_election_id,
                    name=google_civic_election_entry.name,
                    election_date_text=google_civic_election_entry.
                    election_day,
                )

            election_entry.save()

            # Mark the source entry as was_processed so we don't try to import the same data again
            # google_civic_election_entry.was_processed = True

            # Save the local we vote id back to the imported google civic data for cross-checking
            google_civic_election_entry.we_vote_election_id = election_entry.id
            google_civic_election_entry.save()

        except Exception as e:
            handle_record_not_saved_exception(e)
            continue
示例#21
0
文件: models.py 项目: zvxr/WeVoteBase
def google_civic_get_or_create_candidate_campaign_basic(google_civic_candidate_campaign_entry):
    """
    Search the CandidateCampaign table to see if we already have an entry for this election
    :param google_civic_candidate_campaign_entry:
    :return:
    """
    error_result = False
    candidate_campaign_exists_locally = False
    candidate_campaign_on_stage = CandidateCampaign()
    candidate_campaign_created = False
    politician_link_needed = True
    try:
        # Try to find earlier version based on the google_civic_election_id identifier
        candidate_campaign_query = CandidateCampaign.objects.all()
        candidate_campaign_query = candidate_campaign_query.filter(
            google_civic_election_id__exact=google_civic_candidate_campaign_entry.google_civic_election_id)
        # TODO: If the name from Google Civic changes slightly, we would create a new campaign entry
        # (which would not be correct) We should make this more robust and error-proof
        candidate_campaign_query = candidate_campaign_query.filter(
            candidate_name__exact=google_civic_candidate_campaign_entry.name)

        # Was at least one existing entry found based on the above criteria?
        if len(candidate_campaign_query):
            candidate_campaign_on_stage = candidate_campaign_query[0]
            candidate_campaign_exists_locally = True
            # Is a Politician linked to this candidate_campaign_on_stage
            if candidate_campaign_on_stage.politician_id:
                politician_link_needed = False
    except Exception as e:
        error_result = True
        handle_record_not_found_exception(e)

    if not candidate_campaign_exists_locally:
        # An entry in the local CandidateCampaign table was not found
        # ...so create a new entry
        try:
            candidate_campaign_on_stage = CandidateCampaign(
                google_civic_election_id=google_civic_candidate_campaign_entry.google_civic_election_id,
                candidate_name=google_civic_candidate_campaign_entry.name,
                party=google_civic_candidate_campaign_entry.party,
            )
            candidate_campaign_on_stage.save()
            candidate_campaign_created = True
        except Exception as e:
            error_result = True
            handle_record_not_saved_exception(e)

    results = {
        'error_result': error_result,
        'politician_link_needed': politician_link_needed,
        'candidate_campaign_created': candidate_campaign_created,
        'candidate_campaign_on_stage': candidate_campaign_on_stage,
    }

    return results
示例#22
0
def voter_change_authority_process_view(request):
    """
    Grant or remove an existing account volunteer or admin rights
    :param request:
    :return:
    """
    authority_required = {'admin'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    voter_on_stage = Voter()
    authority_changed = False

    voter_id = request.GET.get('voter_id', 0)
    voter_id = convert_to_int(voter_id)
    authority_granted = request.GET.get('authority_granted', False)
    authority_removed = request.GET.get('authority_removed', False)

    # Check to see if this voter is already being used anywhere
    voter_on_stage_found = False
    try:
        voter_query = Voter.objects.filter(id=voter_id)
        if len(voter_query):
            voter_on_stage = voter_query[0]
            voter_on_stage_found = True
    except Exception as e:
        handle_record_not_found_exception(e, logger=logger)

    if voter_on_stage_found:
        try:
            if authority_granted == 'verified_volunteer':
                voter_on_stage.is_verified_volunteer = True
                authority_changed = True
            elif authority_granted == 'admin':
                voter_on_stage.is_admin = True
                authority_changed = True

            if authority_removed == 'verified_volunteer':
                voter_on_stage.is_verified_volunteer = False
                authority_changed = True
            elif authority_removed == 'admin':
                voter_on_stage.is_admin = False
                authority_changed = True

            if authority_changed:
                voter_on_stage.save()

            messages.add_message(request, messages.INFO, 'Voter authority updated.')
        except Exception as e:
            handle_record_not_saved_exception(e, logger=logger)
            messages.add_message(request, messages.ERROR, 'Could not save voter.')
    else:
        messages.add_message(request, messages.ERROR, 'Could not save change to authority.')

    return HttpResponseRedirect(reverse('voter:voter_edit', args=(voter_id,)))
示例#23
0
    def toggle_voter_following_organization(self, voter_id, organization_id,
                                            following_status):
        # Does a follow_organization entry exist from this voter already exist?
        follow_organization_manager = FollowOrganizationManager()
        results = follow_organization_manager.retrieve_follow_organization(
            0, voter_id, organization_id)

        follow_organization_on_stage_found = False
        follow_organization_on_stage_id = 0
        follow_organization_on_stage = FollowOrganization()
        if results['follow_organization_found']:
            follow_organization_on_stage = results['follow_organization']

            # Update this follow_organization entry with new values - we do not delete because we might be able to use
            try:
                follow_organization_on_stage.following_status = following_status
                # We don't need to update here because set set auto_now=True in the field
                # follow_organization_on_stage.date_last_changed =
                follow_organization_on_stage.save()
                follow_organization_on_stage_id = follow_organization_on_stage.id
                follow_organization_on_stage_found = True
            except Exception as e:
                handle_record_not_saved_exception(e)

        elif results['MultipleObjectsReturned']:
            print "follow_organization: delete all but one and take it over?"
        elif results['DoesNotExist']:
            try:
                # Create new follow_organization entry
                # First make sure that organization_id is for a valid organization
                organization_manager = OrganizationManager()
                results = organization_manager.retrieve_organization(
                    organization_id)
                if results['organization_found']:
                    follow_organization_on_stage = FollowOrganization(
                        voter_id=voter_id,
                        organization_id=organization_id,
                        following_status=following_status,
                        # We don't need to update here because set set auto_now=True in the field
                        # date_last_changed =
                    )
                    follow_organization_on_stage.save()
                    follow_organization_on_stage_id = follow_organization_on_stage.id
                    follow_organization_on_stage_found = True
            except Exception as e:
                handle_record_not_saved_exception(e)

        results = {
            'success': True if follow_organization_on_stage_found else False,
            'follow_organization_found': follow_organization_on_stage_found,
            'follow_organization_id': follow_organization_on_stage_id,
            'follow_organization': follow_organization_on_stage,
        }
        return results
示例#24
0
文件: models.py 项目: zvxr/WeVoteBase
def google_civic_save_election():
    # Bring in the GoogleCivicElection and save the Election
    google_civic_query1 = GoogleCivicElection.objects.all()
    # Only retrieve entries that haven't been processed yet
    # google_civic_query1 = google_civic_query1.filter(was_processed=False)

    for google_civic_election_entry in google_civic_query1:
        election_exists_locally = False

        #########################
        # Search the Election table to see if we already have an entry for this election
        if google_civic_election_entry.google_civic_election_id != "":
            try:
                # Try to find earlier version based on the google_civic_election_id identifier
                query1 = Election.objects.all()
                query1 = query1.filter(
                    google_civic_election_id__exact=google_civic_election_entry.google_civic_election_id)

                # Was at least one existing entry found based on the above criteria?
                if len(query1):
                    election_entry = query1[0]
                    election_exists_locally = True
            except Exception as e:
                handle_record_not_found_exception(e)
                continue

        try:
            if election_exists_locally:
                # Update the values
                election_entry.google_civic_election_id = google_civic_election_entry.google_civic_election_id
                election_entry.name = google_civic_election_entry.name+"TEST"
                election_entry.election_date_text = google_civic_election_entry.election_day
            else:
                # An entry in the local Election was not found based on google_civic_election_id
                # ...so create a new entry
                election_entry = Election(
                    google_civic_election_id=google_civic_election_entry.google_civic_election_id,
                    name=google_civic_election_entry.name,
                    election_date_text=google_civic_election_entry.election_day,
                )

            election_entry.save()

            # Mark the source entry as was_processed so we don't try to import the same data again
            # google_civic_election_entry.was_processed = True

            # Save the local we vote id back to the imported google civic data for cross-checking
            google_civic_election_entry.we_vote_election_id = election_entry.id
            google_civic_election_entry.save()

        except Exception as e:
            handle_record_not_saved_exception(e)
            continue
示例#25
0
 def create_organization_simple(self, organization_name, organization_website, organization_twitter_handle,
                                organization_email='', organization_facebook='', organization_image=''):
     try:
         organization = self.create(organization_name=organization_name,
                                    organization_website=organization_website,
                                    organization_twitter_handle=organization_twitter_handle,
                                    organization_email=organization_email,
                                    organization_facebook=organization_facebook,
                                    organization_image=organization_image)
     except Exception as e:
         handle_record_not_saved_exception(e, logger=logger)
         organization = Organization
     return organization
示例#26
0
 def create_organization_simple(self, organization_name, organization_website, organization_twitter_handle,
                                organization_email='', organization_facebook='', organization_image=''):
     try:
         organization = self.create(organization_name=organization_name,
                                    organization_website=organization_website,
                                    organization_twitter_handle=organization_twitter_handle,
                                    organization_email=organization_email,
                                    organization_facebook=organization_facebook,
                                    organization_image=organization_image)
     except Exception as e:
         handle_record_not_saved_exception(e, logger=logger)
         organization = Organization
     return organization
示例#27
0
文件: models.py 项目: zvxr/WeVoteBase
    def toggle_voter_following_organization(self, voter_id, organization_id, following_status):
        # Does a follow_organization entry exist from this voter already exist?
        follow_organization_manager = FollowOrganizationManager()
        results = follow_organization_manager.retrieve_follow_organization(0, voter_id, organization_id)

        follow_organization_on_stage_found = False
        follow_organization_on_stage_id = 0
        follow_organization_on_stage = FollowOrganization()
        if results['follow_organization_found']:
            follow_organization_on_stage = results['follow_organization']

            # Update this follow_organization entry with new values - we do not delete because we might be able to use
            try:
                follow_organization_on_stage.following_status = following_status
                # We don't need to update here because set set auto_now=True in the field
                # follow_organization_on_stage.date_last_changed =
                follow_organization_on_stage.save()
                follow_organization_on_stage_id = follow_organization_on_stage.id
                follow_organization_on_stage_found = True
            except Exception as e:
                handle_record_not_saved_exception(e)

        elif results['MultipleObjectsReturned']:
            print "follow_organization: delete all but one and take it over?"
        elif results['DoesNotExist']:
            try:
                # Create new follow_organization entry
                # First make sure that organization_id is for a valid organization
                organization_manager = OrganizationManager()
                results = organization_manager.retrieve_organization(organization_id)
                if results['organization_found']:
                    follow_organization_on_stage = FollowOrganization(
                        voter_id=voter_id,
                        organization_id=organization_id,
                        following_status=following_status,
                        # We don't need to update here because set set auto_now=True in the field
                        # date_last_changed =
                    )
                    follow_organization_on_stage.save()
                    follow_organization_on_stage_id = follow_organization_on_stage.id
                    follow_organization_on_stage_found = True
            except Exception as e:
                handle_record_not_saved_exception(e)

        results = {
            'success':                      True if follow_organization_on_stage_found else False,
            'follow_organization_found':    follow_organization_on_stage_found,
            'follow_organization_id':       follow_organization_on_stage_id,
            'follow_organization':          follow_organization_on_stage,
        }
        return results
示例#28
0
def measure_edit_process_view(request):
    """
    Process the new or edit measure 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)

    measure_id = convert_to_int(request.POST['measure_id'])
    measure_name = request.POST['measure_name']
    twitter_handle = request.POST['twitter_handle']
    measure_website = request.POST['measure_website']

    # Check to see if this measure is already being used anywhere
    measure_on_stage_found = False
    measure_on_stage = ContestMeasure()
    try:
        measure_query = ContestMeasure.objects.filter(id=measure_id)
        if len(measure_query):
            measure_on_stage = measure_query[0]
            measure_on_stage_found = True
    except Exception as e:
        handle_record_not_found_exception(e, logger=logger)

    try:
        if measure_on_stage_found:
            # Update
            measure_on_stage.measure_name = measure_name
            measure_on_stage.twitter_handle = twitter_handle
            measure_on_stage.measure_website = measure_website
            measure_on_stage.save()
            messages.add_message(request, messages.INFO,
                                 'ContestMeasure updated.')
        else:
            # Create new
            measure_on_stage = ContestMeasure(
                measure_name=measure_name,
                twitter_handle=twitter_handle,
                measure_website=measure_website,
            )
            measure_on_stage.save()
            messages.add_message(request, messages.INFO, 'New measure saved.')
    except Exception as e:
        handle_record_not_saved_exception(e, logger=logger)
        messages.add_message(request, messages.ERROR,
                             'Could not save measure.')

    return HttpResponseRedirect(reverse('measure:measure_list', args=()))
示例#29
0
def organization_edit_process_view(request):
    """
    Process the new or edit organization forms
    :param request:
    :return:
    """
    organization_id = convert_to_int(request.POST['organization_id'])
    organization_name = request.POST['organization_name']
    organization_twitter_handle = request.POST['organization_twitter_handle']
    organization_website = request.POST['organization_website']

    # 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
            organization_on_stage.organization_name = organization_name
            organization_on_stage.organization_twitter_handle = organization_twitter_handle
            organization_on_stage.organization_website = organization_website
            organization_on_stage.save()
            organization_id = organization_on_stage.id
            messages.add_message(request, messages.INFO, 'Organization updated.')
            return HttpResponseRedirect(reverse('organization:organization_position_list', args=(organization_id,)))
        else:
            # Create new
            organization_on_stage = Organization(
                organization_name=organization_name,
                organization_twitter_handle=organization_twitter_handle,
                organization_website=organization_website
            )
            organization_on_stage.save()
            organization_id = organization_on_stage.id
            messages.add_message(request, messages.INFO, 'New organization saved.')
            return HttpResponseRedirect(reverse('organization:organization_position_list', args=(organization_id,)))
    except Exception as e:
        handle_record_not_saved_exception(e, logger=logger)
        messages.add_message(request, messages.ERROR, 'Could not save organization.'
                                                      ' {error} [type: {error_type}]'.format(error=e.message,
                                                                                             error_type=type(e)))

    return HttpResponseRedirect(reverse('organization:organization_list', args=()))
示例#30
0
文件: models.py 项目: zvxr/WeVoteBase
def import_we_vote_candidate_campaigns_from_json(request, load_from_uri=False):
    """
    Get the json data, and either create new entries or update existing
    :return:
    """
    if load_from_uri:
        # Request json file from We Vote servers
        messages.add_message(request, messages.INFO, "Loading CandidateCampaign IDs from We Vote Master servers")
        request = requests.get(CANDIDATE_CAMPAIGNS_URL, params={
            "key": WE_VOTE_API_KEY,  # This comes from an environment variable
        })
        structured_json = json.loads(request.text)
    else:
        # Load saved json from local file
        messages.add_message(request, messages.INFO, "Loading CandidateCampaigns IDs from local file")

        with open(CANDIDATE_CAMPAIGNS_JSON_FILE) as json_data:
            structured_json = json.load(json_data)

    for one_candidate_campaign in structured_json:
        # For now we are only adding a We Vote ID so we can save Positions
        candidate_campaign_on_stage_found = False
        try:
            if len(one_candidate_campaign["candidate_name"]) > 0:
                candidate_campaign_query = CandidateCampaign.objects.filter(
                    candidate_name=one_candidate_campaign["candidate_name"])
                if len(candidate_campaign_query) == 1:  # Make sure only one found
                    candidate_campaign_on_stage = candidate_campaign_query[0]
                    candidate_campaign_on_stage_found = True
        except Exception as e:
            handle_record_not_found_exception(e)

        try:
            if candidate_campaign_on_stage_found:
                # Update
                candidate_campaign_on_stage.id_we_vote = one_candidate_campaign["id_we_vote"]
                candidate_campaign_on_stage.save()
                messages.add_message(request, messages.INFO, "CandidateCampaign updated: {candidate_name}".format(
                    candidate_name=one_candidate_campaign["candidate_name"]))
            else:
                messages.add_message(request, messages.ERROR, "CandidateCampaign not found: {candidate_name}".format(
                    candidate_name=one_candidate_campaign["candidate_name"]))
        except Exception as e:
            handle_record_not_saved_exception(e)
            messages.add_message(request, messages.ERROR,
                                 "Could not save CandidateCampaign, id_we_vote: {id_we_vote}, "
                                 "candidate_name: {candidate_name}, ".format(
                                     id_we_vote=one_candidate_campaign["id_we_vote"],
                                     candidate_name=one_candidate_campaign["candidate_name"],))
示例#31
0
def position_delete_process_view(request):
    """
    Delete a position
    :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)

    position_we_vote_id = request.GET.get('position_we_vote_id', '')
    google_civic_election_id = request.GET.get('google_civic_election_id', 0)

    # Retrieve this position
    position_on_stage_found = False
    position_on_stage = PositionEntered()
    organization_id = 0
    try:
        position_query = PositionEntered.objects.filter(we_vote_id=position_we_vote_id)
        if len(position_query):
            position_on_stage = position_query[0]
            organization_id = position_on_stage.organization_id
            position_on_stage_found = True
    except Exception as e:
        messages.add_message(request, messages.ERROR, 'Could not find position -- exception.')

    if not position_on_stage_found:
        messages.add_message(request, messages.ERROR, 'Could not find position.')
        return HttpResponseRedirect(reverse('position:position_list', args=()) +
                                    "?google_civic_election_id=" + str(google_civic_election_id))

    try:
        if position_on_stage_found:
            # Delete
            position_on_stage.delete()
            messages.add_message(request, messages.INFO, 'Position deleted.')
            if positive_value_exists(organization_id):
                return HttpResponseRedirect(reverse('organization:organization_position_list',
                                                    args=([organization_id])) +
                                            "?google_civic_election_id=" + str(google_civic_election_id))
        else:
            messages.add_message(request, messages.ERROR, 'Could not find position.')
    except Exception as e:
        handle_record_not_saved_exception(e, logger=logger)
        messages.add_message(request, messages.ERROR, 'Could not save position.')

    return HttpResponseRedirect(reverse('position:position_list', args=()) +
                                "?google_civic_election_id=" + str(google_civic_election_id))
示例#32
0
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['candidate_name']
    twitter_handle = request.POST['twitter_handle']
    candidate_website = request.POST['candidate_website']

    # Check to see if this candidate is already being used anywhere
    candidate_on_stage_found = False
    candidate_on_stage = CandidateCampaign()
    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)

    try:
        if candidate_on_stage_found:
            # Update
            candidate_on_stage.candidate_name = candidate_name
            candidate_on_stage.twitter_handle = twitter_handle
            candidate_on_stage.candidate_website = candidate_website
            candidate_on_stage.save()
            messages.add_message(request, messages.INFO, 'CandidateCampaign updated.')
        else:
            # Create new
            candidate_on_stage = CandidateCampaign(
                candidate_name=candidate_name,
                twitter_handle=twitter_handle,
                candidate_website=candidate_website,
            )
            candidate_on_stage.save()
            messages.add_message(request, messages.INFO, 'New candidate saved.')
    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_list', args=()))
示例#33
0
def position_edit_process_view(request):
    """
    Process the new or edit position 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)

    position_id = convert_to_int(request.POST['position_id'])
    position_name = request.POST['position_name']
    twitter_handle = request.POST['twitter_handle']
    position_website = request.POST['position_website']

    # Check to see if this position is already being used anywhere
    position_on_stage_found = False
    try:
        position_query = CandidateCampaign.objects.filter(id=position_id)
        if len(position_query):
            position_on_stage = position_query[0]
            position_on_stage_found = True
    except Exception as e:
        handle_record_not_found_exception(e, logger=logger)

    try:
        if position_on_stage_found:
            # Update
            position_on_stage.position_name = position_name
            position_on_stage.twitter_handle = twitter_handle
            position_on_stage.position_website = position_website
            position_on_stage.save()
            messages.add_message(request, messages.INFO, 'CandidateCampaign updated.')
        else:
            # Create new
            position_on_stage = CandidateCampaign(
                position_name=position_name,
                twitter_handle=twitter_handle,
                position_website=position_website,
            )
            position_on_stage.save()
            messages.add_message(request, messages.INFO, 'New position saved.')
    except Exception as e:
        handle_record_not_saved_exception(e, logger=logger)
        messages.add_message(request, messages.ERROR, 'Could not save position.')

    return HttpResponseRedirect(reverse('position:position_list', args=()))
示例#34
0
def position_edit_process_view(request):  # TODO DALE I don't think this is in use, but needs to be updated
    """
    Process the new or edit position 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)

    position_we_vote_id = request.POST.get('position_we_vote_id')
    position_name = request.POST['position_name']
    twitter_handle = request.POST['twitter_handle']
    position_website = request.POST['position_website']

    # Check to see if this position is already being used anywhere
    position_on_stage_found = False
    try:
        position_query = PositionEntered.objects.filter(we_vote_id=position_we_vote_id)
        if len(position_query):
            position_on_stage = position_query[0]
            position_on_stage_found = True
    except Exception as e:
        handle_record_not_found_exception(e, logger=logger)

    try:
        if position_on_stage_found:
            # Update
            position_on_stage.position_name = position_name
            position_on_stage.twitter_handle = twitter_handle
            position_on_stage.position_website = position_website
            position_on_stage.save()
            messages.add_message(request, messages.INFO, 'PositionEntered updated.')
        else:
            # Create new
            position_on_stage = CandidateCampaign(
                position_name=position_name,
                twitter_handle=twitter_handle,
                position_website=position_website,
            )
            position_on_stage.save()
            messages.add_message(request, messages.INFO, 'New position saved.')
    except Exception as e:
        handle_record_not_saved_exception(e, logger=logger)
        messages.add_message(request, messages.ERROR, 'Could not save position.')

    return HttpResponseRedirect(reverse('position:position_list', args=()))
示例#35
0
def measure_edit_process_view(request):
    """
    Process the new or edit measure 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)

    measure_id = convert_to_int(request.POST["measure_id"])
    measure_name = request.POST["measure_name"]
    twitter_handle = request.POST["twitter_handle"]
    measure_website = request.POST["measure_website"]

    # Check to see if this measure is already being used anywhere
    measure_on_stage_found = False
    measure_on_stage = ContestMeasure()
    try:
        measure_query = ContestMeasure.objects.filter(id=measure_id)
        if len(measure_query):
            measure_on_stage = measure_query[0]
            measure_on_stage_found = True
    except Exception as e:
        handle_record_not_found_exception(e, logger=logger)

    try:
        if measure_on_stage_found:
            # Update
            measure_on_stage.measure_name = measure_name
            measure_on_stage.twitter_handle = twitter_handle
            measure_on_stage.measure_website = measure_website
            measure_on_stage.save()
            messages.add_message(request, messages.INFO, "ContestMeasure updated.")
        else:
            # Create new
            measure_on_stage = ContestMeasure(
                measure_name=measure_name, twitter_handle=twitter_handle, measure_website=measure_website
            )
            measure_on_stage.save()
            messages.add_message(request, messages.INFO, "New measure saved.")
    except Exception as e:
        handle_record_not_saved_exception(e, logger=logger)
        messages.add_message(request, messages.ERROR, "Could not save measure.")

    return HttpResponseRedirect(reverse("measure:measure_list", args=()))
示例#36
0
    def toggle_on_voter_position_for_candidate_campaign(
            self, voter_id, candidate_campaign_id, stance):
        # Does a position from this voter already exist?
        position_entered_manager = PositionEnteredManager()
        results = position_entered_manager.retrieve_voter_candidate_campaign_position(
            voter_id, candidate_campaign_id)

        voter_position_on_stage = PositionEntered()
        voter_position_on_stage_found = False
        position_id = 0
        if results['position_found']:
            voter_position_on_stage = results['position']

            # Update this position with new values
            try:
                voter_position_on_stage.stance = stance
                # voter_position_on_stage.statement_text = statement_text
                voter_position_on_stage.save()
                position_id = voter_position_on_stage.id
                voter_position_on_stage_found = True
            except Exception as e:
                handle_record_not_saved_exception(e, logger=logger)

        elif results['MultipleObjectsReturned']:
            logger.warn("delete all but one and take it over?")
        elif results['DoesNotExist']:
            try:
                # Create new
                voter_position_on_stage = PositionEntered(
                    voter_id=voter_id,
                    candidate_campaign_id=candidate_campaign_id,
                    stance=stance,
                    #  statement_text=statement_text,
                )
                voter_position_on_stage.save()
                position_id = voter_position_on_stage.id
                voter_position_on_stage_found = True
            except Exception as e:
                handle_record_not_saved_exception(e, logger=logger)

        results = {
            'success': True if voter_position_on_stage_found else False,
            'position_id': position_id,
            'position': voter_position_on_stage,
        }
        return results
示例#37
0
def organization_edit_process_view(request):
    """
    Process the new or edit organization forms
    :param request:
    :return:
    """
    # If person isn't signed in, we don't want to let them visit this page yet
    if not request.user.is_authenticated():
        return redirect('/admin')

    organization_id = convert_to_int(request.POST['organization_id'])
    organization_name = request.POST['organization_name']

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

    try:
        if organization_on_stage_found:
            # Update
            organization_on_stage.name = organization_name
            organization_on_stage.save()
            messages.add_message(request, messages.INFO,
                                 'Organization updated.')
        else:
            # Create new
            organization_on_stage = Organization(name=organization_name, )
            organization_on_stage.save()
            messages.add_message(request, messages.INFO,
                                 'New organization saved.')
    except Exception as e:
        handle_record_not_saved_exception(e)
        messages.add_message(request, messages.ERROR,
                             'Could not save organization.')

    return HttpResponseRedirect(
        reverse('organization:organization_list', args=()))
示例#38
0
def measure_edit_process_view(request):
    """
    Process the new or edit measure forms
    :param request:
    :return:
    """
    measure_id = convert_to_int(request.POST['measure_id'])
    measure_name = request.POST['measure_name']
    twitter_handle = request.POST['twitter_handle']
    measure_website = request.POST['measure_website']

    # Check to see if this measure is already being used anywhere
    measure_on_stage_found = False
    measure_on_stage = ContestMeasure()
    try:
        measure_query = ContestMeasure.objects.filter(id=measure_id)
        if len(measure_query):
            measure_on_stage = measure_query[0]
            measure_on_stage_found = True
    except Exception as e:
        handle_record_not_found_exception(e, logger=logger)

    try:
        if measure_on_stage_found:
            # Update
            measure_on_stage.measure_name = measure_name
            measure_on_stage.twitter_handle = twitter_handle
            measure_on_stage.measure_website = measure_website
            measure_on_stage.save()
            messages.add_message(request, messages.INFO, 'ContestMeasure updated.')
        else:
            # Create new
            measure_on_stage = ContestMeasure(
                measure_name=measure_name,
                twitter_handle=twitter_handle,
                measure_website=measure_website,
            )
            measure_on_stage.save()
            messages.add_message(request, messages.INFO, 'New measure saved.')
    except Exception as e:
        handle_record_not_saved_exception(e, logger=logger)
        messages.add_message(request, messages.ERROR, 'Could not save measure.')

    return HttpResponseRedirect(reverse('measure:measure_list', args=()))
示例#39
0
    def toggle_on_voter_position_for_candidate_campaign(self, voter_id, candidate_campaign_id, stance):
        # Does a position from this voter already exist?
        position_entered_manager = PositionEnteredManager()
        results = position_entered_manager.retrieve_voter_candidate_campaign_position(voter_id, candidate_campaign_id)

        voter_position_on_stage = PositionEntered()
        voter_position_on_stage_found = False
        position_id = 0
        if results['position_found']:
            voter_position_on_stage = results['position']

            # Update this position with new values
            try:
                voter_position_on_stage.stance = stance
                # voter_position_on_stage.statement_text = statement_text
                voter_position_on_stage.save()
                position_id = voter_position_on_stage.id
                voter_position_on_stage_found = True
            except Exception as e:
                handle_record_not_saved_exception(e, logger=logger)

        elif results['MultipleObjectsReturned']:
            logger.warn("delete all but one and take it over?")
        elif results['DoesNotExist']:
            try:
                # Create new
                voter_position_on_stage = PositionEntered(
                    voter_id=voter_id,
                    candidate_campaign_id=candidate_campaign_id,
                    stance=stance,
                    #  statement_text=statement_text,
                )
                voter_position_on_stage.save()
                position_id = voter_position_on_stage.id
                voter_position_on_stage_found = True
            except Exception as e:
                handle_record_not_saved_exception(e, logger=logger)

        results = {
            'success':                  True if voter_position_on_stage_found else False,
            'position_id':              position_id,
            'position':                 voter_position_on_stage,
        }
        return results
示例#40
0
def polling_location_edit_process_view(request):
    """
    Process the new or edit polling_location 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)

    polling_location_id = convert_to_int(request.POST['polling_location_id'])
    polling_location_name = request.POST.get('polling_location_name', False)

    # Check to see if this polling_location is already being used anywhere
    polling_location_on_stage_found = False
    polling_location_on_stage = PollingLocation()
    try:
        polling_location_query = PollingLocation.objects.filter(
            id=polling_location_id)
        if len(polling_location_query):
            polling_location_on_stage = polling_location_query[0]
            polling_location_on_stage_found = True
    except Exception as e:
        handle_record_not_found_exception(e, logger=logger)

    try:
        if polling_location_on_stage_found:
            # Update
            polling_location_on_stage.polling_location_name = polling_location_name
            polling_location_on_stage.save()
            messages.add_message(request, messages.INFO,
                                 'PollingLocation updated.')
        else:
            # Create new
            messages.add_message(
                request, messages.INFO,
                'We do not support adding new polling locations.')
    except Exception as e:
        handle_record_not_saved_exception(e, logger=logger)
        messages.add_message(request, messages.ERROR,
                             'Could not save polling_location.')

    return HttpResponseRedirect(
        reverse('polling_location:polling_location_list', args=()))
示例#41
0
文件: views.py 项目: zvxr/WeVoteBase
def organization_edit_process_view(request):
    """
    Process the new or edit organization forms
    :param request:
    :return:
    """
    # If person isn't signed in, we don't want to let them visit this page yet
    if not request.user.is_authenticated():
        return redirect('/admin')

    organization_id = convert_to_int(request.POST['organization_id'])
    organization_name = request.POST['organization_name']

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

    try:
        if organization_on_stage_found:
            # Update
            organization_on_stage.name = organization_name
            organization_on_stage.save()
            messages.add_message(request, messages.INFO, 'Organization updated.')
        else:
            # Create new
            organization_on_stage = Organization(
                name=organization_name,
            )
            organization_on_stage.save()
            messages.add_message(request, messages.INFO, 'New organization saved.')
    except Exception as e:
        handle_record_not_saved_exception(e)
        messages.add_message(request, messages.ERROR, 'Could not save organization.')

    return HttpResponseRedirect(reverse('organization:organization_list', args=()))
示例#42
0
def position_edit_process_view(request):
    """
    Process the new or edit position forms
    :param request:
    :return:
    """
    position_id = convert_to_int(request.POST['position_id'])
    position_name = request.POST['position_name']
    twitter_handle = request.POST['twitter_handle']
    position_website = request.POST['position_website']

    # Check to see if this position is already being used anywhere
    position_on_stage_found = False
    try:
        position_query = CandidateCampaign.objects.filter(id=position_id)
        if len(position_query):
            position_on_stage = position_query[0]
            position_on_stage_found = True
    except Exception as e:
        handle_record_not_found_exception(e, logger=logger)

    try:
        if position_on_stage_found:
            # Update
            position_on_stage.position_name = position_name
            position_on_stage.twitter_handle = twitter_handle
            position_on_stage.position_website = position_website
            position_on_stage.save()
            messages.add_message(request, messages.INFO, 'CandidateCampaign updated.')
        else:
            # Create new
            position_on_stage = CandidateCampaign(
                position_name=position_name,
                twitter_handle=twitter_handle,
                position_website=position_website,
            )
            position_on_stage.save()
            messages.add_message(request, messages.INFO, 'New position saved.')
    except Exception as e:
        handle_record_not_saved_exception(e, logger=logger)
        messages.add_message(request, messages.ERROR, 'Could not save position.')

    return HttpResponseRedirect(reverse('position:position_list', args=()))
示例#43
0
def election_edit_process_view(request):
    """
    Process the new or edit election forms
    :param request:
    :return:
    """
    authority_required = {'admin'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    election_local_id = convert_to_int(request.POST['election_local_id'])
    election_name = request.POST['election_name']
    election_on_stage = Election()

    # Check to see if this election is already being used anywhere
    election_on_stage_found = False
    try:
        election_query = Election.objects.filter(id=election_local_id)
        if len(election_query):
            election_on_stage = election_query[0]
            election_on_stage_found = True
    except Exception as e:
        handle_record_not_found_exception(e, logger=logger)

    try:
        if election_on_stage_found:
            # Update
            election_on_stage.election_name = election_name
            election_on_stage.save()
            messages.add_message(request, messages.INFO, 'Election updated.')
        else:
            # Create new
            election_on_stage = Election(election_name=election_name, )
            election_on_stage.save()
            messages.add_message(request, messages.INFO, 'New election saved.')
    except Exception as e:
        handle_record_not_saved_exception(e, logger=logger)
        messages.add_message(request, messages.ERROR,
                             'Could not save election.')

    return HttpResponseRedirect(reverse('election:election_list', args=()))
示例#44
0
 def create_organization(self, organization_name, organization_website, organization_twitter_handle,
                         organization_email='', organization_facebook='', organization_image=''):
     try:
         organization = self.create(organization_name=organization_name,
                                    organization_website=organization_website,
                                    organization_twitter_handle=organization_twitter_handle,
                                    organization_email=organization_email,
                                    organization_facebook=organization_facebook,
                                    organization_image=organization_image)
         status = "CREATE_ORGANIZATION_SUCCESSFUL"
         success = True
     except Exception as e:
         handle_record_not_saved_exception(e, logger=logger)
         organization = Organization
         status = "CREATE_ORGANIZATION_FAILED"
         success = False
     results = {
         'success':      success,
         'status':       status,
         'organization': organization,
     }
     return results
示例#45
0
def organization_edit_process_view(request):
    """
    Process the new or edit organization forms
    :param request:
    :return:
    """
    organization_id = convert_to_int(request.POST['organization_id'])
    organization_name = request.POST['organization_name']

    # 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 len(organization_query):
            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
            organization_on_stage.name = organization_name
            organization_on_stage.save()
            messages.add_message(request, messages.INFO,
                                 'Organization updated.')
        else:
            # Create new
            organization_on_stage = Organization(name=organization_name, )
            organization_on_stage.save()
            messages.add_message(request, messages.INFO,
                                 'New organization saved.')
    except Exception as e:
        handle_record_not_saved_exception(e, logger=logger)
        messages.add_message(request, messages.ERROR,
                             'Could not save organization.')

    return HttpResponseRedirect(
        reverse('organization:organization_list', args=()))
    def save_setting(self, setting_name, setting_value, value_type=None):
        accepted_value_types = ['bool', 'int', 'str']

        if value_type is None:
            if type(setting_value).__name__ == 'bool':
                value_type = WeVoteSetting.BOOLEAN
            elif type(setting_value).__name__ == 'int':
                value_type = WeVoteSetting.INTEGER
            elif type(setting_value).__name__ == 'str':
                value_type = WeVoteSetting.STRING
            elif type(setting_value).__name__ == 'list':
                logger.info("setting is a list. To be developed")
                value_type = WeVoteSetting.STRING
            else:
                value_type = WeVoteSetting.STRING
        elif value_type not in accepted_value_types:
            # Not a recognized value_type, save as a str
            value_type = WeVoteSetting.STRING

        # Does this setting already exist?
        we_vote_setting = WeVoteSetting()
        we_vote_setting_id = 0
        we_vote_setting_exists = False
        we_vote_setting_does_not_exist = False
        try:
            we_vote_setting = WeVoteSetting.objects.get(name=setting_name)
            we_vote_setting_exists = True
        except WeVoteSetting.MultipleObjectsReturned as e:
            handle_record_found_more_than_one_exception(e, logger=logger)
        except WeVoteSetting.DoesNotExist:
            we_vote_setting_does_not_exist = True

        we_vote_setting_manager = WeVoteSettingsManager()
        if we_vote_setting_exists:
            # Update this position with new values
            try:
                we_vote_setting.value_type = value_type
                we_vote_setting = we_vote_setting_manager.set_setting_value_by_type(
                    we_vote_setting, setting_value, value_type)
                we_vote_setting.save()
                we_vote_setting_id = we_vote_setting.id
            except Exception as e:
                handle_record_not_saved_exception(e, logger=logger)
        elif we_vote_setting_does_not_exist:
            try:
                # Create new
                we_vote_setting = WeVoteSetting(
                    value_type=value_type,
                    name=setting_name,
                )
                we_vote_setting = we_vote_setting_manager.set_setting_value_by_type(
                    we_vote_setting, setting_value, value_type)
                we_vote_setting.save()
                we_vote_setting_id = we_vote_setting.id
            except Exception as e:
                handle_record_not_saved_exception(e, logger=logger)

        results = {
            'success': True if we_vote_setting_id else False,
            'we_vote_setting': we_vote_setting,
        }
        return results
示例#47
0
def voter_edit_process_view(request):
    """
    Process the new or edit voter forms
    :param request:
    :return:
    """
    authority_required = {'admin'}  # admin, verified_volunteer
    if not voter_has_authority(request, authority_required):
        return redirect_to_sign_in_page(request, authority_required)

    voter_on_stage = Voter()
    at_least_one_value_changed = False

    voter_id = request.POST.get('voter_id', 0)
    voter_id = convert_to_int(voter_id)
    first_name = request.POST.get('first_name', False)
    last_name = request.POST.get('last_name', False)
    twitter_handle = request.POST.get('twitter_handle', False)
    email = request.POST.get('email', False)
    password_text = request.POST.get('password_text', False)

    # Check to see if this voter is already being used anywhere
    voter_on_stage_found = False
    try:
        voter_query = Voter.objects.filter(id=voter_id)
        if len(voter_query):
            voter_on_stage = voter_query[0]
            voter_on_stage_found = True
    except Exception as e:
        handle_record_not_found_exception(e, logger=logger)

    if voter_on_stage_found:
        try:
            # Update existing voter
            if first_name is not False:
                voter_on_stage.first_name = first_name
                at_least_one_value_changed = True
            if last_name is not False:
                voter_on_stage.last_name = last_name
                at_least_one_value_changed = True
            if twitter_handle is not False:
                voter_on_stage.twitter_screen_name = twitter_handle
                at_least_one_value_changed = True
            if email is not False:
                voter_on_stage.email = email
                at_least_one_value_changed = True
            if password_text is not False:
                voter_on_stage.set_password(password_text)
                at_least_one_value_changed = True

            if at_least_one_value_changed:
                voter_on_stage.save()

            if password_text:
                # Check to see if a login has already been created
                pass
            messages.add_message(request, messages.INFO,
                                 'Voter information updated.')
        except Exception as e:
            handle_record_not_saved_exception(e, logger=logger)
            messages.add_message(request, messages.ERROR,
                                 'Could not save voter.')
    else:
        try:
            # Create new
            voter_on_stage = Voter.objects.create_user(email, email,
                                                       password_text)

            # Update new voter
            if first_name is not False:
                voter_on_stage.first_name = first_name
                at_least_one_value_changed = True
            if last_name is not False:
                voter_on_stage.last_name = last_name
                at_least_one_value_changed = True
            if twitter_handle is not False:
                voter_on_stage.twitter_screen_name = twitter_handle
                at_least_one_value_changed = True
            if email is not False:
                voter_on_stage.email = email
                at_least_one_value_changed = True

            if at_least_one_value_changed:
                voter_on_stage.save()

            messages.add_message(request, messages.INFO, 'Added new Voter.')
        except Exception as e:
            messages.add_message(request, messages.ERROR,
                                 'Could not save voter.')

    return HttpResponseRedirect(reverse('voter:voter_edit', args=(voter_id, )))
示例#48
0
def import_maplight_contest_office_candidates_from_array(
        politicians_running_for_one_contest_array):
    maplight_contest_office_saved = False  # Has the contest these politicians are running for been saved?
    maplight_contest_office_manager = MapLightContestOfficeManager()
    maplight_candidate_manager = MapLightCandidateManager()

    loop_count = 0
    loop_count_limit = 1

    for politician_id in politicians_running_for_one_contest_array:
        one_politician_array = politicians_running_for_one_contest_array[
            politician_id]

        # Save the office_contest so we can link the politicians to it first

        if not maplight_contest_office_saved:
            maplight_contest_office = MapLightContestOffice()
            if 'contest' in one_politician_array:
                maplight_contest_array = one_politician_array['contest']
                if 'office' in maplight_contest_array:
                    maplight_contest_office_array = maplight_contest_array[
                        'office']
                if 'id' in maplight_contest_array:
                    maplight_contest_id = maplight_contest_array['id']
                    maplight_contest_office = \
                        maplight_contest_office_manager.fetch_maplight_contest_office_from_id_maplight(
                            maplight_contest_id)

            # If an internal identifier is found, then we know we have an object
            if maplight_contest_office.id:
                maplight_contest_office_saved = True
                # try:
                #     maplight_contest_office.contest_id = maplight_contest_array['id']
                #     maplight_contest_office.election_date = maplight_contest_array['election_date']
                #     maplight_contest_office.title = maplight_contest_array['title']
                #     maplight_contest_office.type = maplight_contest_array['type']
                #     maplight_contest_office.url = maplight_contest_array['url']
                #     # Save into this db the 'office'?
                #     # Save into this db the 'jurisdiction'?
                #     maplight_contest_office.save()
                #     maplight_contest_office_saved = True
                #
                # except Exception as e:
                #     handle_record_not_saved_exception(e)
            else:
                try:
                    maplight_contest_office = MapLightContestOffice(
                        contest_id=maplight_contest_array['id'],
                        election_date=maplight_contest_array['election_date'],
                        title=maplight_contest_array['title'],
                        type=maplight_contest_array['type'],
                        url=maplight_contest_array['url'],
                    )
                    # Save into this db the 'office'?
                    # Save into this db the 'jurisdiction'?
                    maplight_contest_office.save()
                    maplight_contest_office_saved = True

                except Exception as e:
                    handle_record_not_saved_exception(e)

        maplight_candidate = maplight_candidate_manager.fetch_maplight_candidate_from_candidate_id_maplight(
            one_politician_array['candidate_id'])

        if maplight_candidate.id:
            print "Candidate {display_name} previously saved. To Update?".format(
                display_name=maplight_candidate.display_name)
        else:
            # Not found in the MapLightCandidate database, so we need to save
            try:
                maplight_candidate = MapLightCandidate()
                maplight_candidate.politician_id = one_politician_array[
                    'politician_id']
                maplight_candidate.candidate_id = one_politician_array[
                    'candidate_id']
                maplight_candidate.display_name = one_politician_array[
                    'display_name']
                maplight_candidate.original_name = one_politician_array[
                    'original_name']
                maplight_candidate.gender = one_politician_array['gender']
                maplight_candidate.first_name = one_politician_array[
                    'first_name']
                maplight_candidate.middle_name = one_politician_array[
                    'middle_name']
                maplight_candidate.last_name = one_politician_array[
                    'last_name']
                maplight_candidate.name_prefix = one_politician_array[
                    'name_prefix']
                maplight_candidate.name_suffix = one_politician_array[
                    'name_suffix']
                maplight_candidate.bio = one_politician_array['bio']
                maplight_candidate.party = one_politician_array['party']
                maplight_candidate.candidate_flags = one_politician_array[
                    'candidate_flags']
                if validate_maplight_date(
                        one_politician_array['last_funding_update']):
                    maplight_candidate.last_funding_update = one_politician_array[
                        'last_funding_update']
                maplight_candidate.roster_name = one_politician_array[
                    'roster_name']
                maplight_candidate.photo = one_politician_array['photo']
                maplight_candidate.url = one_politician_array['url']

                maplight_candidate.save()
                print "Candidate {display_name} added".format(
                    display_name=maplight_candidate.display_name)

            except Exception as e:
                handle_record_not_saved_exception(e)
示例#49
0
    def update_or_create_quick_info(
            self, quick_info_id, quick_info_we_vote_id,
            ballot_item_display_name, contest_office_we_vote_id,
            candidate_campaign_we_vote_id, politician_we_vote_id,
            contest_measure_we_vote_id, info_html, info_text, language,
            last_editor_we_vote_id, quick_info_master_we_vote_id,
            more_info_url, more_info_credit, google_civic_election_id):
        # Does a quick_info entry already exist?
        quick_info_manager = QuickInfoManager()
        results = quick_info_manager.retrieve_quick_info(
            quick_info_id, quick_info_we_vote_id, contest_office_we_vote_id,
            candidate_campaign_we_vote_id, politician_we_vote_id,
            contest_measure_we_vote_id)

        quick_info_on_stage_found = False
        quick_info_on_stage_id = 0
        quick_info_on_stage = QuickInfo()
        if results['quick_info_found']:
            quick_info_on_stage = results['quick_info']

            # Update this quick_info entry with new values - we do not delete because we might be able to use
            # noinspection PyBroadException
            try:
                # Figure out if the update is a change to a master entry
                if positive_value_exists(quick_info_master_we_vote_id):
                    uses_master_entry = True
                elif (info_html is not False) or (info_text is not False) or (
                        more_info_url is not False):
                    uses_master_entry = False
                elif positive_value_exists(quick_info_on_stage.info_textx) or \
                        positive_value_exists(quick_info_on_stage.info_html) or \
                        positive_value_exists(quick_info_on_stage.more_info_url):
                    uses_master_entry = False
                elif positive_value_exists(
                        quick_info_on_stage.quick_info_master_we_vote_id):
                    uses_master_entry = True
                else:
                    uses_master_entry = True

                if ballot_item_display_name is not False:
                    quick_info_on_stage.ballot_item_display_name = ballot_item_display_name
                if language is not False:
                    quick_info_on_stage.language = language
                if last_editor_we_vote_id is not False:
                    quick_info_on_stage.last_editor_we_vote_id = last_editor_we_vote_id
                if contest_office_we_vote_id is not False:
                    quick_info_on_stage.contest_office_we_vote_id = contest_office_we_vote_id
                if candidate_campaign_we_vote_id is not False:
                    quick_info_on_stage.candidate_campaign_we_vote_id = candidate_campaign_we_vote_id
                if politician_we_vote_id is not False:
                    quick_info_on_stage.politician_we_vote_id = politician_we_vote_id
                if contest_measure_we_vote_id is not False:
                    quick_info_on_stage.contest_measure_we_vote_id = contest_measure_we_vote_id
                if google_civic_election_id is not False:
                    quick_info_on_stage.google_civic_election_id = google_civic_election_id
                if uses_master_entry:
                    if quick_info_master_we_vote_id is not False:
                        quick_info_on_stage.quick_info_master_we_vote_id = quick_info_master_we_vote_id
                    # Clear out unique entry values
                    quick_info_on_stage.info_text = ""
                    quick_info_on_stage.info_html = ""
                    quick_info_on_stage.more_info_url = ""
                    quick_info_on_stage.more_info_credit = NOT_SPECIFIED
                else:
                    # If here, this is NOT a master entry
                    if info_text is not False:
                        quick_info_on_stage.info_text = info_text
                    if info_html is not False:
                        quick_info_on_stage.info_html = info_html
                    if more_info_url is not False:
                        quick_info_on_stage.more_info_url = more_info_url
                    if more_info_credit is not False:
                        quick_info_on_stage.more_info_credit = more_info_credit
                    # Clear out master entry value
                    quick_info_on_stage.quick_info_master_we_vote_id = ""
                if google_civic_election_id is not False:
                    quick_info_on_stage.google_civic_election_id = google_civic_election_id
                # We don't need to update date_last_changed here because set set auto_now=True in the field
                quick_info_on_stage.save()
                quick_info_on_stage_id = quick_info_on_stage.id
                quick_info_on_stage_found = True
                status = 'QUICK_INFO_UPDATED'
            except Exception as e:
                status = 'FAILED_TO_UPDATE_QUICK_INFO'
        elif results['MultipleObjectsReturned']:
            status = 'QUICK_INFO MultipleObjectsReturned'
        elif results['DoesNotExist']:
            try:
                # Create new quick_info entry
                if ballot_item_display_name is False:
                    ballot_item_display_name = ""
                if language is False:
                    language = ENGLISH
                if last_editor_we_vote_id is False:
                    last_editor_we_vote_id = ""
                if contest_office_we_vote_id is False:
                    contest_office_we_vote_id = ""
                if candidate_campaign_we_vote_id is False:
                    candidate_campaign_we_vote_id = ""
                if politician_we_vote_id is False:
                    politician_we_vote_id = ""
                if contest_measure_we_vote_id is False:
                    contest_measure_we_vote_id = ""
                if google_civic_election_id is False:
                    google_civic_election_id = 0
                # Master related data
                if quick_info_master_we_vote_id is False:
                    quick_info_master_we_vote_id = ""
                # Unique related data
                if info_html is False:
                    info_html = ""
                if info_text is False:
                    info_text = ""
                if more_info_url is False:
                    more_info_url = ""
                if more_info_credit is False:
                    more_info_credit = None
                quick_info_on_stage = QuickInfo(
                    ballot_item_display_name=ballot_item_display_name,
                    contest_office_we_vote_id=contest_office_we_vote_id,
                    candidate_campaign_we_vote_id=candidate_campaign_we_vote_id,
                    politician_we_vote_id=politician_we_vote_id,
                    contest_measure_we_vote_id=contest_measure_we_vote_id,
                    info_html=info_html,
                    info_text=info_text,
                    language=language,
                    last_editor_we_vote_id=last_editor_we_vote_id,
                    quick_info_master_we_vote_id=quick_info_master_we_vote_id,
                    more_info_url=more_info_url,
                    more_info_credit=more_info_credit,
                    google_civic_election_id=google_civic_election_id
                    # We don't need to update last_updated here because set set auto_now=True in the field
                )
                quick_info_on_stage.save()
                quick_info_on_stage_id = quick_info_on_stage.id
                quick_info_on_stage_found = True
                status = 'CREATED_QUICK_INFO'
            except Exception as e:
                status = 'FAILED_TO_CREATE_NEW_QUICK_INFO'
                handle_record_not_saved_exception(
                    e, logger=logger, exception_message_optional=status)
        else:
            status = results['status']

        results = {
            'success': True if quick_info_on_stage_found else False,
            'status': status,
            'quick_info_found': quick_info_on_stage_found,
            'quick_info_id': quick_info_on_stage_id,
            'quick_info': quick_info_on_stage,
        }
        return results
示例#50
0
    def update_or_create_quick_info_master(
        self,
        quick_info_master_id,
        quick_info_master_we_vote_id,
        master_entry_name,
        info_html,
        info_text,
        language,
        kind_of_ballot_item,
        last_editor_we_vote_id,
        more_info_url,
        more_info_credit,
    ):
        # Does a quick_info_master entry already exist?
        quick_info_master_manager = QuickInfoMasterManager()
        if positive_value_exists(
                quick_info_master_id) or positive_value_exists(
                    quick_info_master_we_vote_id):
            results = quick_info_master_manager.retrieve_quick_info_master(
                quick_info_master_id, quick_info_master_we_vote_id)
            quick_info_master_found = results['quick_info_master_found']
        else:
            quick_info_master_found = False

        if quick_info_master_found:
            quick_info_master = results['quick_info_master']

            # noinspection PyBroadException
            try:
                if master_entry_name is not False:
                    quick_info_master.master_entry_name = master_entry_name
                if info_html is not False:
                    quick_info_master.info_html = info_html
                if info_text is not False:
                    quick_info_master.info_text = info_text
                if language is not False:
                    quick_info_master.language = language
                if kind_of_ballot_item is not False:
                    quick_info_master.kind_of_ballot_item = kind_of_ballot_item
                if last_editor_we_vote_id is not False:
                    quick_info_master.last_editor_we_vote_id = last_editor_we_vote_id
                if more_info_url is not False:
                    quick_info_master.more_info_url = more_info_url
                if more_info_credit is not False:
                    quick_info_master.more_info_credit = more_info_credit
                # We don't need to update date_last_changed here because set set auto_now=True in the field
                quick_info_master.save()
                quick_info_master_id = quick_info_master.id
                quick_info_master_found = True
                status = 'QUICK_INFO_MASTER_UPDATED'
            except Exception as e:
                status = 'FAILED_TO_UPDATE_QUICK_INFO_MASTER'
        else:
            try:
                # Create new quick_info_master entry
                # Create new quick_info entry
                if master_entry_name is False:
                    master_entry_name = None
                if info_html is False:
                    info_html = None
                if info_text is False:
                    info_text = None
                if language is False:
                    language = ENGLISH
                if last_editor_we_vote_id is False:
                    last_editor_we_vote_id = None
                if more_info_url is False:
                    more_info_url = None
                if more_info_credit is False:
                    more_info_credit = None
                quick_info_master = QuickInfoMaster(
                    master_entry_name=master_entry_name,
                    info_html=info_html,
                    info_text=info_text,
                    language=language,
                    kind_of_ballot_item=kind_of_ballot_item,
                    last_editor_we_vote_id=last_editor_we_vote_id,
                    more_info_url=more_info_url,
                    more_info_credit=more_info_credit,
                    # We don't need to update last_updated here because set set auto_now=True in the field
                )
                quick_info_master.save()
                quick_info_master_id = quick_info_master.id
                quick_info_master_found = True
                status = 'CREATED_QUICK_INFO_MASTER'
            except Exception as e:
                status = 'FAILED_TO_CREATE_NEW_QUICK_INFO_MASTER'
                handle_record_not_saved_exception(
                    e, logger=logger, exception_message_optional=status)

        results = {
            'success': True if quick_info_master_found else False,
            'status': status,
            'quick_info_master_found': quick_info_master_found,
            'quick_info_master_id': quick_info_master_id,
            'quick_info_master': quick_info_master,
        }
        return results
示例#51
0
def import_we_vote_organizations_from_json(request, load_from_uri=False):
    """
    Get the json data, and either create new entries or update existing
    :return:
    """
    if load_from_uri:
        # Request json file from We Vote servers
        logger.info("Loading Organizations from We Vote Master servers")
        request = requests.get(
            ORGANIZATIONS_URL,
            params={
                "key":
                WE_VOTE_API_KEY,  # This comes from an environment variable
            })
        structured_json = json.loads(request.text)
    else:
        # Load saved json from local file
        logger.info("Loading organizations from local file")

        with open(ORGANIZATIONS_JSON_FILE) as json_data:
            structured_json = json.load(json_data)

    for one_organization in structured_json:
        logger.debug(
            u"id_we_vote: {id_we_vote}, name: {name}, url: {url}".format(
                **one_organization))
        # Make sure we have the minimum required variables
        if len(one_organization["id_we_vote"]) == 0 or len(
                one_organization["name"]) == 0:
            continue

        # Check to see if this organization is already being used anywhere
        organization_on_stage_found = False
        try:
            if len(one_organization["id_we_vote"]) > 0:
                organization_query = Organization.objects.filter(
                    id_we_vote=one_organization["id_we_vote"])
                if len(organization_query):
                    organization_on_stage = organization_query[0]
                    organization_on_stage_found = True
            elif len(one_organization["name"]) > 0:
                organization_query = Organization.objects.filter(
                    name=one_organization["name"])
                if len(organization_query):
                    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
                organization_on_stage.id_we_vote = one_organization[
                    "id_we_vote"]
                organization_on_stage.name = one_organization["name"]
                organization_on_stage.url = one_organization["url"]
                organization_on_stage.save()
                messages.add_message(
                    request, messages.INFO,
                    u"Organization updated: {name}".format(
                        name=one_organization["name"]))
            else:
                # Create new
                organization_on_stage = Organization(
                    id_we_vote=one_organization["id_we_vote"],
                    name=one_organization["name"],
                    url=one_organization["url"],
                )
                organization_on_stage.save()
                messages.add_message(
                    request, messages.INFO,
                    u"New organization imported: {name}".format(
                        name=one_organization["name"]))
        except Exception as e:
            handle_record_not_saved_exception(e, logger=logger)
            messages.add_message(
                request, messages.ERROR,
                u"Could not save Organization, id_we_vote: {id_we_vote}, name: {name}, url: {url}"
                .format(
                    id_we_vote=one_organization["id_we_vote"],
                    name=one_organization["name"],
                    url=one_organization["url"],
                ))
示例#52
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['organization_id'])
    organization_name = request.POST['organization_name']
    organization_twitter_handle = request.POST.get('organization_twitter_handle', '')
    organization_facebook = request.POST.get('organization_facebook', '')
    organization_website = request.POST['organization_website']
    wikipedia_page_title = request.POST.get('wikipedia_page_title', '')
    wikipedia_photo_url = request.POST.get('wikipedia_photo_url', '')

    # 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
            organization_on_stage.organization_name = organization_name
            organization_on_stage.organization_twitter_handle = organization_twitter_handle
            organization_on_stage.organization_facebook = organization_facebook
            organization_on_stage.organization_website = organization_website
            organization_on_stage.wikipedia_page_title = wikipedia_page_title
            organization_on_stage.wikipedia_photo_url = wikipedia_photo_url
            organization_on_stage.save()
            organization_id = organization_on_stage.id
            messages.add_message(request, messages.INFO, 'Organization updated.')
            return HttpResponseRedirect(reverse('organization:organization_position_list', args=(organization_id,)))
        else:
            # Create new
            organization_on_stage = Organization(
                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,
            )
            organization_on_stage.save()
            organization_id = organization_on_stage.id
            messages.add_message(request, messages.INFO, 'New organization saved.')
            return HttpResponseRedirect(reverse('organization:organization_position_list', args=(organization_id,)))
    except Exception as e:
        handle_record_not_saved_exception(e, logger=logger)
        messages.add_message(request, messages.ERROR, 'Could not save organization.'
                                                      ' {error} [type: {error_type}]'.format(error=e.message,
                                                                                             error_type=type(e)))

    return HttpResponseRedirect(reverse('organization:organization_list', args=()))
def quick_info_import_from_sample_file(
        request=None):  # , load_from_uri=False  # TODO to be converted
    """
    Get the json data, and either create new entries or update existing
    :return:
    """
    # if load_from_uri:
    #     # Request json file from We Vote servers
    #     messages.add_message(request, messages.INFO, "Loading quick_info from We Vote Master servers")
    #     request = requests.get(QUICK_INFO_URL, params={
    #         "key": WE_VOTE_API_KEY,  # This comes from an environment variable
    #     })
    #     structured_json = json.loads(request.text)
    # else:
    # Load saved json from local file
    with open("quick_info/import_data/quick_info_sample.json") as json_data:
        structured_json = json.load(json_data)

    quick_info_saved = 0
    quick_info_updated = 0
    quick_info_not_processed = 0
    for one_quick_info in structured_json:
        # Make sure we have the minimum required variables
        if not positive_value_exists(one_quick_info["we_vote_id"]) \
                or not positive_value_exists(one_quick_info["organization_we_vote_id"])\
                or not positive_value_exists(one_quick_info["candidate_campaign_we_vote_id"]):
            quick_info_not_processed += 1
            continue

        # Check to see if this quick_info is already being used anywhere
        quick_info_found = False
        try:
            if len(one_quick_info["we_vote_id"]) > 0:
                quick_info_query = QuickInfo.objects.filter(
                    we_vote_id=one_quick_info["we_vote_id"])
                if len(quick_info_query):
                    quick_info = quick_info_query[0]
                    quick_info_found = True
        except QuickInfo.DoesNotExist as e:
            handle_record_not_found_exception(e, logger=logger)
            pass
        except Exception as e:
            handle_record_not_found_exception(e, logger=logger)

        # We need to look up the local organization_id based on the newly saved we_vote_id
        organization_manager = OrganizationManager()
        organization_id = organization_manager.fetch_organization_id(
            one_quick_info["organization_we_vote_id"])

        # We need to look up the local candidate_campaign_id
        candidate_campaign_manager = CandidateCampaignManager()
        candidate_campaign_id = candidate_campaign_manager.fetch_candidate_campaign_id_from_we_vote_id(
            one_quick_info["candidate_campaign_we_vote_id"])

        # Find the google_civic_candidate_name so we have a backup way to link quick_info if the we_vote_id is lost
        google_civic_candidate_name = one_quick_info["google_civic_candidate_name"] if \
            "google_civic_candidate_name" in one_quick_info else ''
        if not positive_value_exists(google_civic_candidate_name):
            google_civic_candidate_name = candidate_campaign_manager.fetch_google_civic_candidate_name_from_we_vote_id(
                one_quick_info["candidate_campaign_we_vote_id"])

        # TODO We need to look up contest_measure_id
        contest_measure_id = 0

        try:
            if quick_info_found:
                # Update
                quick_info.we_vote_id = one_quick_info["we_vote_id"]
                quick_info.organization_id = organization_id
                quick_info.organization_we_vote_id = one_quick_info[
                    "organization_we_vote_id"]
                quick_info.candidate_campaign_id = candidate_campaign_id
                quick_info.candidate_campaign_we_vote_id = one_quick_info[
                    "candidate_campaign_we_vote_id"]
                quick_info.google_civic_candidate_name = google_civic_candidate_name
                quick_info.contest_measure_id = contest_measure_id
                quick_info.date_entered = one_quick_info["date_entered"]
                quick_info.google_civic_election_id = one_quick_info[
                    "google_civic_election_id"]
                quick_info.stance = one_quick_info["stance"]
                quick_info.more_info_url = one_quick_info["more_info_url"]
                quick_info.statement_text = one_quick_info["statement_text"]
                quick_info.statement_html = one_quick_info["statement_html"]
                quick_info.save()
                quick_info_updated += 1
                # messages.add_message(request, messages.INFO, u"QuickInfo updated: {we_vote_id}".format(
                #     we_vote_id=one_quick_info["we_vote_id"]))
            else:
                # Create new
                quick_info = QuickInfo(
                    we_vote_id=one_quick_info["we_vote_id"],
                    organization_id=organization_id,
                    organization_we_vote_id=one_quick_info[
                        "organization_we_vote_id"],
                    candidate_campaign_id=candidate_campaign_id,
                    candidate_campaign_we_vote_id=one_quick_info[
                        "candidate_campaign_we_vote_id"],
                    google_civic_candidate_name=google_civic_candidate_name,
                    contest_measure_id=contest_measure_id,
                    date_entered=one_quick_info["date_entered"],
                    google_civic_election_id=one_quick_info[
                        "google_civic_election_id"],
                    stance=one_quick_info["stance"],
                    more_info_url=one_quick_info["more_info_url"],
                    statement_text=one_quick_info["statement_text"],
                    statement_html=one_quick_info["statement_html"],
                )
                quick_info.save()
                quick_info_saved += 1
                # messages.add_message(request, messages.INFO, u"New quick_info imported: {we_vote_id}".format(
                #     we_vote_id=one_quick_info["we_vote_id"]))
        except Exception as e:
            handle_record_not_saved_exception(e, logger=logger)
            if request is not None:
                messages.add_message(
                    request, messages.ERROR,
                    u"Could not save/update quick_info, "
                    u"quick_info_found: {quick_info_found}, "
                    u"we_vote_id: {we_vote_id}, "
                    u"organization_we_vote_id: {organization_we_vote_id}, "
                    u"candidate_campaign_we_vote_id: {candidate_campaign_we_vote_id}"
                    .format(
                        quick_info_found=quick_info_found,
                        we_vote_id=one_quick_info["we_vote_id"],
                        organization_we_vote_id=one_quick_info[
                            "organization_we_vote_id"],
                        candidate_campaign_we_vote_id=one_quick_info[
                            "candidate_campaign_we_vote_id"],
                    ))
            quick_info_not_processed += 1

    quick_info_results = {
        'saved': quick_info_saved,
        'updated': quick_info_updated,
        'not_processed': quick_info_not_processed,
    }
    return quick_info_results
示例#54
0
def organization_save_new_or_edit_existing_position_process_form_view(request):
    """

    :param request:
    :return:
    """
    organization_id = convert_to_int(request.POST['organization_id'])
    position_id = convert_to_int(request.POST['position_id'])
    candidate_campaign_id = convert_to_int(
        request.POST['candidate_campaign_id'])
    measure_campaign_id = convert_to_int(request.POST['measure_campaign_id'])
    stance = request.POST.get(
        'stance', SUPPORT)  # Set a default if stance comes in empty
    statement_text = request.POST.get(
        'statement_text', '')  # Set a default if stance comes in empty
    more_info_url = request.POST.get('more_info_url', '')

    # Make sure this is a valid organization before we try to save a position
    organization_on_stage_found = False
    try:
        organization_query = Organization.objects.filter(id=organization_id)
        if len(organization_query):
            # organization_on_stage = organization_query[0]
            organization_on_stage_found = True
    except Exception as e:
        # If we can't retrieve the organization, we cannot proceed
        handle_record_not_found_exception(e, logger=logger)

    if not organization_on_stage_found:
        messages.add_message(
            request, messages.ERROR,
            "Could not find the organization when trying to create or edit a new position."
        )
        return HttpResponseRedirect(
            reverse('organization:organization_list', args=()))

    # Now retrieve the CandidateCampaign or the MeasureCampaign so we can save it with the Position
    # We need either candidate_campaign_id or measure_campaign_id
    if candidate_campaign_id:
        try:
            candidate_campaign_on_stage = CandidateCampaign.objects.get(
                id=candidate_campaign_id)
            candidate_campaign_on_stage_found = True
        except CandidateCampaign.MultipleObjectsReturned as e:
            handle_record_found_more_than_one_exception(e, logger=logger)
        except CandidateCampaign.DoesNotExist as e:
            handle_record_not_found_exception(e, logger=logger)

        if not candidate_campaign_on_stage_found:
            messages.add_message(
                request, messages.ERROR,
                "Could not find Candidate's campaign when trying to create or edit a new position."
            )
            if position_id:
                return HttpResponseRedirect(
                    reverse('organization:organization_position_edit',
                            args=([organization_id], [position_id])))
            else:
                return HttpResponseRedirect(
                    reverse('organization:organization_position_new',
                            args=([organization_id])))
    elif measure_campaign_id:
        logger.warn(
            "measure_campaign_id FOUND. Look for MeasureCampaign here.")

    else:
        logger.warn(
            "Neither candidate_campaign_id nor measure_campaign_id found")
        messages.add_message(request, messages.ERROR,
                             "Unable to find either Candidate or Measure.")
        return HttpResponseRedirect(
            reverse('organization:organization_position_list',
                    args=([organization_id])))

    organization_position_on_stage_found = False
    logger.info("position_id: {position_id}".format(position_id=position_id))

    # Retrieve position from position_id if it exists already
    if position_id > 0:
        position_entered_manager = PositionEnteredManager()
        results = position_entered_manager.retrieve_position_from_id(
            position_id)
        if results['position_found']:
            organization_position_on_stage_found = True
            organization_position_on_stage = results['position']

    if not organization_position_on_stage_found:
        # If a position_id hasn't been passed in, then we are trying to create a new position.
        # Check to make sure a position for this org and candidate doesn't already exist

        position_entered_manager = PositionEnteredManager()
        results = position_entered_manager.retrieve_organization_candidate_campaign_position(
            organization_id, candidate_campaign_id)

        if results['MultipleObjectsReturned']:
            messages.add_message(
                request, messages.ERROR,
                "We found more than one existing positions for this candidate. Please delete all but one position."
            )
            return HttpResponseRedirect(
                reverse('organization:organization_position_list',
                        args=([organization_id])))
        elif results['position_found']:
            organization_position_on_stage_found = True
            organization_position_on_stage = results['position']

    # Now save existing, or create new
    try:
        if organization_position_on_stage_found:
            # Update the position
            organization_position_on_stage.stance = stance
            organization_position_on_stage.statement_text = statement_text
            organization_position_on_stage.more_info_url = more_info_url
            organization_position_on_stage.save()
            messages.add_message(
                request, messages.INFO,
                "Position on {candidate_name} updated.".format(
                    candidate_name=candidate_campaign_on_stage.candidate_name))
        else:
            # Create new
            organization_position_on_stage = PositionEntered(
                organization_id=organization_id,
                candidate_campaign_id=candidate_campaign_on_stage.id,
                stance=stance,
                statement_text=statement_text,
                more_info_url=more_info_url,
            )
            organization_position_on_stage.save()
            messages.add_message(
                request, messages.INFO,
                "New position on {candidate_name} saved.".format(
                    candidate_name=candidate_campaign_on_stage.candidate_name))
    except Exception as e:
        handle_record_not_saved_exception(e, logger=logger)
        logger.error("Problem saving PositionEntered for CandidateCampaign")

    return HttpResponseRedirect(
        reverse('organization:organization_position_list',
                args=([organization_id])))
示例#55
0
def google_civic_get_or_create_contest_office(
        google_civic_candidate_campaign_entry, election_on_stage):
    error_result = False
    ballot_item_on_stage_found = False
    try:
        # When we import from google, we link a google_civic_contest_office entry (with an internal id) to
        #  google_civic_candidate_campaign_entry
        # print "Retrieving google_civic_contest_office"
        google_civic_contest_office_query = GoogleCivicContestOffice.objects.all(
        )
        google_civic_contest_office_query = google_civic_contest_office_query.filter(
            id=google_civic_candidate_campaign_entry.
            google_civic_contest_office_id)

        if len(google_civic_contest_office_query) == 1:
            google_civic_contest_office_on_stage = google_civic_contest_office_query[
                0]
        else:
            print "Single google_civic_contest_office NOT found"
            return {
                'error_result': True,
            }

        # Try to find earlier version based on the google_civic_election_id identifier
        # print "Retrieving contest_office"
        contest_office_query = ContestOffice.objects.all()
        contest_office_query = contest_office_query.filter(
            google_civic_election_id=google_civic_contest_office_on_stage.
            google_civic_election_id)
        contest_office_query = contest_office_query.filter(
            district_name=google_civic_contest_office_on_stage.district_name)
        contest_office_query = contest_office_query.filter(
            office_name=google_civic_contest_office_on_stage.office)
        # TODO: If the 'office' text from Google Civic changes slightly, we would create a new ContestOffice entry
        # (which would not be correct) Should we make this more robust and error-proof?

        # Was at least one existing entry found based on the above criteria?
        if len(contest_office_query):
            contest_office_on_stage = contest_office_query[0]
            contest_office_created = False

            # TODO Update contest_office information here
        elif len(contest_office_query) > 1:
            # We have bad data - a duplicate
            print "We have bad data, a duplicate ContestOffice entry: {office}".format(
                office=google_civic_contest_office_on_stage.office)
            return {
                'error_result': True,
            }
        else:
            # Create a new ContestOffice entry
            # print "Creating contest_office"
            contest_office_on_stage = ContestOffice(
                office_name=google_civic_contest_office_on_stage.office,
                election_id=election_on_stage.id,
                google_civic_election_id=google_civic_contest_office_on_stage.
                google_civic_election_id,
                number_voting_for=google_civic_contest_office_on_stage.
                number_voting_for,
                number_elected=google_civic_contest_office_on_stage.
                number_elected,
                primary_party=google_civic_contest_office_on_stage.
                primary_party,
                district_name=google_civic_contest_office_on_stage.
                district_name,
                district_scope=google_civic_contest_office_on_stage.
                district_scope,
                district_ocd_id=google_civic_contest_office_on_stage.
                district_ocd_id,
            )
            contest_office_on_stage.save()
            contest_office_created = True

        google_civic_contest_office_on_stage.we_vote_election_id = election_on_stage.id
        google_civic_contest_office_on_stage.we_vote_contest_office_id = contest_office_on_stage.id
        google_civic_contest_office_on_stage.save()

        # Save the ballot_placement
        # Try to find earlier version based on the google_civic_election_id identifier
        # print "Retrieving BallotItemCache"
        ballot_item_query = BallotItemCache.objects.all()
        ballot_item_query = ballot_item_query.filter(voter_id=1)
        ballot_item_query = ballot_item_query.filter(
            google_civic_election_id=google_civic_contest_office_on_stage.
            google_civic_election_id)
        ballot_item_query = ballot_item_query.filter(
            contest_office_id=contest_office_on_stage.id)
        if len(ballot_item_query) == 1:
            ballot_item_on_stage = ballot_item_query[0]
            ballot_item_on_stage_found = True
    except Exception as e:
        error_result = True
        handle_record_not_found_exception(e)

    try:
        if ballot_item_on_stage_found:
            # Update the values
            ballot_item_on_stage.election_id = election_on_stage.id
            # TODO Add all values here
        else:
            # print "Creating BallotItemCache"
            ballot_item_on_stage = BallotItemCache(
                voter_id=1,
                election_id=election_on_stage.id,
                google_civic_election_id=google_civic_contest_office_on_stage.
                google_civic_election_id,
                contest_office_id=contest_office_on_stage.id,
                # contest_measure_id: Used for measures/referendum/initiatives
                ballot_order=google_civic_contest_office_on_stage.
                ballot_placement,
                ballot_item_label=google_civic_contest_office_on_stage.office,
            )
        ballot_item_on_stage.save()
    except Exception as e:
        error_result = True
        handle_record_not_saved_exception(e)

    results = {
        'error_result': error_result,
        'contest_office_on_stage': contest_office_on_stage,
        'contest_office_created': contest_office_created,
    }
    return results
示例#56
0
def google_civic_get_or_create_politician(
        google_civic_candidate_campaign_entry):
    error_result = False
    ##########################
    # Does this politician exist locally?
    politician_on_stage_found = False
    first_name_guess = google_civic_candidate_campaign_entry.name.partition(
        ' ')[0]
    last_name_guess = google_civic_candidate_campaign_entry.name.partition(
        ' ')[-1]
    try:
        # print "We are searching based on full_name_google_civic"
        query1 = Politician.objects.all()
        query1 = query1.filter(
            full_name_google_civic=google_civic_candidate_campaign_entry.name)

        # Was at least one existing entry found based on the above criteria?
        if len(query1):
            politician_on_stage = query1[0]
            politician_on_stage_found = True
            if len(query1) > 1:
                # We have confusion, so skip processing this google_civic_candidate_campaign_entry
                print "More than one Politician found (query1)"
        else:
            print "No politician found based on full_name_google_civic: {name}".format(
                name=google_civic_candidate_campaign_entry.name)
    except Exception as e:
        handle_record_not_found_exception(e)

    if not politician_on_stage_found:
        # No entries were found, so we need to
        # a) Search more deeply
        # Searching based on full_name_assembled
        print "Searching against full_name_assembled: {name}".format(
            name=google_civic_candidate_campaign_entry.name)
        # TODO DALE 2015-05-02 With this code, if we had imported a "Betty T. Yee" from another non-google-civic
        #  source (where full_name_google_civic was empty), we would create a second Politician entry. Fix this.
        try:
            politician_query_full_name_assembled = Politician.objects.all()
            politician_query_full_name_assembled = politician_query_full_name_assembled.filter(
                full_name_assembled=google_civic_candidate_campaign_entry.name)

            if len(politician_query_full_name_assembled):
                politician_on_stage = politician_query_full_name_assembled[0]
                politician_on_stage_found = True
            else:
                print "No politician found based on full_name_assembled: {name}".format(
                    name=google_civic_candidate_campaign_entry.name)
        except Exception as e:
            handle_record_not_found_exception(e)

    if not politician_on_stage_found:
        # No entries were found, so we need to
        # a) Search more deeply
        print "first_name_guess: {first_name_guess}, last_name_guess: {last_name_guess}".format(
            first_name_guess=first_name_guess, last_name_guess=last_name_guess)
        # TODO DALE 2015-05-02 With this code, if we had imported a "Betty T. Yee" from another non-google-civic
        #  source (where full_name_google_civic was empty), we would create a second Politician entry. Fix this.
        try:
            politician_query_first_last_guess = Politician.objects.all()
            politician_query_first_last_guess = politician_query_first_last_guess.filter(
                first_name=first_name_guess)
            politician_query_first_last_guess = politician_query_first_last_guess.filter(
                last_name=last_name_guess)

            if len(politician_query_first_last_guess):
                politician_on_stage = politician_query_first_last_guess[0]
                politician_on_stage_found = True
            else:
                print "No politician found based on first_name_guess: {first_name} and last_name_guess: {last_name}".format(
                    first_name=first_name_guess, last_name=last_name_guess)
        except Exception as e:
            handle_record_not_found_exception(e)

    try:
        if politician_on_stage_found:
            # We found a match, and want to update the Politician data to match how Google Civic references the name
            # print "Store google_civic_candidate_campaign_entry.name in Politician.full_name_google_civic"
            politician_on_stage.full_name_google_civic = google_civic_candidate_campaign_entry.name
        else:
            # print "Create Politician entry: {name}".format(name=google_civic_candidate_campaign_entry.name)
            politician_on_stage = Politician(
                # Do not save first_name or last_name because middle initials will throw this off
                last_name=last_name_guess,
                first_name=first_name_guess,
                full_name_google_civic=google_civic_candidate_campaign_entry.
                name,
            )
        politician_on_stage.save()
    except Exception as e:
        handle_record_not_saved_exception(e)

    if error_result:
        print "There was an error trying to create a politician"
    # else:
    # print "It seems we have found a politician: {display_full_name}".format(display_full_name=politician_on_stage.display_full_name())
    # print "It seems we have found a politician: "+str(politician_on_stage.display_full_name())
    # print "It seems we found or created a politician."

    results = {
        'error_result': error_result,
        'politician_on_stage': politician_on_stage,
    }
    return results
示例#57
0
def import_we_vote_positions_from_json(request, load_from_uri=False):
    """
    Get the json data, and either create new entries or update existing
    :return:
    """
    if load_from_uri:
        # Request json file from We Vote servers
        messages.add_message(request, messages.INFO,
                             "Loading positions from We Vote Master servers")
        request = requests.get(
            POSITIONS_URL,
            params={
                "key":
                WE_VOTE_API_KEY,  # This comes from an environment variable
            })
        structured_json = json.loads(request.text)
    else:
        # Load saved json from local file
        messages.add_message(request, messages.INFO,
                             "Loading positions from local file")

        with open(POSITIONS_JSON_FILE) as json_data:
            structured_json = json.load(json_data)

    for one_position in structured_json:
        # Make sure we have the minimum required variables
        if len(one_position["id_we_vote"]) == 0 \
                or len(one_position["organization_id_we_vote"]) == 0\
                or len(one_position["candidate_campaign_id_we_vote"]) == 0:
            continue

        # Check to see if this position is already being used anywhere
        position_on_stage_found = False
        try:
            if len(one_position["id_we_vote"]) > 0:
                position_query = PositionEntered.objects.filter(
                    id_we_vote=one_position["id_we_vote"])
                if len(position_query):
                    position_on_stage = position_query[0]
                    position_on_stage_found = True
        except PositionEntered.DoesNotExist as e:
            pass
        except Exception as e:
            handle_record_not_found_exception(e, logger=logger)

        # We need to look up the local organization_id based on the newly saved we_vote_id
        organization_manager = OrganizationManager()
        organization_id = organization_manager.fetch_organization_id(
            one_position["organization_id_we_vote"])

        # We need to look up the local candidate_campaign_id
        candidate_campaign_manager = CandidateCampaignManager()
        candidate_campaign_id = candidate_campaign_manager.fetch_candidate_campaign_id_from_id_we_vote(
            one_position["candidate_campaign_id_we_vote"])

        # TODO We need to look up measure_campaign_id
        measure_campaign_id = 0

        try:
            if position_on_stage_found:
                # Update
                position_on_stage.id_we_vote = one_position["id_we_vote"]
                position_on_stage.organization_id = organization_id
                position_on_stage.candidate_campaign_id = candidate_campaign_id
                position_on_stage.measure_campaign_id = measure_campaign_id
                position_on_stage.date_entered = one_position["date_entered"]
                position_on_stage.election_id = one_position["election_id"]
                position_on_stage.stance = one_position["stance"]
                position_on_stage.more_info_url = one_position["more_info_url"]
                position_on_stage.statement_text = one_position[
                    "statement_text"]
                position_on_stage.statement_html = one_position[
                    "statement_html"]
                position_on_stage.save()
                messages.add_message(
                    request, messages.INFO,
                    u"Position updated: {id_we_vote}".format(
                        id_we_vote=one_position["id_we_vote"]))
            else:
                # Create new
                position_on_stage = PositionEntered(
                    id_we_vote=one_position["id_we_vote"],
                    organization_id=organization_id,
                    candidate_campaign_id=candidate_campaign_id,
                    measure_campaign_id=measure_campaign_id,
                    date_entered=one_position["date_entered"],
                    election_id=one_position["election_id"],
                    stance=one_position["stance"],
                    more_info_url=one_position["more_info_url"],
                    statement_text=one_position["statement_text"],
                    statement_html=one_position["statement_html"],
                )
                position_on_stage.save()
                messages.add_message(
                    request, messages.INFO,
                    u"New position imported: {id_we_vote}".format(
                        id_we_vote=one_position["id_we_vote"]))
        except Exception as e:
            handle_record_not_saved_exception(e, logger=logger)
            messages.add_message(
                request, messages.ERROR,
                u"Could not save position, id_we_vote: {id_we_vote}, "
                u"organization_id_we_vote: {organization_id_we_vote}, "
                u"candidate_campaign_id_we_vote: {candidate_campaign_id_we_vote}"
                .format(
                    id_we_vote=one_position["id_we_vote"],
                    organization_id_we_vote=one_position[
                        "organization_id_we_vote"],
                    candidate_campaign_id_we_vote=one_position[
                        "candidate_campaign_id_we_vote"],
                ))
示例#58
0
def import_we_vote_candidate_campaigns_from_json(request, load_from_uri=False):
    """
    Get the json data, and either create new entries or update existing
    :return:
    """
    if load_from_uri:
        # Request json file from We Vote servers
        messages.add_message(
            request, messages.INFO,
            "Loading CandidateCampaign IDs from We Vote Master servers")
        request = requests.get(
            CANDIDATE_CAMPAIGNS_URL,
            params={
                "key":
                WE_VOTE_API_KEY,  # This comes from an environment variable
            })
        structured_json = json.loads(request.text)
    else:
        # Load saved json from local file
        messages.add_message(request, messages.INFO,
                             "Loading CandidateCampaigns IDs from local file")

        with open(CANDIDATE_CAMPAIGNS_JSON_FILE) as json_data:
            structured_json = json.load(json_data)

    for one_candidate_campaign in structured_json:
        # For now we are only adding a We Vote ID so we can save Positions
        candidate_campaign_on_stage_found = False
        try:
            if len(one_candidate_campaign["candidate_name"]) > 0:
                candidate_campaign_query = CandidateCampaign.objects.filter(
                    candidate_name=one_candidate_campaign["candidate_name"])
                if len(candidate_campaign_query
                       ) == 1:  # Make sure only one found
                    candidate_campaign_on_stage = candidate_campaign_query[0]
                    candidate_campaign_on_stage_found = True
        except Exception as e:
            handle_record_not_found_exception(e, logger=logger)

        try:
            if candidate_campaign_on_stage_found:
                # Update
                candidate_campaign_on_stage.id_we_vote = one_candidate_campaign[
                    "id_we_vote"]
                candidate_campaign_on_stage.save()
                messages.add_message(
                    request, messages.INFO,
                    u"CandidateCampaign updated: {candidate_name}".format(
                        candidate_name=one_candidate_campaign["candidate_name"]
                    ))
            else:
                messages.add_message(
                    request, messages.ERROR,
                    u"CandidateCampaign not found: {candidate_name}".format(
                        candidate_name=one_candidate_campaign["candidate_name"]
                    ))
        except Exception as e:
            handle_record_not_saved_exception(e, logger=logger)
            messages.add_message(
                request, messages.ERROR,
                u"Could not save CandidateCampaign, id_we_vote: {id_we_vote}, "
                u"candidate_name: {candidate_name}, ".format(
                    id_we_vote=one_candidate_campaign["id_we_vote"],
                    candidate_name=one_candidate_campaign["candidate_name"],
                ))
示例#59
0
def google_civic_link_politician_to_campaign():

    # Bring in the GoogleCivicCandidateCampaign and save the CandidateCampaign
    google_civic_candidate_campaign_query = GoogleCivicCandidateCampaign.objects.all(
    )

    for google_civic_candidate_campaign_entry in google_civic_candidate_campaign_query:

        if not google_civic_candidate_campaign_entry.google_civic_election_id:
            print "We cannot proceed with {name} -- there is no google_civic_election_id".format(
                name=google_civic_candidate_campaign_entry.name)
            continue

        try:
            election_query = Election.objects.all()
            election_query = election_query.filter(
                google_civic_election_id=google_civic_candidate_campaign_entry.
                google_civic_election_id)

            if len(election_query) == 1:
                election_on_stage = election_query[0]
            else:
                print "ERROR: Break out of main loop without an election_on_stage -- single Election entry not found"
                continue
        except Exception as e:
            handle_record_not_found_exception(e)
            continue

        ###########################################
        # Election
        # The election is linked below

        ###########################################
        # ContestOffice
        # We want to find or create a We Vote ContestOffice
        results = google_civic_get_or_create_contest_office(
            google_civic_candidate_campaign_entry, election_on_stage)
        try:
            contest_office_error = results['error_result']
            if contest_office_error:
                print "ERROR returned in google_civic_get_or_create_contest_office "\
                      "(skipping to next google_civic_candidate_campaign_entry)"
                continue
            contest_office_on_stage = results['contest_office_on_stage']
            contest_office_created = results['contest_office_created']

            # Link this ContestOffice to the Election that was created above
            contest_office_on_stage.election_id = election_on_stage.id
            contest_office_on_stage.save(
            )  # We save here AND lower in case there are failures
        except Exception as e:
            handle_record_not_saved_exception(e)
            continue

        ###########################################
        # CandidateCampaign
        # We want to find or create a We Vote CandidateCampaign
        results = google_civic_get_or_create_candidate_campaign_basic(
            google_civic_candidate_campaign_entry)
        candidate_campaign_error = results['error_result']
        if candidate_campaign_error:
            print "ERROR returned in google_civic_get_or_create_candidate_campaign_basic "\
                  "(skipping to next google_civic_candidate_campaign_entry)"
            continue
        politician_link_needed = results['politician_link_needed']
        candidate_campaign_created = results['candidate_campaign_created']
        candidate_campaign_on_stage = results['candidate_campaign_on_stage']

        try:
            # Add/update campaign information
            candidate_campaign_on_stage.candidate_name = google_civic_candidate_campaign_entry.name
            candidate_campaign_on_stage.party = google_civic_candidate_campaign_entry.party

            # Link this CandidateCampaign to the Election and ContestOffice that was created above
            candidate_campaign_on_stage.election_id = election_on_stage.id
            candidate_campaign_on_stage.google_civic_election_id = \
                google_civic_candidate_campaign_entry.google_civic_election_id
            candidate_campaign_on_stage.contest_office_id = contest_office_on_stage.id
            candidate_campaign_on_stage.save()

            # We want to save the local id back to the GoogleCivicCandidateCampaign table
            # so we can cross-check data-integrity
            # NOTE: We do not limit this linkage to when we first create these local entries
            google_civic_candidate_campaign_entry.we_vote_election_id = election_on_stage.id
            google_civic_candidate_campaign_entry.we_vote_contest_office_id = contest_office_on_stage.id
            google_civic_candidate_campaign_entry.we_vote_candidate_campaign_id = candidate_campaign_on_stage.id
            google_civic_candidate_campaign_entry.save(
            )  # We save here AND lower in case there are failures
        except Exception as e:
            handle_record_not_saved_exception(e)
            continue

        ###########################################
        # Politician
        # We know that a politician is not currently linked to this campaign
        # if politician_link_needed:  # DALE 2015-05-03 I would like this to always refresh
        results = google_civic_get_or_create_politician(
            google_civic_candidate_campaign_entry)
        politician_error = results['error_result']
        if politician_error:
            print "ERROR returned in google_civic_get_or_create_politician "\
                  "(skipping to next google_civic_candidate_campaign_entry)"
            continue
        politician_on_stage = results['politician_on_stage']

        try:
            candidate_campaign_on_stage.politician_id = politician_on_stage.id
            candidate_campaign_on_stage.save()

            google_civic_candidate_campaign_entry.we_vote_politician_id = politician_on_stage.id
            google_civic_candidate_campaign_entry.save()
        except Exception as e:
            handle_record_not_saved_exception(e)
            continue
示例#60
0
def organization_save_new_or_edit_existing_position_process_form_view(request):
    """

    :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)

    google_civic_election_id = convert_to_int(request.POST['google_civic_election_id'])
    organization_id = convert_to_int(request.POST['organization_id'])
    position_id = convert_to_int(request.POST['position_id'])
    candidate_campaign_id = convert_to_int(request.POST['candidate_campaign_id'])
    contest_measure_id = convert_to_int(request.POST['contest_measure_id'])
    stance = request.POST.get('stance', SUPPORT)  # Set a default if stance comes in empty
    statement_text = request.POST.get('statement_text', '')  # Set a default if stance comes in empty
    more_info_url = request.POST.get('more_info_url', '')

    # Make sure this is a valid organization before we try to save a position
    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:
        # If we can't retrieve the organization, we cannot proceed
        handle_record_not_found_exception(e, logger=logger)

    if not organization_on_stage_found:
        messages.add_message(
            request, messages.ERROR,
            "Could not find the organization when trying to create or edit a new position.")
        return HttpResponseRedirect(reverse('organization:organization_list', args=()))

    # Now retrieve the CandidateCampaign or the ContestMeasure so we can save it with the Position
    # We need either candidate_campaign_id or contest_measure_id
    if candidate_campaign_id:
        try:
            candidate_campaign_on_stage = CandidateCampaign.objects.get(id=candidate_campaign_id)
            candidate_campaign_on_stage_found = True
        except CandidateCampaign.MultipleObjectsReturned as e:
            handle_record_found_more_than_one_exception(e, logger=logger)
        except CandidateCampaign.DoesNotExist as e:
            handle_record_not_found_exception(e, logger=logger)

        if not candidate_campaign_on_stage_found:
            messages.add_message(
                request, messages.ERROR,
                "Could not find Candidate's campaign when trying to create or edit a new position.")
            if position_id:
                return HttpResponseRedirect(
                    reverse('organization:organization_position_edit', args=([organization_id], [position_id]))
                )
            else:
                return HttpResponseRedirect(
                    reverse('organization:organization_position_new', args=([organization_id]))
                )
    elif contest_measure_id:
        logger.warn("contest_measure_id FOUND. Look for ContestMeasure here.")

    else:
        logger.warn("Neither candidate_campaign_id nor contest_measure_id found")
        messages.add_message(
            request, messages.ERROR,
            "Unable to find either Candidate or Measure.")
        return HttpResponseRedirect(
            reverse('organization:organization_position_list', args=([organization_id]))
        )

    organization_position_on_stage_found = False
    logger.info("position_id: {position_id}".format(position_id=position_id))

    # Retrieve position from position_id if it exists already
    if position_id > 0:
        position_entered_manager = PositionEnteredManager()
        results = position_entered_manager.retrieve_position_from_id(position_id)
        if results['position_found']:
            organization_position_on_stage_found = True
            organization_position_on_stage = results['position']

    if not organization_position_on_stage_found:
        # If a position_id hasn't been passed in, then we are trying to create a new position.
        # Check to make sure a position for this org and candidate doesn't already exist

        position_entered_manager = PositionEnteredManager()
        results = position_entered_manager.retrieve_organization_candidate_campaign_position(
            organization_id, candidate_campaign_id)

        if results['MultipleObjectsReturned']:
            messages.add_message(
                request, messages.ERROR,
                "We found more than one existing positions for this candidate. Please delete all but one position.")
            return HttpResponseRedirect(
                reverse('organization:organization_position_list', args=([organization_id]))
            )
        elif results['position_found']:
            organization_position_on_stage_found = True
            organization_position_on_stage = results['position']

    # Now save existing, or create new
    success = False
    try:
        if organization_position_on_stage_found:
            # Update the position
            organization_position_on_stage.stance = stance
            organization_position_on_stage.google_civic_election_id = google_civic_election_id
            organization_position_on_stage.more_info_url = more_info_url
            organization_position_on_stage.statement_text = statement_text
            if not positive_value_exists(organization_position_on_stage.organization_we_vote_id):
                organization_position_on_stage.organization_we_vote_id = organization_on_stage.we_vote_id
            if not positive_value_exists(organization_position_on_stage.candidate_campaign_we_vote_id):
                organization_position_on_stage.candidate_campaign_we_vote_id = candidate_campaign_on_stage.we_vote_id
            if not positive_value_exists(organization_position_on_stage.google_civic_candidate_name):
                organization_position_on_stage.google_civic_candidate_name = \
                    candidate_campaign_on_stage.google_civic_candidate_name
            organization_position_on_stage.save()
            success = True
            messages.add_message(
                request, messages.INFO,
                "Position on {candidate_name} updated.".format(
                    candidate_name=candidate_campaign_on_stage.candidate_name))
        else:
            # Create new
            organization_position_on_stage = PositionEntered(
                organization_id=organization_id,
                organization_we_vote_id=organization_on_stage.we_vote_id,
                candidate_campaign_id=candidate_campaign_on_stage.id,
                candidate_campaign_we_vote_id=candidate_campaign_on_stage.we_vote_id,
                # Save candidate_campaign_on_stage so we can re-link candidates to positions if we_vote_id is lost
                google_civic_candidate_name=candidate_campaign_on_stage.google_civic_candidate_name,
                google_civic_election_id=google_civic_election_id,
                stance=stance,
                statement_text=statement_text,
                more_info_url=more_info_url,
            )
            organization_position_on_stage.save()
            success = True
            messages.add_message(
                request, messages.INFO,
                "New position on {candidate_name} saved.".format(
                    candidate_name=candidate_campaign_on_stage.candidate_name))
    except Exception as e:
        handle_record_not_saved_exception(e, logger=logger)
        logger.error("Problem saving PositionEntered for CandidateCampaign")

    # If the position was saved, then update the voter_guide entry
    if success:
        voter_guide_manager = VoterGuideManager()
        results = voter_guide_manager.update_or_create_organization_voter_guide_by_election_id(
            organization_on_stage.we_vote_id, google_civic_election_id)
        # if results['success']:

    return HttpResponseRedirect(reverse('organization:organization_position_list', args=(organization_on_stage.id,)))