def test_choice_str(self): time = timezone.now() question = Question(pub_date=time) choice = Choice() choice.question = question choice.choice_text = 'Choice1' self.assertEqual(str(choice), 'Choice1')
def handle(self, *args, **options): # delete Questionnaire.objects.filter(id__gt=3).delete() # reset index ALTER TABLE table_name AUTO_INCREMENT = 1; gene_time = options['gene_num'] origin_count = Questionnaire.objects.count() for i in range(gene_time): polls_orders = origin_count + i + 1 print(polls_orders) pub_date = timezone.now() - datetime.timedelta(days=(400 - i)) questionnaire = Questionnaire( questionnaire_name="测试问卷{}".format(polls_orders), pub_date=pub_date, detail_info="用于测试的问卷") questionnaire.save() for j in range(4): question = Question(question_text="测试问题{}".format(j + 1), question_type=1, questionnaire=questionnaire) question.save() for k in range(4): choice = Choice(choice_text="测试选项{}".format(k + 1), votes=random.randint(50, 200), question=question) choice.save() self.stdout.write( self.style.SUCCESS('Successfully generate test questionnaire'))
class VoteTests(base.BaseTestCase): def setUp(self): super().setUp() self.question = Question.objects.create( question_text='Is this a test?', pub_date=timezone.now() ) self.question.save() self.choice1 = Choice( question=self.question, choice_text='No', votes=0, ) self.choice1.save() self.choice2 = Choice( question=self.question, choice_text='Yes', votes=0, ) self.choice2.save() def test_view(self): url = reverse('polls:vote', args=(self.question.id,)) request = self.request_factory.post(url, {'choice': self.choice2.id}) response = vote(request, self.question.id) self.assertEqual(response.status_code, 302) self.assertEqual(response.url, reverse('polls:results', args=(self.question.id,)))
def get_question(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = QuestionForm(request.POST) # check whether it's valid: if form.is_valid(): question_body = request.POST.get('your_question', '') new_question = Question(question_text=question_body, pub_date=timezone.now()) new_question.save() characters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w', 'x','y','z'] for i in range(0, 5): answer_text = 'your_answer_' + characters[i] new_answer = request.POST.get(answer_text, '') if new_answer != '': new_choice = Choice(question=new_question, choice_text=new_answer, votes=0) new_choice.save() # process the data in form.cleansed_data as required # ... # redirect to a new URL: return HttpResponseRedirect('/polls/') # if a GET (or any other method) we'll create a blank form else: form = QuestionForm() return render(request, 'polls/question.html', {'form': form})
def generate_elements(count=1): """ this guy generates db elements for testing """ for k in range(count): question = "" for i in range(choice((2, 3, 4, 5, 6, 7))): question = " ".join((question, choice(WORDS))) question = question[1:] + "?" question = question[0].upper() + question[1:] q = Question(question_text=question, pub_date=timezone.now()) q.save() print(q.id, q.question_text) for choicecount in range(choice((2, 3))): choicetxt = "" for choicewords in range(choice((2, 3, 4, 5))): choicetxt = " ".join((choicetxt, choice(WORDS))) choicetxt = choicetxt[1:] choicetxt = choicetxt[0].upper() + choicetxt[1:] + "." # print('\t', choicetxt) ch = Choice(question=q, choice_text=choicetxt, votes=choice((0, 1, 2, 3, 4, 5))) ch.save() print("\t", ch.question.id, ch.choice_text)
def add_choice(request, poll_id): p = get_object_or_404(Poll, pk=poll_id) try: new_choice = Choice( poll = p, choice_text = request.POST['choice_text'], choice_desc = request.POST['choice_desc'], proposer = request.POST['proposer'], votes = 1 ); new_choice.save() except IntegrityError: return render(request, 'polls/detail.html', { 'poll': p, 'error_propose_message': request.POST['choice_text'] + u": 이미 존재하는 이름입니다.", }) try: if 'suggest_subscribe_check' in request.POST.keys(): subscribe_check = True else: subscribe_check = False new_voter = Voter(poll=p, choice=new_choice, email=request.POST['proposer'], subscription=subscribe_check) new_voter.save() except Exception as err: print err.message, type(err) # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. #return HttpResponseRedirect(reverse('results', args=(p.id,))) return render(request, 'polls/results.html', {'poll': p})
def add_poll(request): if request.method == 'POST': form = PollForm(request.POST) if form.is_valid(): new_poll = form.save(commit=False) new_poll.owner = request.user new_poll.pub_date = datetime.datetime.now() new_poll.save() new_choice1 = Choice( poll=new_poll, choice_text=form.cleaned_data['choice1']).save() new_choice2 = Choice( poll=new_poll, choice_text=form.cleaned_data['choice2']).save() messages.success( request, 'Poll and Choices Added!', extra_tags='alert alert-success alert-dismissible fade show') return redirect('polls:list') else: form = PollForm() context = {'form': form} return render(request, 'polls/add_poll.htm', context)
def test_vote_answer_type_ONE(self): Poll.objects.create( name='Test_ONE', question='question1', begin_date=timezone.now(), end_date=timezone.now()+timezone.timedelta(minutes=1), answer_type='ONE' ) poll = Poll.objects.get(name='Test_ONE') poll.choice_set.add(Choice(choice_text='ans1', created=timezone.now())) poll.choice_set.add(Choice(choice_text='ans2', created=timezone.now())) poll.choice_set.add(Choice(choice_text='ans3', created=timezone.now())) choices = poll.get_ordered_choices() self._common_test_for_ONE_and_MANY(poll, choices) response = self.client.post( '/polls/%s/vote/' % poll.id, { 'choice': [choices[1].id, choices[2].id], }, follow=True ) messages = list(response.context['messages']) self.assertEqual(len(messages), 1) self.assertEqual('Вы должны выбрать один вариант ответа', str(messages[0])) self._check_results(choices, self._last_results)
def test_unicode(self): """ __unicode__ should return the text of choice """ poll = create_poll(question='Poll', days=-5) choice = Choice(poll=poll, choice_text='Awesome!', votes=5) self.assertEqual(choice.__unicode__(), 'Awesome!')
def setUpClass(cls): u = User.objects.create_user('simeon', '*****@*****.**', 'password') p = Poll(user=u, question="Why?", pub_date=dt.now()) p.save() Choice.objects.bulk_create([ Choice(poll=p, choice="Because", votes=0), Choice(poll=p, choice="Because", votes=0) ]) cls.p = p
def question_page(request, question_pk): question = Question.objects.get(pk=question_pk) if request.method == 'POST': answer = request.POST['answer'] choice = Choice(question=question, choice_text=answer) choice.save() return render(request, 'question_detail.html', context={'question': question})
def _create_choices(self): question = Question.objects.get(id=1) Choice(question=question, choice_text='Billy Eyelash').save() Choice(question=question, choice_text='BLACKPINK').save() Choice(question=question, choice_text='Clairo').save() Choice(question=question, choice_text='Dua Lipa').save() Choice(question=question, choice_text='Taylor Swift').save() print("***** ADDING TEST CHOICES TO THE DATABASE *****")
def vote(request): #we need to check if its before 4pm if request.method == "POST": form = polls.forms_DK.NameForm(request.POST) if form.is_valid(): your_email = form.cleaned_data["your_email"] ratio = str(form.cleaned_data["ratio"]) django.setup() timer_split = get_timer() dater = timer_split[0] hrs = timer_split[1] # we check if the user exists in the database. try: checking_email = Person.objects.get(email=your_email) except: address = "registration/" return HttpResponseRedirect(address) #Checking if its before 4pm cut_hour if datetime.datetime.now() < cut_hour: print "you can still vote" #quering to see if the person voted date_query = Choice.objects.filter(date_vote=dater) voted = False for i in date_query: if i.person_id == checking_email.id: voted = True print "you voted" # action if he voted or not if voted is False: cc = Choice(date_vote=dater, time_vote=hrs, restaurant_vote_id=ratio, person_id=checking_email.id) cc.save() address = "thank/?email="+your_email+"/" return HttpResponseRedirect(address) elif voted is True: message = "you already voted tomorrow try again" return render(request, "thanks.html", {"message": message}) address = "thank/?email="+your_email+"/" return HttpResponseRedirect(address) else: # if its after cut_hour message = "its after time, talk to your PA he might take your order" return render(request, "thanks.html", {"message": message}) #regular empty forms render for the first time. else: form = polls.forms_DK.NameForm() django.setup() all_restaurants = Restaurant.objects.all() message = "select the restaurant of your choice before: " + str(cut_hour_12) return render(request, "vote_form.html", {"message": message, "all_restaurants": all_restaurants, "form": form})
class VoteTests(base.BaseTestCase): def setUp(self): super().setUp() self.request_factory = RequestFactory() self.question = self.create_question(question_text='Some question.', days=0) self.question.save() self.choice1 = Choice( question=self.question, choice_text='Choice 1', votes=0, ) self.choice1.save() self.choice2 = Choice( question=self.question, choice_text='Choice 2', votes=0, ) self.choice2.save() def test_vote_counts_with_client(self): url = reverse('polls:vote', args=(self.question.id,)) # follow=True follows the redirect chain so response is the end page response = self.client.post(url, {'choice': self.choice2.id}, follow=True) self.assertEqual(response.status_code, 200) self.assertContains(response, "<li>{} -- 0 votes</li>".format(self.choice1.choice_text)) self.assertContains(response, "<li>{} -- 1 vote</li>".format(self.choice2.choice_text)) def test_post_redirect_with_client(self): url = reverse('polls:vote', args=(self.question.id,)) response = self.client.post(url, {'choice': self.choice2.id}) self.assertEqual(response.status_code, 302) self.assertEqual(response['Location'], reverse('polls:results', args=(self.question.id,))) def test_logged_in_redirect(self): # This test is no different from test_post_redirect, but it # shows an example with logging in before calling `post`. password = '******' user = User(username='******') user.set_password(password) user.save() logged_in = self.client.login(username=user.username, password=password) self.assertTrue(logged_in) url = reverse('polls:vote', args=(self.question.id,)) response = self.client.post(url, {'choice': self.choice2.id}) self.assertEqual(response.status_code, 302) self.assertEqual(response['Location'], reverse('polls:results', args=(self.question.id,)))
def test_unicode(self): """ str(Choice) or unicode(Choice) should be the choice_text """ poll = create_poll(question="Testing unicode", days=0) choice = Choice(poll=poll, choice_text="Testing is fun!") choice.save() self.assertEqual(str(choice), choice.choice_text) self.assertEqual(unicode(choice), choice.choice_text) self.assertEqual(str(choice), unicode(choice))
def test_add_choice_to_no_question(): """ Assert Integrity error if a choice is added to a question that does not exist """ with pytest.raises(IntegrityError) as excinfo: choice = Choice(question_id=33, choice_text="Test choice", votes=23) choice.save() assert "FOREIGN KEY constraint failed" in str(excinfo)
def test_form_renders_poll_choices_as_radio_inputs(self): # set up a poll with a couple of choices poll1 = Poll(question='6 times 7', pub_date=timezone.now()) poll1.save() choice1 = Choice(poll=poll1, choice='42', votes=0) choice1.save() choice2 = Choice(poll=poll1, choice='The Ultimate Answer', votes=0) choice2.save() # set up another poll to make sure we only see the right choices poll2 = Poll(question='time', pub_date=timezone.now()) poll2.save() choice3 = Choice(poll=poll2, choice='PM', votes=0) choice3.save() # build a voting form for poll1 form = PollVoteForm(poll=poll1) # check it has a single field called 'vote', which has right choices: self.assertEquals(form.fields.keys(), ['vote']) # choices are tuples in the format (choice_number, choice_text): self.assertEquals(form.fields['vote'].choices, [ (choice1.id, choice1.choice), (choice2.id, choice2.choice), ]) # check it uses radio inputs to render self.assertIn('input type="radio"', form.as_p())
def test_list_question_relation(self): q = Question( question_text="question_text_006", pub_date=timezone.now()) q.save() c = Choice(question=q, choice_text="006_001") c.save() response = self.client.get( reverse("polls:choice-list"), **self.auth_headers) self.assertEqual(q.id, json.loads(response.content)[0]["question"])
def createdb(): from django.utils import timezone from polls.models import Poll, Choice n = int(raw_input("Enter no. of items to create: ")) for i in xrange(n): p = Poll(question="Question = {0}".format(i), pub_date = timezone.now()) p.save() for i in xrange(4): cycle = ['a', 'b', 'c', 'd'] c = Choice(poll = p, choice_text = cycle[i], votes = 0) c.save()
def handle(self, *args, **options): for pc in data: p = Poll(**pc['poll']) p.save() self.stdout.write('saved Poll: {}'.format(p)) for c in pc['choices']: c = Choice(**c) c.poll = p c.save() self.stdout.write('saved Choice: {}'.format(c), ending=',') self.stdout.write('') self.stdout.write('DONE')
def setUp(self): User.objects.create_user(username='******', password='******') self.client.login(username='******', password='******') self.question = create_question("1 or 2?", pub_date=-4, end_date=5) self.first_choice = Choice(id=1, question=self.question, choice_text="1") self.second_choice = Choice(id=2, question=self.question, choice_text="2") self.first_choice.save() self.second_choice.save()
def test_creating_new_choice_and_saving_it_to_the_database(self): #creating a poll object poll = Question(question_text="What are my choices?", pub_date=timezone.now()) poll.save() #creating a choice object choice = Choice(question=poll, choice_text="You have no choice", votes=0) choice.save() #searching in database all_choices_in_database = poll.choice_set.all() self.assertEquals(all_choices_in_database.count(), 1)
def test_add_choice_to_question(): """ Test if we can add a choice to a question safely """ pub_date = timezone.now() question = Question(question_text="Test question", pub_date=pub_date) question.save() choice = Choice(question_id=question.id, choice_text="Test choice", votes=23) choice.save() assert choice.choice_text == "Test choice" assert choice.votes == 23
def setUp(self): User.objects.create_user(username='******', password='******') self.client.login(username='******', password='******') self.question = create_question("What is your gender?", pub_date=-4, end_date=5) self.first_choice = Choice(id=1, question=self.question, choice_text="male") self.second_choice = Choice(id=2, question=self.question, choice_text="female") self.first_choice.save() self.second_choice.save()
def setUp(self): super(TestPollSample,self).setUp() self.poll = Poll( question="What is your favorite number?", pub_date=datetime.now() ) self.poll.save() for i in range(1, 4): choice = Choice( poll = self.poll, choice=str(i), votes=0 ) choice.save()
def test_view_can_handle_votes_via_POST(self): # set up a poll with choices poll1 = Poll(question='6 times 7', pub_date=timezone.now()) poll1.save() choice1 = Choice(poll=poll1, choice='42', votes=1) choice1.save() choice2 = Choice(poll=poll1, choice='The Ultimate Answer', votes=3) choice2.save() # set up our POST data - keys and values are strings post_data = {'vote': str(choice2.id)} # make our request to the view poll_url = '/poll/%d/' % (poll1.id, ) response = self.client.post(poll_url, data=post_data) # retrieve the updated choice from the database choice_in_db = Choice.objects.get(pk=choice2.id) # check it's votes have gone up by 1 self.assertEquals(choice_in_db.votes, 4) # always redirect after a POST - even if, in this case, we go back # to the same page. self.assertRedirects(response, poll_url)
def test_saving_and_retrieving_choices(self): choice = Choice() choice.choice_text = '1. Demi Moore 2. Julia Roberts' choice.votes = 1000 choice.save() saved_choices = Choice.objects.all() self.assertEqual(saved_choices.count(), 1) saved_choice = saved_choices[0] self.assertIn('1. Demi Moore 2. Julia Roberts', repr(saved_choice), ) self.assertEqual(saved_choice.choice_text, '1. Demi Moore 2. Julia Roberts') self.assertEqual(saved_choice.votes, 1000)
def create_poll(question, days, choice_text=CHOICE_TEXT): """ Creates a poll with the given 'question' published the given number of 'days' offset to now (negative for polls published in the past, positive for polls that have yet to be published). """ now = timezone.now() result = Poll(question=question, pub_date=now + datetime.timedelta(days)) result.save() if choice_text: choice = Choice(choice_text=choice_text, poll=result) choice.save() return result
def index(request): if request.method=='GET' : latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5] return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list}) elif request.method== 'POST' : newPoll=Poll(question=request.POST["poll"]) newPoll.save() for key in request.POST.keys(): if key.startswith("choice"): choice=Choice(poll=newPoll, choice=request.POST[key], votes=0) choice.save() latest_poll_list = Poll.objects.all().order_by('-pub_date')[Poll.objects.count()-1] return HttpResponseRedirect('/')
def insert_record(request): left = request.POST['left'] right = request.POST['right'] choice = request.POST['choice'] usetime = request.POST['usetime'] userID = request.POST['userID'] newChoice = Choice(use_time=usetime, left_pic_id=left, right_pic_id=right, choice_num=choice, user_id=userID) print("newChoice") print(newChoice) newChoice.save() return JsonResponse({'inserted': True})
def results(request, poll_key): try: p = Poll.get_by_id(int(poll_key)) c = Choice.query(Choice.poll == p.key) except: raise Http404 return render_to_response('polls/results.html', {'poll': p, 'choices': c})
def test(): import os from django.conf import settings from polls.models import Choice from django.db.utils import IntegrityError from PIL import Image for filename in os.listdir(settings.MEDIA_ROOT): try: Image.open(settings.MEDIA_ROOT + filename) except: pass else: if not Choice.objects.filter(image=filename): choice = Choice(image=filename) choice.save()
def seed_polls(num_entries=10, choice_min=2, choice_max=5, overwrite=False): """ Seeds num_entries poll with random users as owners Each poll will be seeded with # choices from choice_min to choice_max """ if overwrite: print('Overwriting polls') Poll.objects.all().delete() users = list(User.objects.all()) count = 0 for _ in range(num_entries): p = Poll(owner=random.choice(users), text=fake.paragraph(), pub_date=datetime.datetime.now()) p.save() num_choices = random.randrange(choice_min, choice_max + 1) for _ in range(num_choices): c = Choice(poll=p, choice_text=fake.sentence()).save() count += 1 percent_complete = count / num_entries * 100 print("Adding {} new Polls: {:.2f}%".format(num_entries, percent_complete), end='\r', flush=True) print()
def create_question(self, question_text, choice_texts): question = Question(question_text=question_text) question.save() for choice_text in choice_texts: Choice(question=question, choice_text=choice_text).save() return question
def objects(): for ln in DATA.splitlines(): if ln: a = ln.split('|') q = Question(question_text=a[0].strip()) yield q for choice in a[1:]: yield Choice(choice_text=choice.strip(), question=q)
def objects(): for ln in DATA.splitlines(): if ln: a = ln.split('|') p = Poll(question=a[0].strip()) yield p for choice in a[1:]: yield Choice(choice=choice.strip(), poll=p)
def test_replace_user_vote(self): self.new_question = create_question(question_text='How are you', days=-5) self.first_choice = Choice(id = 1, question = self.new_question, choice_text = "I'm ok") self.second_choice = Choice(id = 2, question = self.new_question, choice_text = "I'm fine") self.first_choice.save() self.second_choice.save() self.client.login(username='******', password='******') response = self.client.post(reverse('polls:vote', args=(self.new_question.id,)), {'choice':self.first_choice.id}) self.first_choice = self.new_question.choice_set.get(pk = self.first_choice.id) self.assertEqual(response.status_code, 302) self.assertEqual(self.first_choice.vote_set.all().count(), 1) response = self.client.post(reverse('polls:vote', args=(self.new_question.id,)), {'choice':self.second_choice.id}) self.second_choice = self.new_question.choice_set.get(pk = self.second_choice.id) self.first_choice = self.new_question.choice_set.get(pk = self.first_choice.id) self.assertEqual(response.status_code, 302) self.assertEqual(self.second_choice.vote_set.all().count(), 1) self.assertEqual(self.first_choice.vote_set.all().count(), 0)
def test_choice_can_calculate_its_own_percentage_of_votes(self): poll = Poll(question='who?', pub_date=timezone.now()) poll.save() choice1 = Choice(poll=poll, choice='me', votes=2) choice1.save() choice2 = Choice(poll=poll, choice='you', votes=1) choice2.save() self.assertEquals(choice1.percentage(),100*2/3.0 ) self.assertEquals(choice2.percentage(), 100*1/3.0)
def test_creating_some_choices_for_a_poll(self): # start by creating a new Poll object poll = Poll() poll.question = "What's up?" poll.pub_date = timezone.now() poll.save() # now create a Choice object choice = Choice() # link it with our Poll choice.poll = poll # give it some text choice.choice = "doin' fine..." # and let's say it's had some votes choice.votes = 3 # save it choice.save() # try retrieving it from the database, using the poll object's reverse # lookup poll_choices = poll.choice_set.all() self.assertEquals(poll_choices.count(), 1) # finally, check its attributes have been saved choice_from_db = poll_choices[0] self.assertEquals(choice_from_db, choice) self.assertEquals(choice_from_db.choice, "doin' fine...") self.assertEquals(choice_from_db.votes, 3)
def create(request): """Creates a new poll instance.""" poll = Poll( question = request.POST['question'], pub_date = datetime.datetime.now() ) poll.save() choice = Choice(poll=poll, choice= request.POST['choice1'], votes=0) choice.save() choice = Choice(poll=poll, choice= request.POST['choice2'], votes=0) choice.save() choice = Choice(poll=poll, choice= request.POST['choice3'], votes=0) choice.save() return HttpResponseRedirect('/polls/%s' % poll.id)
def test_create_some_choices_for_a_poll(self): # Create new poll object poll = Poll() poll.question = "What's up?" poll.pub_date = timezone.now() poll.save() # Create Choice object choice = Choice() choice.poll = poll choice.choice = "doin' fine..." # Give it faux votes choice.votes = 3 choice.save() # Try to retrieve from DB using poll's reverse lookup. poll_choices = poll.choice_set.all() self.assertEquals(poll_choices.count(), 1) # Finally, check attrbs have been saved choice_from_db = poll_choices[0] self.assertEqual(choice_from_db, choice) self.assertEqual(choice_from_db.choice, "doin' fine...") self.assertEqual(choice_from_db.votes, 3)
def detail(request, poll_key): try: p = Poll.get_by_id(int(poll_key)) c = Choice.query(Choice.poll == p.key) except: raise Http404 return render_to_response('polls/detail.html', {'poll': p, 'choices': c}, context_instance=RequestContext(request))
def save(request): qd = request.POST quest = "" if(qd['createNew'] == "false"): id = int(qd['qid']) quest = get_object_or_404(Question,pk=id) quest.question_text = qd['qt'] quest.pub_date = datetime.strptime(qd['date'] + ' ' + qd['time'], '%Y-%m-%d %H:%M') quest.choice_set.all().delete() else: quest = Question(question_text=qd['qt'],pub_date=datetime.strptime(qd['date'] + ' ' + qd['time'], '%Y-%m-%d %H:%M')) quest.save() m = qd['arrayChoice'].split('\0,') m[len(m)-1] = m[len(m)-1][:-1] for el in m: c = Choice(choice_text=el,votes=0,question=quest) c.save() return redirect('detail',quest.id)
def save(self): if not self.form.is_valid(): return False self.reset_pdf_cache() data = self.form.cleaned_data slide_set = self.event.presentation.slide_set if slide_set == None: slide_set = SlideSet() slide_set.presentation = self.event.presentation slide_set.save() self.event.presentation.slide_set = slide_set slide = self.form.instance if data['slide_type'] == 'poll': # delete the old slide if it has been changed to a poll if slide.id != None: slide.delete() slide = Poll() slide.question = data['poll_question'] slide.slide_set = slide_set slide.offset = data['offset'] if data['image']: base_path = os.path.dirname(slide_upload_to(slide, data['image'].name)) slide.image = self.upload_file(data['image'], upload_to = base_path) self.event.presentation.video = data['video'] slide.save() self.event.presentation.save() # we need to save the poll choices here, after the poll is saved and has an id if data['slide_type'] == 'poll': for choice_text in data['poll_choices'].split('\n'): print '!!!! choice: %s' % choice_text choice = Choice() choice.choice = choice_text choice.poll = slide choice.save() return True
class VotingTests(TestCase): def setUp(self): User.objects.create_user(username='******', password='******') self.client.login(username='******', password='******') self.question = create_question("What is your gender?", pub_date=-4, end_date=5) self.first_choice = Choice(id=1, question=self.question, choice_text="male") self.second_choice = Choice(id=2, question=self.question, choice_text="female") self.first_choice.save() self.second_choice.save() def test_authenticated_user_can_replace_their_vote(self): '''test authenticated user can replace their vote in this polls period''' response = self.client.post( reverse('polls:vote', args=(self.question.id, )), {'choice': self.first_choice.id}) self.first_choice = self.question.choice_set.get( pk=self.first_choice.id) self.assertEqual(self.first_choice.vote_set.all().count(), 1) response = self.client.post( reverse('polls:vote', args=(self.question.id, )), {'choice': self.second_choice.id}) self.second_choice = self.question.choice_set.get( pk=self.second_choice.id) self.first_choice = self.question.choice_set.get( pk=self.first_choice.id) self.assertEqual(self.second_choice.vote_set.all().count(), 1) self.assertEqual(self.first_choice.vote_set.all().count(), 0) def test_previous_vote_show(self): '''test previos vote show on detail page''' response1 = self.client.get( reverse('polls:detail', args=(self.question.id, ))) self.assertContains(response1, "None") self.client.post(reverse('polls:vote', args=(self.question.id, )), {'choice': self.first_choice.id}) response1 = self.client.get( reverse('polls:detail', args=(self.question.id, ))) self.assertNotContains(response1, "None")
def setup_poll1(self): poll = Poll(question='Which is better?', pub_date=timezone.now()) poll.save() email_choice = Choice(question=poll, choice_text='Email sign-up') email_choice.save() external_choice = Choice(question=poll, choice_text='External sign-in') external_choice.save() return (poll, email_choice, external_choice)
def test_vote_answer_type_MANY(self): Poll.objects.create( name='Test_MANY', question='question1', begin_date=timezone.now(), end_date=timezone.now()+timezone.timedelta(minutes=1), answer_type='MANY' ) poll = Poll.objects.get(name='Test_MANY') poll.choice_set.add(Choice(choice_text='ans1', created=timezone.now())) poll.choice_set.add(Choice(choice_text='ans2', created=timezone.now())) poll.choice_set.add(Choice(choice_text='ans3', created=timezone.now())) choices = poll.get_ordered_choices() self._common_test_for_ONE_and_MANY(poll, choices) response = self.client.post( '/polls/%s/vote/' % poll.id, { 'choice': [choices[1].id, choices[2].id], }, follow=True ) results = self._last_results results[1] += 1 results[2] += 1 self._check_results(choices, results) response = self.client.post( '/polls/%s/vote/' % poll.id, { 'choice': [choices[1].id, choices[1].id, choices[0].id], }, follow=True ) results = self._last_results results[1] += 1 results[0] += 1 self._check_results(choices, results)
def create_poll(request): current_user = get_current_user(request=request) if request.method == "POST": #Create poll new_poll = Poll() new_poll.pub_date = datetime.datetime.now() new_poll.question = request.POST["question"] new_poll.master = current_user new_poll.save() #Create answers answers = [request.POST["answer1"], request.POST["answer2"], request.POST["answer3"], request.POST["answer4"], request.POST["answer5"], request.POST["answer6"]] for answer in answers: if answer != "": new_choice = Choice() new_choice.poll = new_poll new_choice.choice_text = answer new_choice.save() return render(request, "add_poll.html", {"current_user": current_user})
def objects(): p = Question(question_text="What is your preferred colour?") yield p yield Choice(choice_text="Blue", question=p) yield Choice(choice_text="Red", question=p) yield Choice(choice_text="Yellow", question=p) yield Choice(choice_text="other", question=p) p = Question(question_text="Do you like Django?") yield p yield Choice(choice_text="Yes", question=p) yield Choice(choice_text="No", question=p) yield Choice(choice_text="Not yet decided", question=p) p = Question(question_text="Do you like ExtJS?") yield p yield Choice(choice_text="Yes", question=p) yield Choice(choice_text="No", question=p) yield Choice(choice_text="Not yet decided", question=p)
def form_valid(self, form): choices_list = [] if isinstance(form.cleaned_data['choice'], Choice): choice = form.cleaned_data['choice'] choice.votes.add(self.request.user) choices_list.append(choice) elif isinstance(form.cleaned_data['choice'], str): choice = Choice(question_id=self.kwargs['question_id'], choice_text=form.cleaned_data['choice']) choice.save() choice.votes.add(self.request.user) else: for choice in form.cleaned_data['choice']: choice.votes.add(self.request.user) choices_list.append(choice) bulk_update(choices_list) return HttpResponseRedirect( reverse('polls:results', args=(self.get_form_kwargs()['question_id'], )))
def vote(request, question_id): p = get_object_or_404(Question, pk=question_id) try: selected_choice = Choice() for choice in get_list_or_404(Choice, question=question_id): if choice.id == long(request.POST['choice']): selected_choice = choice except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': p, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
def add(request): """Adds a new poll to the polls. Might be used for mass insertion of polls. Is currently commented out in template, but fully functional if uncommented""" poll = Poll( question = request.POST['question'], pub_date = datetime.datetime.now() ) poll.save() choice = Choice(poll=poll, choice= request.POST['choice1'], votes=0) choice.save() choice = Choice(poll=poll, choice= request.POST['choice2'], votes=0) choice.save() choice = Choice(poll=poll, choice= request.POST['choice3'], votes=0) choice.save() return HttpResponseRedirect('/polls/')
def setUp(self): super().setUp() self.request_factory = RequestFactory() self.question = self.create_question(question_text='Some question.', days=0) self.question.save() self.choice1 = Choice( question=self.question, choice_text='Choice 1', votes=0, ) self.choice1.save() self.choice2 = Choice( question=self.question, choice_text='Choice 2', votes=0, ) self.choice2.save()
def test_view_can_handle_votes_via_POST(self): # set up a poll with choices poll1 = Poll(question='6 times 7', pub_date=timezone.now()) poll1.save() choice1 = Choice(poll=poll1, choice='42', votes=1) choice1.save() choice2 = Choice(poll=poll1, choice='The Ultimate Answer', votes=3) choice2.save() # set up our POST data - keys and values are strings post_data = {'vote': str(choice2.id)} # make our request to the view poll_url = '/poll/%d/' % (poll1.id,) response = self.client.post(poll_url, data=post_data) # retrieve the updated choice from the database choice_in_db = Choice.objects.get(pk=choice2.id) # check it's votes have gone up by 1 self.assertEquals(choice_in_db.votes, 4) # always redirect after a POST - even if, in this case, we go back # to the same page. self.assertRedirects(response, poll_url)
def test_creating_some_choices_for_a_poll(self): # Start by creating a new Poll object poll = Poll() poll.question = "What's up?" poll.pub_date = timezone.now() poll.save() # Now we create a Choice object choice = Choice() # Link it to our poll choice.poll = poll choice.choice = 'Doing fine...' choice.votes = 3 choice.save() # Try retrieving from the database using the poll object's reverse lookup poll_choices = poll.choice_set.all() self.assertEquals(poll_choices.count(), 1) # Finally, check that its attributes have been saved choice_from_db = poll_choices[0] self.assertEquals(choice_from_db, choice) self.assertEquals(choice_from_db.choice, 'Doing fine...') self.assertEquals(choice_from_db.votes, 3)
def test_view_shows_total_votes(self): # set up a poll with choices poll1 = Poll(question='6 times 7', pub_date=timezone.now()) poll1.save() choice1 = Choice(poll=poll1, choice='42', votes=1) choice1.save() choice2 = Choice(poll=poll1, choice='The Ultimate Answer', votes=2) choice2.save() response = self.client.get('/poll/%d/' % (poll1.id, )) self.assertIn('3 votes', response.content) # also check we only pluralise "votes" if necessary. details! choice2.votes = 0 choice2.save() response = self.client.get('/poll/%d/' % (poll1.id, )) self.assertIn('1 vote', response.content) self.assertNotIn('1 votes', response.content)