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=()))
def retrieve_voter_guides_for_election(self, google_civic_election_id): voter_guide_list = [] voter_guide_list_found = False try: voter_guide_queryset = VoterGuide.objects.order_by('-twitter_followers_count') voter_guide_list = voter_guide_queryset.filter( google_civic_election_id=google_civic_election_id) if len(voter_guide_list): voter_guide_list_found = True status = 'VOTER_GUIDE_FOUND' else: status = 'NO_VOTER_GUIDES_FOUND' success = True except Exception as e: handle_record_not_found_exception(e, logger=logger) status = 'voterGuidesToFollowRetrieve: Unable to retrieve voter guides from db. ' \ '{error} [type: {error_type}]'.format(error=e.message, error_type=type(e)) success = False results = { 'success': success, 'status': status, 'voter_guide_list_found': voter_guide_list_found, 'voter_guide_list': voter_guide_list, } return results
def retrieve_all_positions_for_candidate_campaign( self, candidate_campaign_id, stance_we_are_looking_for): # TODO Error check stance_we_are_looking_for # Note that one of the incoming options for stance_we_are_looking_for is 'ANY' which means we want to return # all stances # Retrieve the support positions for this candidate_campaign_id organization_position_list = PositionEntered() organization_position_list_found = False try: organization_position_list = PositionEntered.objects.order_by( 'date_entered') organization_position_list = organization_position_list.filter( candidate_campaign_id=candidate_campaign_id) # SUPPORT, STILL_DECIDING, INFORMATION_ONLY, NO_STANCE, OPPOSE if stance_we_are_looking_for != ANY: # If we passed in the stance "ANY" it means we want to not filter down the list organization_position_list = organization_position_list.filter( stance=stance_we_are_looking_for) # organization_position_list = organization_position_list.filter(election_id=election_id) if len(organization_position_list): organization_position_list_found = True except Exception as e: handle_record_not_found_exception(e, logger=logger) if organization_position_list_found: return organization_position_list else: organization_position_list = {} return organization_position_list
def retrieve_all_positions_for_candidate_campaign(self, candidate_campaign_id, stance_we_are_looking_for): # TODO Error check stance_we_are_looking_for # Note that one of the incoming options for stance_we_are_looking_for is 'ANY' which means we want to return # all stances # Retrieve the support positions for this candidate_campaign_id organization_position_list = PositionEntered() organization_position_list_found = False try: organization_position_list = PositionEntered.objects.order_by('date_entered') organization_position_list = organization_position_list.filter(candidate_campaign_id=candidate_campaign_id) # SUPPORT, STILL_DECIDING, INFORMATION_ONLY, NO_STANCE, OPPOSE if stance_we_are_looking_for != ANY: # If we passed in the stance "ANY" it means we want to not filter down the list organization_position_list = organization_position_list.filter(stance=stance_we_are_looking_for) # organization_position_list = organization_position_list.filter(election_id=election_id) if len(organization_position_list): organization_position_list_found = True except Exception as e: handle_record_not_found_exception(e, logger=logger) if organization_position_list_found: return organization_position_list else: organization_position_list = {} return organization_position_list
def retrieve_star_item_list_for_voter(self, voter_id): # Retrieve a list of star_item entries for this voter star_item_list_found = False star_item_list = [] try: star_item_list = StarItem.objects.all() star_item_list = star_item_list.filter(voter_id=voter_id) if len(star_item_list): star_item_list_found = True except Exception as e: handle_record_not_found_exception(e, logger=logger) if star_item_list_found: results = { 'status': "STAR_ITEMS_FOUND", 'success': True, 'star_item_list': star_item_list, } return results else: results = { 'status': "STAR_ITEMS_NOT_FOUND", 'success': True, 'star_item_list': [], } return results
def retrieve_all_voter_guides(self): voter_guide_list = [] voter_guide_list_found = False try: status = 'ERROR_VOTER_GUIDE_LIST_START' voter_guide_queryset = VoterGuide.objects.order_by('last_updated') voter_guide_list = voter_guide_queryset if len(voter_guide_list): voter_guide_list_found = True status = 'VOTER_GUIDE_FOUND' else: status = 'NO_VOTER_GUIDES_FOUND' except Exception as e: handle_record_not_found_exception(e, logger=logger) status = 'voterGuidesToFollowRetrieve: Unable to retrieve voter guides from db. ' \ '{error} [type: {error_type}]'.format(error=e.message, error_type=type(e)) results = { 'success': True if voter_guide_list_found else False, 'status': status, 'voter_guide_list_found': voter_guide_list_found, 'voter_guide_list': voter_guide_list, } return results
def retrieve_all_voter_guides(self): voter_guide_list = [] voter_guide_list_found = False try: voter_guide_queryset = VoterGuide.objects.order_by("last_updated") voter_guide_list = voter_guide_queryset if len(voter_guide_list): voter_guide_list_found = True status = "VOTER_GUIDE_FOUND" else: status = "NO_VOTER_GUIDES_FOUND" success = True except Exception as e: handle_record_not_found_exception(e, logger=logger) status = ( "voterGuidesToFollowRetrieve: Unable to retrieve voter guides from db. " "{error} [type: {error_type}]".format(error=e.message, error_type=type(e)) ) success = False results = { "success": success, "status": status, "voter_guide_list_found": voter_guide_list_found, "voter_guide_list": voter_guide_list, } return results
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=()))
def retrieve_all_positions_for_candidate_campaign( self, candidate_campaign_id, stance_we_are_looking_for): # TODO Error check stance_we_are_looking_for # Retrieve the support positions for this candidate_campaign_id organization_position_list_found = False try: organization_position_list = PositionEntered.objects.order_by( 'date_entered') organization_position_list = organization_position_list.filter( candidate_campaign_id=candidate_campaign_id) # SUPPORT, STILL_DECIDING, INFORMATION_ONLY, NO_STANCE, OPPOSE organization_position_list = organization_position_list.filter( stance=stance_we_are_looking_for) # organization_position_list = organization_position_list.filter(election_id=election_id) if len(organization_position_list): organization_position_list_found = True except Exception as e: handle_record_not_found_exception(e) if organization_position_list_found: return organization_position_list else: organization_position_list = {} return organization_position_list
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=()))
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
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, )))
def candidate_edit_view(request, candidate_id): authority_required = {'verified_volunteer'} # admin, verified_volunteer if not voter_has_authority(request, authority_required): return redirect_to_sign_in_page(request, authority_required) messages_on_stage = get_messages(request) candidate_id = convert_to_int(candidate_id) candidate_on_stage_found = False candidate_on_stage = CandidateCampaign() try: candidate_on_stage = CandidateCampaign.objects.get(id=candidate_id) candidate_on_stage_found = True except CandidateCampaign.MultipleObjectsReturned as e: handle_record_found_more_than_one_exception(e, logger=logger) except CandidateCampaign.DoesNotExist: # This is fine, create new pass if candidate_on_stage_found: # Working with Vote Smart data try: vote_smart_candidate_id = candidate_on_stage.vote_smart_id rating_list_query = VoteSmartRatingOneCandidate.objects.order_by( '-timeSpan') # Desc order rating_list = rating_list_query.filter( candidateId=vote_smart_candidate_id) except VotesmartApiError as error_instance: # Catch the error message coming back from Vote Smart and pass it in the status error_message = error_instance.args status = "EXCEPTION_RAISED: {error_message}".format( error_message=error_message) print_to_log(logger=logger, exception_message_optional=status) rating_list = [] # Working with We Vote Positions try: candidate_position_list = PositionEntered.objects.order_by( 'stance') candidate_position_list = candidate_position_list.filter( candidate_campaign_id=candidate_id) # if positive_value_exists(google_civic_election_id): # organization_position_list = candidate_position_list.filter( # google_civic_election_id=google_civic_election_id) except Exception as e: handle_record_not_found_exception(e, logger=logger) candidate_position_list = [] template_values = { 'messages_on_stage': messages_on_stage, 'candidate': candidate_on_stage, 'rating_list': rating_list, 'candidate_position_list': candidate_position_list, } else: template_values = { 'messages_on_stage': messages_on_stage, } return render(request, 'candidate/candidate_edit.html', template_values)
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
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
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,)))
def retrieve_voter_guides_by_organization_list(self, organization_we_vote_ids_followed_by_voter): voter_guide_list = [] voter_guide_list_found = False if not type(organization_we_vote_ids_followed_by_voter) is list: status = "NO_VOTER_GUIDES_FOUND_MISSING_ORGANIZATION_LIST" success = False results = { "success": success, "status": status, "voter_guide_list_found": voter_guide_list_found, "voter_guide_list": voter_guide_list, } return results if not len(organization_we_vote_ids_followed_by_voter): status = "NO_VOTER_GUIDES_FOUND_NO_ORGANIZATIONS_IN_LIST" success = False results = { "success": success, "status": status, "voter_guide_list_found": voter_guide_list_found, "voter_guide_list": voter_guide_list, } return results try: voter_guide_queryset = VoterGuide.objects.all() voter_guide_queryset = voter_guide_queryset.filter( organization_we_vote_id__in=organization_we_vote_ids_followed_by_voter ) voter_guide_queryset = voter_guide_queryset.order_by("last_updated") voter_guide_list = voter_guide_queryset if len(voter_guide_list): voter_guide_list_found = True status = "VOTER_GUIDES_FOUND_BY_ORGANIZATION_LIST" else: status = "NO_VOTER_GUIDES_FOUND_BY_ORGANIZATION_LIST" success = True except Exception as e: handle_record_not_found_exception(e, logger=logger) status = ( "voterGuidesToFollowRetrieve: Unable to retrieve voter guides from db. " "{error} [type: {error_type}]".format(error=e.message, error_type=type(e)) ) success = False results = { "success": success, "status": status, "voter_guide_list_found": voter_guide_list_found, "voter_guide_list": voter_guide_list, } return results
def candidate_edit_view(request, candidate_id): authority_required = {'verified_volunteer'} # admin, verified_volunteer if not voter_has_authority(request, authority_required): return redirect_to_sign_in_page(request, authority_required) messages_on_stage = get_messages(request) candidate_id = convert_to_int(candidate_id) candidate_on_stage_found = False candidate_on_stage = CandidateCampaign() try: candidate_on_stage = CandidateCampaign.objects.get(id=candidate_id) candidate_on_stage_found = True except CandidateCampaign.MultipleObjectsReturned as e: handle_record_found_more_than_one_exception(e, logger=logger) except CandidateCampaign.DoesNotExist: # This is fine, create new pass if candidate_on_stage_found: # Working with Vote Smart data try: vote_smart_candidate_id = candidate_on_stage.vote_smart_id rating_list_query = VoteSmartRatingOneCandidate.objects.order_by('-timeSpan') # Desc order rating_list = rating_list_query.filter(candidateId=vote_smart_candidate_id) except VotesmartApiError as error_instance: # Catch the error message coming back from Vote Smart and pass it in the status error_message = error_instance.args status = "EXCEPTION_RAISED: {error_message}".format(error_message=error_message) print_to_log(logger=logger, exception_message_optional=status) rating_list = [] # Working with We Vote Positions candidate_position_list_found = False try: candidate_position_list = PositionEntered.objects.order_by('stance') candidate_position_list = candidate_position_list.filter(candidate_campaign_id=candidate_id) # if positive_value_exists(google_civic_election_id): # organization_position_list = candidate_position_list.filter( # google_civic_election_id=google_civic_election_id) except Exception as e: handle_record_not_found_exception(e, logger=logger) candidate_position_list = [] template_values = { 'messages_on_stage': messages_on_stage, 'candidate': candidate_on_stage, 'rating_list': rating_list, 'candidate_position_list': candidate_position_list, } else: template_values = { 'messages_on_stage': messages_on_stage, } return render(request, 'candidate/candidate_edit.html', template_values)
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
def organization_position_list_view(request, organization_id): authority_required = {'verified_volunteer'} # admin, verified_volunteer if not voter_has_authority(request, authority_required): return redirect_to_sign_in_page(request, authority_required) messages_on_stage = get_messages(request) organization_id = convert_to_int(organization_id) google_civic_election_id = convert_to_int(request.GET.get('google_civic_election_id', 0)) 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) organization_on_stage_found = False if not organization_on_stage_found: messages.add_message(request, messages.ERROR, 'Could not find organization when trying to retrieve positions.') return HttpResponseRedirect(reverse('organization:organization_list', args=())) else: organization_position_list_found = False try: organization_position_list = PositionEntered.objects.order_by('stance') organization_position_list = organization_position_list.filter(organization_id=organization_id) if positive_value_exists(google_civic_election_id): organization_position_list = organization_position_list.filter( google_civic_election_id=google_civic_election_id) if len(organization_position_list): organization_position_list_found = True except Exception as e: handle_record_not_found_exception(e, logger=logger) election_list = Election.objects.order_by('-election_day_text') if organization_position_list_found: template_values = { 'messages_on_stage': messages_on_stage, 'organization': organization_on_stage, 'organization_position_list': organization_position_list, 'election_list': election_list, 'google_civic_election_id': google_civic_election_id, } else: template_values = { 'messages_on_stage': messages_on_stage, 'organization': organization_on_stage, 'election_list': election_list, 'google_civic_election_id': google_civic_election_id, } return render(request, 'organization/organization_position_list.html', template_values)
def retrieve_voter_guides_by_organization_list(self, organization_we_vote_ids_followed_by_voter): voter_guide_list = [] voter_guide_list_found = False if not type(organization_we_vote_ids_followed_by_voter) is list: status = 'NO_VOTER_GUIDES_FOUND_MISSING_ORGANIZATION_LIST' success = False results = { 'success': success, 'status': status, 'voter_guide_list_found': voter_guide_list_found, 'voter_guide_list': voter_guide_list, } return results if not len(organization_we_vote_ids_followed_by_voter): status = 'NO_VOTER_GUIDES_FOUND_NO_ORGANIZATIONS_IN_LIST' success = False results = { 'success': success, 'status': status, 'voter_guide_list_found': voter_guide_list_found, 'voter_guide_list': voter_guide_list, } return results try: voter_guide_queryset = VoterGuide.objects.all() voter_guide_queryset = voter_guide_queryset.filter( organization_we_vote_id__in=organization_we_vote_ids_followed_by_voter) voter_guide_queryset = voter_guide_queryset.order_by('-twitter_followers_count') voter_guide_list = voter_guide_queryset if len(voter_guide_list): voter_guide_list_found = True status = 'VOTER_GUIDES_FOUND_BY_ORGANIZATION_LIST' else: status = 'NO_VOTER_GUIDES_FOUND_BY_ORGANIZATION_LIST' success = True except Exception as e: handle_record_not_found_exception(e, logger=logger) status = 'voterGuidesToFollowRetrieve: Unable to retrieve voter guides from db. ' \ '{error} [type: {error_type}]'.format(error=e.message, error_type=type(e)) success = False results = { 'success': success, 'status': status, 'voter_guide_list_found': voter_guide_list_found, 'voter_guide_list': voter_guide_list, } return results
def process_election_from_structured_json(election_structured_data, save_to_db): """ "id": "4111", "name": "MI Special Election", "electionDay": "2015-05-05" """ google_civic_election_id = election_structured_data['id'] name = election_structured_data['name'] election_day = election_structured_data['electionDay'] # DALE 2015-05-01 The election type is currently in the contests, and not in the election # is_general_election = False # Reset to false # is_primary_election = False # Reset to false # is_runoff_election = False # Reset to false # for case in switch(election_structured_data['type']): # if case('Primary'): # is_primary_election = True # break # if case('Run-off'): # is_runoff_election = True # break # if case('General'): pass # if case(): # default # is_general_election = True if save_to_db: if google_civic_election_id and name and election_day: try: # Try to find earlier version based on Google's unique identifier google_civic_election_id query1 = GoogleCivicContestOffice.objects.all() query1 = query1.filter( google_civic_election_id__exact=google_civic_election_id) # Was at least one existing entry found based on the above criteria? if len(query1): google_civic_election_entry = query1[0] # If no entries found previously, create a new entry else: google_civic_election_entry \ = GoogleCivicElection.objects.create(google_civic_election_id=google_civic_election_id, name=name, election_day=election_day, # is_general_election=is_general_election, # is_primary_election=is_primary_election, # is_runoff_election=is_runoff_election, ) # Return the google_civic_election_id so we can tie all of the Offices and Measures to this election except Exception as e: handle_record_not_found_exception(e) return google_civic_election_id
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=()))
def process_election_from_structured_json(election_structured_data, save_to_db): """ "id": "4111", "name": "MI Special Election", "electionDay": "2015-05-05" """ google_civic_election_id = election_structured_data['id'] name = election_structured_data['name'] election_day = election_structured_data['electionDay'] # DALE 2015-05-01 The election type is currently in the contests, and not in the election # is_general_election = False # Reset to false # is_primary_election = False # Reset to false # is_runoff_election = False # Reset to false # for case in switch(election_structured_data['type']): # if case('Primary'): # is_primary_election = True # break # if case('Run-off'): # is_runoff_election = True # break # if case('General'): pass # if case(): # default # is_general_election = True if save_to_db: if google_civic_election_id and name and election_day: try: # Try to find earlier version based on Google's unique identifier google_civic_election_id query1 = GoogleCivicContestOffice.objects.all() query1 = query1.filter(google_civic_election_id__exact=google_civic_election_id) # Was at least one existing entry found based on the above criteria? if len(query1): google_civic_election_entry = query1[0] # If no entries found previously, create a new entry else: google_civic_election_entry \ = GoogleCivicElection.objects.create(google_civic_election_id=google_civic_election_id, name=name, election_day=election_day, # is_general_election=is_general_election, # is_primary_election=is_primary_election, # is_runoff_election=is_runoff_election, ) # Return the google_civic_election_id so we can tie all of the Offices and Measures to this election except Exception as e: handle_record_not_found_exception(e, logger=logger) return google_civic_election_id
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"],))
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=()))
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=()))
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=()))
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=()))
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=()))
def retrieve_position_like_list_for_voter(self, voter_id): # Retrieve a list of position_like entries for this voter position_like_list_found = False position_like_list = {} try: position_like_list = PositionLike.objects.all() position_like_list = position_like_list.filter(voter_id=voter_id) if len(position_like_list): position_like_list_found = True except Exception as e: handle_record_not_found_exception(e, logger=logger) if position_like_list_found: return position_like_list else: position_like_list = {} return position_like_list
def organization_position_list_view(request, organization_id): messages_on_stage = get_messages(request) organization_id = convert_to_int(organization_id) # election_id = 1 # TODO We will need to provide the election_id somehow, perhaps as a global variable? 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) organization_on_stage_found = False if not organization_on_stage_found: messages.add_message( request, messages.ERROR, 'Could not find organization when trying to retrieve positions.') return HttpResponseRedirect( reverse('organization:organization_list', args=())) else: organization_position_list_found = False try: organization_position_list = PositionEntered.objects.order_by( 'stance') organization_position_list = organization_position_list.filter( organization_id=organization_id) # organization_position_list = organization_position_list.filter(election_id=election_id) if len(organization_position_list): organization_position_list_found = True except Exception as e: handle_record_not_found_exception(e) if organization_position_list_found: template_values = { 'messages_on_stage': messages_on_stage, 'organization': organization_on_stage, 'organization_position_list': organization_position_list, } else: template_values = { 'messages_on_stage': messages_on_stage, 'organization': organization_on_stage, } return render(request, 'organization/organization_position_list.html', template_values)
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=()))
def retrieve_follow_organization_info_for_organization(self, organization_id): # Retrieve a list of follow_organization entries for this organization follow_organization_list_found = False following_status = FOLLOWING try: follow_organization_list = FollowOrganization.objects.all() follow_organization_list = follow_organization_list.filter(organization_id=organization_id) follow_organization_list = follow_organization_list.filter(following_status=following_status) if len(follow_organization_list): follow_organization_list_found = True except Exception as e: handle_record_not_found_exception(e) if follow_organization_list_found: return follow_organization_list else: follow_organization_list = {} return follow_organization_list
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=()))
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=()))
def retrieve_follow_organization_info_for_organization(self, organization_id): # Retrieve a list of follow_organization entries for this organization follow_organization_list_found = False following_status = FOLLOWING follow_organization_list = {} try: follow_organization_list = FollowOrganization.objects.all() follow_organization_list = follow_organization_list.filter(organization_id=organization_id) follow_organization_list = follow_organization_list.filter(following_status=following_status) if len(follow_organization_list): follow_organization_list_found = True except Exception as e: handle_record_not_found_exception(e, logger=logger) if follow_organization_list_found: return follow_organization_list else: follow_organization_list = {} return follow_organization_list
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=()))
def retrieve_star_item_list_for_voter(self, voter_id): # Retrieve a list of star_item entries for this voter star_item_list_found = False star_status = ITEM_STARRED star_item_list = {} try: star_item_list = StarItem.objects.all() star_item_list = star_item_list.filter(voter_id=voter_id) star_item_list = star_item_list.filter(star_status=star_status) if len(star_item_list): star_item_list_found = True except Exception as e: handle_record_not_found_exception(e, logger=logger) if star_item_list_found: return star_item_list else: star_item_list = {} return star_item_list
def office_edit_process_view(request): """ Process the new or edit office forms :param request: :return: """ office_id = convert_to_int(request.POST['office_id']) office_name = request.POST['office_name'] twitter_handle = request.POST['twitter_handle'] office_website = request.POST['office_website'] # Check to see if this office is already being used anywhere office_on_stage_found = False try: office_query = ContestOffice.objects.filter(id=office_id) if len(office_query): office_on_stage = office_query[0] office_on_stage_found = True except Exception as e: handle_record_not_found_exception(e, logger=logger) try: if office_on_stage_found: # Update office_on_stage.office_name = office_name office_on_stage.twitter_handle = twitter_handle office_on_stage.office_website = office_website office_on_stage.save() messages.add_message(request, messages.INFO, 'ContestOffice updated.') else: # Create new office_on_stage = ContestOffice( office_name=office_name, twitter_handle=twitter_handle, office_website=office_website, ) office_on_stage.save() messages.add_message(request, messages.INFO, 'New office saved.') except Exception as e: handle_record_not_saved_exception(e, logger=logger) messages.add_message(request, messages.ERROR, 'Could not save office.') return HttpResponseRedirect(reverse('office:office_list', args=()))
def retrieve_ignore_organization_by_voter_id(self, voter_id): # Retrieve a list of follow_organization entries for this voter follow_organization_list_found = False following_status = FOLLOW_IGNORE follow_organization_list = {} try: follow_organization_list = FollowOrganization.objects.all() follow_organization_list = follow_organization_list.filter(voter_id=voter_id) follow_organization_list = follow_organization_list.filter(following_status=following_status) if len(follow_organization_list): follow_organization_list_found = True except Exception as e: handle_record_not_found_exception(e, logger=logger) if follow_organization_list_found: return follow_organization_list else: follow_organization_list = {} return follow_organization_list
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=()))
def candidate_edit_process_view(request): """ Process the new or edit candidate forms :param request: :return: """ 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=()))
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=()))
def retrieve_ignore_organization_by_voter_id(self, voter_id): # Retrieve a list of follow_organization entries for this voter follow_organization_list_found = False following_status = FOLLOW_IGNORE follow_organization_list = {} try: follow_organization_list = FollowOrganization.objects.all() follow_organization_list = follow_organization_list.filter( voter_id=voter_id) follow_organization_list = follow_organization_list.filter( following_status=following_status) if len(follow_organization_list): follow_organization_list_found = True except Exception as e: handle_record_not_found_exception(e, logger=logger) if follow_organization_list_found: return follow_organization_list else: follow_organization_list = {} return follow_organization_list
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 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
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
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
def import_legislators_current_csv(): """ This is a very simple method that is hard coded to the UnitedStates.io CSV Field names. We are saving the contents of this file locally so we can 1) share the data on ElectionDataSummary.org dynamically 2) save it/merge it into the correct We Vote tables later :return: """ with open(LEGISLATORS_CURRENT_CSV_FILE, 'rU') as legislators_current_data: legislators_current_data.readline() # Skip the header reader = csv.reader( legislators_current_data) # Create a regular tuple reader for index, legislator_row in enumerate(reader): # if index > 7: # break logger.debug("import_legislators_current_csv: " + legislator_row[0]) # For debugging legislator_entry_found = False # Do we have a record of this legislator based on bioguide_id? if legislator_row[18] != "": try: query1 = TheUnitedStatesIoLegislatorCurrent.objects.all() query1 = query1.filter( bioguide_id__exact=legislator_row[18]) # Was at least one existing entry found based on the above criteria? if len(query1): legislator_entry = query1[0] legislator_entry_found = True except Exception as e: handle_record_not_found_exception(e, logger=logger) if not legislator_entry_found: # TheUnitedStatesIoLegislatorCurrent was not found based on bioguide id # ...so check to see if we have a record of this legislator based on govtrack id? if legislator_row[23] != "": try: query2 = TheUnitedStatesIoLegislatorCurrent.objects.all( ) query2 = query2.filter( govtrack_id__exact=legislator_row[23]) # Was at least one existing entry found based on the above criteria? if len(query2): legislator_entry = query2[0] legislator_entry_found = True except Exception as e: handle_record_not_found_exception(e, logger=logger) if not legislator_entry_found: # TheUnitedStatesIoLegislatorCurrent was not found based on govtrack id # ...so create a new entry legislator_entry = TheUnitedStatesIoLegislatorCurrent( last_name=legislator_row[ 0], # "last_name", # row[0] first_name=legislator_row[ 1], # "first_name", # row[1] ) legislator_entry.last_name = legislator_row[ 0] # "last_name", # row[0] legislator_entry.first_name = legislator_row[ 1] # "first_name", # row[1] legislator_entry.birth_date = legislator_row[ 2] # "birthday", # row[2] legislator_entry.gender = legislator_row[ 3] # "gender", # row[3] # "type", # row[4] legislator_entry.state = legislator_row[ 5] # "state", # row[5] # "district", # row[6] # Convert this to ocd district legislator_entry.party = legislator_row[ 7] # "party", # row[7] # "url", # row[8] # "address", # row[9] # "phone", # row[10] # "contact_form", # row[11] # "rss_url", # row[12] # "twitter", # row[13] # "facebook", # row[14] # "facebook_id", # row[15] # "youtube", # row[16] # "youtube_id", # row[17] legislator_entry.bioguide_id = legislator_row[ 18] # "bioguide_id", # row[18] legislator_entry.thomas_id = legislator_row[ 19] # "thomas_id", # row[19] legislator_entry.opensecrets_id = legislator_row[ 20] # "opensecrets_id", # row[20] legislator_entry.lis_id = legislator_row[ 21] # "lis_id", # row[21] legislator_entry.cspan_id = legislator_row[ 22] # "cspan_id", # row[22] legislator_entry.govtrack_id = legislator_row[ 23] # "govtrack_id", # row[23] legislator_entry.votesmart_id = legislator_row[ 24] # "votesmart_id", # row[24] legislator_entry.ballotpedia_id = legislator_row[ 25] # "ballotpedia_id", # row[25] legislator_entry.washington_post_id = legislator_row[ 26] # "washington_post_id", # row[26] legislator_entry.icpsr_id = legislator_row[ 27] # "icpsr_id", # row[27] legislator_entry.wikipedia_id = legislator_row[ 28] # "wikipedia_id" # row[28] # Add "try/exception" so we know when entry isn't saved due to unique requirement try: legislator_entry.save() except Exception as e: handle_exception(e, logger=logger)
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 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,)))
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
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])))
def process_contest_office_from_structured_json(one_contest_office_structured_json, google_civic_election_id, save_to_db): # print "General contest_type" office = one_contest_office_structured_json['office'] # The number of candidates that a voter may vote for in this contest. if 'numberVotingFor' in one_contest_office_structured_json: number_voting_for = one_contest_office_structured_json['numberVotingFor'] else: number_voting_for = 1 # The number of candidates that will be elected to office in this contest. if 'numberElected' in one_contest_office_structured_json: number_elected = one_contest_office_structured_json['numberElected'] else: number_elected = 1 results = process_contest_common_fields_from_structured_json(one_contest_office_structured_json) ballot_placement = results['ballot_placement'] # A number specifying the position of this contest # on the voter's ballot. primary_party = results['primary_party'] # If this is a partisan election, the name of the party it is for. district_name = results['district_name'] # The name of the district. district_scope = results['district_scope'] # The geographic scope of this district. If unspecified the # district's geography is not known. One of: national, statewide, congressional, stateUpper, stateLower, # countywide, judicial, schoolBoard, cityWide, township, countyCouncil, cityCouncil, ward, special district_ocd_id = results['district_ocd_id'] electorate_specifications = results['electorate_specifications'] # A description of any additional # eligibility requirements for voting in this contest. special = results['special'] # "Yes" or "No" depending on whether this a contest being held # outside the normal election cycle. # We want to convert this from an array to three fields for the same table # levels: string, A list of office levels to filter by. Only offices that serve at least one of these levels # will be returned. Divisions that don't contain a matching office will not be returned. (repeated) # Allowed values # administrativeArea1 - # administrativeArea2 - # country - # international - # locality - # regional - # special - # subLocality1 - # subLocality2 - # The levels of government of the office for this contest. There may be more than one in cases where a # jurisdiction effectively acts at two different levels of government; for example, the mayor of the # District of Columbia acts at "locality" level, but also effectively at both "administrative-area-2" # and "administrative-area-1". level_structured_json = one_contest_office_structured_json['level'] contest_level = [] for one_level in level_structured_json: contest_level.append(one_level) if 0 in contest_level: contest_level0 = contest_level[0] else: contest_level0 = '' if 1 in contest_level: contest_level1 = contest_level[1] else: contest_level1 = '' if 2 in contest_level: contest_level2 = contest_level[2] else: contest_level2 = '' # roles: string, A list of office roles to filter by. Only offices fulfilling one of these roles will be returned. Divisions that don't contain a matching office will not be returned. (repeated) # Allowed values # deputyHeadOfGovernment - # executiveCouncil - # governmentOfficer - # headOfGovernment - # headOfState - # highestCourtJudge - # judge - # legislatorLowerBody - # legislatorUpperBody - # schoolBoard - # specialPurposeOfficer - roles_structured_json = one_contest_office_structured_json['roles'] # for one_role in roles_structured_json: # Figure out how we are going to use level info candidates = one_contest_office_structured_json['candidates'] internal_contest_office_id = 0 # Set to 0 in case a new one is not created # Note that all of the information saved here is independent of a particular voter if save_to_db: if office and district_name and district_scope and district_ocd_id and google_civic_election_id: try: # Try to find earlier version based on name of the office google_civic_election_id query1 = GoogleCivicContestOffice.objects.all() query1 = query1.filter(google_civic_election_id__exact=google_civic_election_id) query1 = query1.filter(district_scope__exact=district_scope) query1 = query1.filter(office__exact=office) # Was at least one existing entry found based on the above criteria? if len(query1): google_civic_contest_office = query1[0] # If no entries found previously, create a new entry else: google_civic_contest_office = \ GoogleCivicContestOffice.objects.create(office=office, google_civic_election_id=google_civic_election_id, number_voting_for=number_voting_for, number_elected=number_elected, contest_level0=contest_level0, contest_level1=contest_level1, contest_level2=contest_level2, ballot_placement=ballot_placement, primary_party=primary_party, district_name=district_name, district_scope=district_scope, district_ocd_id=district_ocd_id, electorate_specifications=electorate_specifications, special=special, ) # The internal id is needed since there isn't a ContestOffice google identifier internal_contest_office_id = google_civic_contest_office.id # Save information about this contest item on the voter's ballot from: ballot_placement except Exception as e: handle_record_not_found_exception(e) process_candidates_from_structured_json(candidates, google_civic_election_id, internal_contest_office_id, save_to_db) return
def process_candidates_from_structured_json( candidates_structured_json, google_civic_election_id, google_civic_contest_office_id, save_to_db): """ "candidates": [ { "name": "Nancy Pelosi", "party": "Democratic" }, { "name": "John Dennis", "party": "Republican", "candidateUrl": "http://www.johndennisforcongress.com/", "channels": [ { "type": "Facebook", "id": "https://www.facebook.com/johndennis2010" }, { "type": "Twitter", "id": "https://twitter.com/johndennis2012" """ for one_candidate in candidates_structured_json: name = one_candidate['name'] party = one_candidate['party'] if 'order_on_ballot' in one_candidate: order_on_ballot = one_candidate['orderOnBallot'] else: order_on_ballot = 0 if 'candidateUrl' in one_candidate: candidate_url = one_candidate['candidateUrl'] else: candidate_url = '' # set them to channel values to empty facebook_url = '' twitter_url = '' google_plus_url = '' youtube_url = '' if 'channels' in one_candidate: channels = one_candidate['channels'] for one_channel in channels: if 'type' in one_channel: if one_channel['type'] == 'Facebook': facebook_url = one_channel['id'] if one_channel['type'] == 'Twitter': twitter_url = one_channel['id'] if one_channel['type'] == 'GooglePlus': google_plus_url = one_channel['id'] if one_channel['type'] == 'YouTube': youtube_url = one_channel['id'] if save_to_db: if name and google_civic_election_id and google_civic_contest_office_id: try: # Try to find existing candidate (based on name, google_civic_election_id and google_civic_contest_office_id query1 = GoogleCivicCandidateCampaign.objects.all() query1 = query1.filter(name__exact=name) query1 = query1.filter(google_civic_election_id__exact=google_civic_election_id) query1 = query1.filter(google_civic_contest_office_id__exact=google_civic_contest_office_id) # Was at least one existing entry found based on the above criteria? if len(query1): google_civic_candidate_campaign = query1[0] # If no entries found previously, create a new entry else: google_civic_candidate_campaign = \ GoogleCivicCandidateCampaign.objects.create(name=name, party=party, google_civic_contest_office_id=google_civic_contest_office_id, google_civic_election_id=google_civic_election_id, order_on_ballot=order_on_ballot, candidate_url=candidate_url, facebook_url=facebook_url, twitter_url=twitter_url, google_plus_url=google_plus_url, youtube_url=youtube_url, ) except Exception as e: handle_record_not_found_exception(e) return
def process_contest_referendum_from_structured_json( one_contest_referendum_structured_json, google_civic_election_id, save_to_db): """ "referendumTitle": "Proposition 45", "referendumSubtitle": "Healthcare Insurance. Rate Changes. Initiative Statute.", "referendumUrl": "http://vig.cdn.sos.ca.gov/2014/general/en/pdf/proposition-45-title-summary-analysis.pdf", "district" <= this is an array """ # print "Referendum contest_type" referendum_title = one_contest_referendum_structured_json['referendumTitle'] referendum_subtitle = one_contest_referendum_structured_json['referendumSubtitle'] referendum_url = one_contest_referendum_structured_json['referendumUrl'] # These following fields exist for both candidates and referendum results = process_contest_common_fields_from_structured_json(one_contest_referendum_structured_json) ballot_placement = results['ballot_placement'] # A number specifying the position of this contest # on the voter's ballot. primary_party = results['primary_party'] # If this is a partisan election, the name of the party it is for. district_name = results['district_name'] # The name of the district. district_scope = results['district_scope'] # The geographic scope of this district. If unspecified the # district's geography is not known. One of: national, statewide, congressional, stateUpper, stateLower, # countywide, judicial, schoolBoard, cityWide, township, countyCouncil, cityCouncil, ward, special district_ocd_id = results['district_ocd_id'] electorate_specifications = results['electorate_specifications'] # A description of any additional # eligibility requirements for voting in this contest. special = results['special'] # "Yes" or "No" depending on whether this a contest being held # outside the normal election cycle. if save_to_db: if referendum_title and referendum_subtitle and district_name and district_scope and district_ocd_id \ and google_civic_election_id: try: query1 = GoogleCivicContestReferendum.objects.all() query1 = query1.filter(referendum_title__exact=referendum_title) query1 = query1.filter(google_civic_election_id__exact=google_civic_election_id) query1 = query1.filter(district_scope__exact=district_scope) # Was at least one existing entry found based on the above criteria? if len(query1): google_civic_contest_referendum = query1[0] # If no entries found previously, create a new entry else: google_civic_contest_referendum = \ GoogleCivicContestReferendum.objects.create(referendum_title=referendum_title, referendum_subtitle=referendum_subtitle, google_civic_election_id=google_civic_election_id, referendum_url=referendum_url, ballot_placement=ballot_placement, primary_party=primary_party, district_name=district_name, district_scope=district_scope, district_ocd_id=district_ocd_id, electorate_specifications=electorate_specifications, special=special, ) # Save information about this contest item on the voter's ballot from: ballot_placement except Exception as e: handle_record_not_found_exception(e) return