def load_from_api(): url = "http://yournextmp.popit.mysociety.org/api/v0.1/search/persons?q=_exists_:standing_in.2015.post_id&page=16" while url: print "Fetching url: ", url fp = urllib2.urlopen(url) data = json.load(fp) fp.close() for record in data['result']: try: testrec = Candidate.objects.get(popit_url=record['url']) print "Skipping: ", testrec.name continue except Candidate.DoesNotExist: pass candidate = Candidate( name=record['name'], contact_address=record['email'], popit_url=record['url'], constituency_id=record['standing_in']['2015']['post_id'], constituency_name=record['standing_in']['2015']['name'], party=record['party_memberships']['2015']['name']) candidate.save() print u"Added: {} ({}, {})".format(candidate.name, candidate.party, candidate.constituency_name) if 'next_url' not in data: break url = data['next_url']
def load_from_csv(filename): csv_file = csv.reader(open(filename)) headings = csv_file.next() User = get_user_model() for row in csv_file: record = dict(zip(headings, row)) try: testrec = Candidate.objects.get(popit_id=record['id']) print "Skipping: ", testrec.name continue except Candidate.DoesNotExist: pass user = User(username="******" + record['id']) user.save() candidate = Candidate( popit_id=record['id'], user=user, name=record['name'].decode('utf-8'), contact_address=record['email'].decode('utf-8'), constituency_id=record['mapit_id'], constituency_name=record['constituency'].decode('utf-8'), party=record['party'].decode('utf-8')) candidate.save() print u"Added: {} ({}, {})".format(candidate.name, candidate.party, candidate.constituency_name)
def setUp(self): # create an organisation user = User(username='******') user.save() org = Organisation(name='test_org') org.user = user org.save() # create three questions self.q1 = Question(question='What is your name?', organisation=org) self.q1.save() # create a candidate self.candidate = Candidate(name='Terry', participating=True, popit_id=1234) self.candidate.save() # post-save hook on candidate will automatically assign q1 q2 = Question(question='What is your quest?', organisation=org) q2.save() q3 = Question(question='What is your favourite colour?', organisation=org) q3.save() # assign 1 question to the candidate self.answer = Answer.objects.get(question=self.q1, candidate=self.candidate)
def test_add_candidate(self): # Make some test data to be displayed on the page. candidate = Candidate(name="Bernie Sanders", accomplishments="Test", platform="Test", foreign_policy="Test", unique="Test", candidate_id="P0000" ) candidate.save() # Attempt to add candidate. request = RequestFactory().post(f'/candidates/add-candidate/{candidate.slug}') # Simulate a logged in user. request.user = self.user # Render the detail view with the request. response = CandidateDetailView.as_view()(request, candidate.slug) # Check that response is 302 "found" redirect. self.assertEqual(response.status_code, 302) # Check that the user has been redirected to My Candidates page. self.assertEqual(response.url, '/candidates/my-candidates/')
def test_slug_goes_to_detail_page(self): # Make some test data to be displayed on the page. candidate = Candidate(name="Bernie Sanders", accomplishments="Test", platform="Test", foreign_policy="Test", unique="Test", candidate_id="P0000" ) candidate.save() # Issue a GET request to homepage. response = self.client.get('/candidates/') # Check that the response is 200 OK. self.assertEqual(response.status_code, 200) # Get candidate's slug slug = candidate.slug # Issue a GET request to detail page. next_response = self.client.get(f'/candidates/{slug}') # Check that the response is 200 OK. self.assertEqual(next_response.status_code, 200)
def test_candidate_slugify_on_save(self): candidate = Candidate(name="Bernie Sanders", accomplishments="Test", platform="Test", foreign_policy="Test", unique="Test", candidate_id="P0000" ) candidate.save() self.assertEqual(candidate.slug, "bernie-sanders")
def test_multiple_candidates(self): # Make some test data to be displayed on the page. candidate = Candidate(name="Bernie Sanders", accomplishments="Test", platform="Test", foreign_policy="Test", unique="Test", candidate_id="P0000" ) candidate2 = Candidate(name="Joe Biden", accomplishments="Test", platform="Test", foreign_policy="Test", unique="Test", candidate_id="P0000" ) candidate.save() candidate2.save() # Issue a GET request to homepage. response = self.client.get('/candidates/') # Check that the response is 200 OK. self.assertEqual(response.status_code, 200) # Check that the number of candidates passed to the template # matches the number of candidates we have in the database. responses = response.context['candidates'] self.assertEqual(len(responses), 2) self.assertQuerysetEqual( responses, ['<Candidate: Bernie Sanders>', '<Candidate: Joe Biden>'], ordered=False )
def setUp(self): user = User(username='******') user.save() o1 = Organisation(name='Organisation 1') o1.user = user o1.save() user = User(username='******') user.save() o2 = Organisation(name='Organisation 2') o2.user = user o2.save() c1 = Candidate(popit_id=1235, name='Bob', contact_address='*****@*****.**', participating=True) c1.save() self.candidate = c1 q1 = Question( organisation=o1, question='What is your name?', type='text', ) q1.save() q2 = Question( organisation=o2, question='What is your quest?', type='text', ) q2.save() a1 = Answer(candidate=c1, question=q1, completed=True, completed_timestamp=datetime.datetime( 2015, 1, 1, tzinfo=timezone.get_current_timezone())) a1.save() self.a1 = a1 a2 = Answer(candidate=c1, question=q2, completed=False) a2.save() self.a2 = a2
def test_add_candidate(self): # Make some test data to be displayed on the page. candidate = Candidate(name="Bernie Sanders", accomplishments="Test", platform="Test", foreign_policy="Test", unique="Test", candidate_id="P0000" ) candidate.save() # Attempt to add candidate. request = self.client.post(f'/candidates/add-candidate/{candidate.slug}') # Use the redirected url to render MyCandidatesListView. response = self.client.get(request.url) # Check that the candidate and user were saved with the AddedCandidate model responses = response.context['candidates'] self.assertQuerysetEqual( responses, ['<AddedCandidate: anika > Bernie Sanders>',], ordered=False )
def candidatesignup(request): if request.method == 'POST': form = UserSignUp(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) p = UserProfile() p.user_type = 'candidate' p.user = user p.save() cand = Candidate() cand.user = user cand.education = 'Depaul' cand.date_of_birth = '1223-3-2' cand.save() login(request, user) return redirect('candidates:candidateeditprofile') else: form = UserSignUp() return render(request, 'candidate_signup.html', {'form': form})
def career_apply(request, job_id): site = Site.objects.get_current() siteDetail = SiteDetail.objects.get(site=site) try: job = Job.objects.get(id=job_id) except: return redirect('careers') # make sure this is a post if request.method == 'POST': # create the new document form = ApplyNowForm(request.POST, request.FILES) if form.is_valid(): try: candidate = Candidate() candidate.first_name = form.cleaned_data['firstName'] candidate.last_name = form.cleaned_data['lastName'] candidate.email = form.cleaned_data['email'] candidate.preferred_communication_method = form.cleaned_data['preferredCommunicationMethod'] candidate.best_contact_time = form.cleaned_data['bestContactTime'] candidate.phone_number = form.cleaned_data['phone'] candidate.status='New' candidate.save() candidateApplication = CandidateApplication() candidateApplication.candidate = candidate candidateApplication.job = job candidateApplication.save() if request.FILES.get('resume', False): doc = CandidateDocument(document=request.FILES['resume']) doc.display_name = form.cleaned_data['resume'] doc.candidate = candidate doc.save() # create the initial contact campaign campaign = initial_contact_campaign(job, candidate) candidate_campaign(site, siteDetail, campaign) # create the response form campaign but don't start it just yet response_form_campaign(job, candidate) # send to our crm system #startPipeline(candidate.id, job) except Exception as e: send_mail( 'Error submitting application for job %s - %s' % (job.id, cgi.escape(job.title)), 'Error submitting an application from %s %s (%s). %s' % ( form.cleaned_data['firstName'], form.cleaned_data['lastName'], form.cleaned_data['email'], e.message), siteDetail.support_email, [siteDetail.support_email], fail_silently=True ) return render(request, 'career_apply.html', {'job': job, 'status': 'error', 'site': site, 'siteDetail': siteDetail, 'errorMessage': e.message}) return render(request, 'career_apply.html', {'job': job, 'status': 'success', 'site': site, 'siteDetail': siteDetail}) else: return render(request, 'career_apply.html', {'job': job, 'status': 'new', 'site': site, 'siteDetail': siteDetail})
class TestQuestionAssignment(TestCase): def setUp(self): # create an organisation user = User(username='******') user.save() org = Organisation(name='test_org') org.user = user org.save() # create three questions self.q1 = Question(question='What is your name?', organisation=org) self.q1.save() # create a candidate self.candidate = Candidate(name='Terry', participating=True, popit_id=1234) self.candidate.save() # post-save hook on candidate will automatically assign q1 q2 = Question(question='What is your quest?', organisation=org) q2.save() q3 = Question(question='What is your favourite colour?', organisation=org) q3.save() # assign 1 question to the candidate self.answer = Answer.objects.get(question=self.q1, candidate=self.candidate) def test_auto_assign(self): """Auto-assign from post-save hook has succeeded""" self.assertEquals(self.answer.question, self.q1) def test_question_assignment_count(self): """Open question count increases when a new question is assigned""" self.assertEquals(self.candidate.get_open_question_count(), 1) existing = Answer.objects.filter(candidate=self.candidate) self.candidate.assign_questions(1) self.assertEquals(self.candidate.get_open_question_count(), 2) pass def test_question_assignment_count_close(self): """Open question count decreases when a question is completed""" self.assertEquals(self.candidate.get_open_question_count(), 1) self.answer.completed = True self.answer.save() self.assertEquals(self.candidate.get_open_question_count(), 0) pass def test_question_assignment(self): """Questions are assigned in age order""" # complete the existing assignment self.answer.completed = True self.answer.save() # assign a new one count = self.candidate.assign_questions(1) self.assertEquals(count, 1) newanswer = Answer.objects.filter(candidate=self.candidate, completed=False)[0] self.assertEquals(newanswer.question.question, "What is your quest?") def test_no_more_questions(self): """No more questions are available""" self.candidate.assign_questions(2) count = self.candidate.assign_questions(1) self.assertEquals(count, 0) def test_unique(self): """Question/Answer combinations must be unique""" answer = Answer(candidate=self.candidate, question=self.q1) self.assertRaises(IntegrityError, answer.save)
def candidato(): with open('/maladireta/database/candidatos.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: if line_count == 0: print(f'Column names are {", ".join(row)}') line_count += 1 else: candidate = Candidate() candidate.name = row[0] candidate.number = row[1] party_query = Party.objects.search(row[2]) if party_query: candidate.party = party_query[0] else: print(candidate.name) if row[4] == 'DE': candidate.position = Position.objects.search( 'Deputado Estadual')[0] elif row[4] == 'DF': candidate.position = Position.objects.search( 'Deputado Federal')[0] elif row[4] == 'G': candidate.position = Position.objects.search( 'Governador')[0] elif row[4] == 'S': candidate.position = Position.objects.search('Senador')[0] candidate.save() return line_count - 1