def convert_polls(self): self.clear_polls() cursor = connection.cursor() cursor.execute("SELECT * FROM smf_polls") rows = cursor.fetchall() for row in rows: try: profile = Profile.objects.get(old_user_id=row[7]) try: poll = Poll() poll.old_poll_id = row[0] poll.user = profile.user poll.username = row[8] poll.question = row[1] if row[2] == 1: poll.locked = True poll.expires_on = self.fix_epoch(row[4]) if row[5] == 0: poll.hide_results_until_vote = False if row[6] == 0: poll.allow_changing_votes = False poll.allow_changing_votes = False if row[9] == 1: poll.allow_changing_votes = True poll.hide_results_until_expored = False poll.save() except Exception, e: print "Could not save poll: %s" % (str(e)) except Profile.DoesNotExist, e: pass
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 pollSave(request): # if request.method == 'POST': # if not request.POST.get('subject', ''): # errors.append('Enter a subject.') # if not request.POST.get('message', ''): # errors.append('Enter a message.') # if request.POST.get('email') and '@' not in request.POST['email']: # errors.append('Enter a valid e-mail address.') # if not errors: # send_mail( # request.POST['subject'], # request.POST['message'], # request.POST.get('email', '*****@*****.**'), # ['*****@*****.**'], # ) # return HttpResponseRedirect('/contact/thanks/') title = request.POST.get('title', '') remark = request.POST.get('remark', '') poll = Poll(title=title, remark=remark, createTime=datetime.now()) poll.save() itemIds = request.POST.get('item_ids', '') ids = itemIds.split(',') for id in ids: pollItem = PollItem(title=request.POST.get('item_title' + id, ''), poll=poll) pollItem.save() return render_to_response('pollSave.html')
def gen_poll(self): from poll.models import Poll poll = Poll() candidates = list(self.profile.all()) for elected in self.elected.all(): try: candidates.remove(elected) except ValueError: pass # Option A: candidates <= available posts -> yes/no/abstention if len(candidates) <= self.posts - self.elected.count(): poll.optiondecision = True else: poll.optiondecision = False # Option B: candidates == 1 -> yes/no/abstention #if self.profile.count() == 1: # poll.optiondecision = True #else: # poll.optiondecision = False poll.assignment = self poll.description = self.polldescription poll.save() for candidate in candidates: poll.add_option(candidate) return poll
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/polls/%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) self.assertEquals(choice_in_db.percentage(), 80) # always redirect after a POST - even if, in this case, we go back # to the same page. self.assertRedirects(response, poll_url)
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("over writing poll") 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() ) c.save() count += 1 perecent_complete = count / num_entries * 100 print( "Addind {} new poll: {:.2f}%".format( num_entries, perecent_complete ), end='\r', flush=True ) print()
def post(self, request): title = request.data.get('title') text = request.data.get('text') link = request.data.get('link', 'No link') user = request.user close_date = request.data.get('closeDate', '2424-2-2') if not close_date: close_date = '2424-2-2' participants = request.data.get('participants', []) selects = request.data.get('selects') meeting = Meeting(title=title, text=text, owner=user) meeting.save() poll = Poll(title=title, text=text, meeting=meeting) if close_date: poll.date_close = datetime.datetime.strptime( close_date, '%Y-%m-%d') poll.save() meetingParticipant = MeetingParticipant(meeting=meeting, participant=user) meetingParticipant.save() link += str(poll.id) self.create_participants(meeting, participants, user) self.createOptions(poll, selects) check_poll_close(poll) poll_json = serializers.serialize('json', [poll]) send_email_create_poll(user, title, link, participants) try: return HttpResponse(poll_json, content_type='application/json') except Exception as e: print(e) return HttpResponse404Error("This poll doesn\'t exist.")
def test_index(self, app, client): with app.app_context(): now = datetime.now() p = Poll(id=None, name="Mon premier sondage", date=now) p.save() response = client.get("/") assert response.status_code == 200 assert b"Aucuns sondages actifs" not in response.data assert b"Mon premier sondage" in response.data
def test_get_poll_by_id(self, app): with app.app_context(): now = datetime.now() p = Poll(id=None, name="Nom", date=now) p.save() new_poll = Poll.get_poll_by_id(1) assert new_poll.id == 1 assert new_poll.name == "Nom" assert new_poll.date == str(now)
def gen_poll(self, user=None): """ Generates a poll object for the application """ from poll.models import Poll poll = Poll(optiondecision=True, \ application=self) poll.save() poll.add_option(self) self.writelog(_("Poll created"), user) return poll
def test_save_inserts_row(self, app): with app.app_context(): now = datetime.now() p = Poll(id=None, name="Nom", date=now) p.save() new_poll = get_db().execute( "SELECT id, name, date FROM polls WHERE id = ?", [1]).fetchone() assert new_poll[0] == 1 assert new_poll[1] == "Nom" assert new_poll[2] == str(now)
def test_poll_url_shows_all_polls(self): poll1 = Poll(question='6 times 7', pub_date=timezone.now()) poll1.save() poll2 = Poll(question='life, the universe and everything', pub_date=timezone.now()) poll2.save() response = self.client.get('/poll/polls/') ##logger.info(response) self.assertTemplateUsed(response, 'index.html') # check we've passed the polls to the template polls_in_context = response.context['latest_poll_list'] ##logger.info(response.context) self.assertEquals(list(polls_in_context).sort(), [poll1, poll2].sort()) # check the poll names appear on the page self.assertIn(poll1.question, response.content) self.assertIn(poll2.question, response.content)
def test_get_polls(self, app): with app.app_context(): now = datetime.now() p = Poll(id=None, name="Nom", date=now) p.save() p = Poll(id=None, name="Nom #2", date=now) p.save() new_poll = Poll.get_polls() assert new_poll[0].id == 1 assert new_poll[0].name == "Nom" assert new_poll[0].date == str(now) assert new_poll[1].id == 2 assert new_poll[1].name == "Nom #2" assert new_poll[1].date == str(now)
def poll_creation_form(request): if request.method == "POST": poll_form = PollForm(request.POST) content = {"form": poll_form} if poll_form.is_valid(): poll = Poll(poll_name=poll_form.cleaned_data["poll_name"], start_date=poll_form.cleaned_data["start_date"], manager=request.user.email, end_date=poll_form.cleaned_data["end_date"]) poll.save() poll.member.add(request.user) return redirect("pollhome.page") else: return render(request, "poll/poll_form.html", content) else: poll_form = PollForm() content = {"form": poll_form} return render(request, "poll/poll_form.html", content)
def test_get_number_of_votes(self, app): with app.app_context(): now = datetime.now() p = Poll(id=None, name="Nom", date=now) p.save() assert p.number_of_votes() == 0 c1 = Choice(id=None, choice="Premier choix", poll=p) c1.save() c2 = Choice(id=None, choice="Deuxième choix", poll=p) c2.save() assert p.number_of_votes() == 0 c1.cast_vote() c1.cast_vote() c2.cast_vote() assert p.number_of_votes() == 3
def test_page_shows_choices_using_form(self): # set up a poll with choices poll1 = Poll(question='time', pub_date=timezone.now()) poll1.save() choice1 = Choice(poll=poll1, choice="PM", votes=0) choice1.save() choice2 = Choice(poll=poll1, choice="Gardener's", votes=0) choice2.save() response = self.client.get('/poll/polls/%d/' % (poll1.id, )) # check we've passed in a form of the right type self.assertTrue(isinstance(response.context['form'], PollVoteForm)) self.assertTrue(response.context['poll'], poll1) self.assertTemplateUsed(response, 'poll.html') # and check the check the form is being used in the template, # by checking for the choice text self.assertIn(choice1.choice, response.content.replace(''', "'")) self.assertIn(choice2.choice, response.content.replace(''', "'")) self.assertIn('csrf', response.content) self.assertIn('0 %', response.content)
class PollTest(TestCase): def setUp(self): self.queue = Queue(title='TestQueue', auth=False) self.queue.save() self.poll = Poll(title='TestPoll', queue=self.queue, polltype=0, startdate=datetime.now()) self.poll.save() self.item = self.poll.item_set.create(userbox=False, value='One', index=0) self.client = Client() def test_voting(self): request = self.client.post( reverse('poll_ajax_vote', args=(self.poll.pk,)), {'chosen_items': '{"%s": "radio"}'\ % (self.item.id,)}, HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(request.status_code, 200) self.assertEqual(Vote.objects.count(), 1)
def create_new_poll_from_post_data(cls, post_data, date): poll = Poll(id=None, name=post_data['name'], date=date) poll.save() return poll
def add_poll( request ): errors = [] if request.method == 'POST': word = re.compile( r'\s*\w+\s*' ) title = request.POST.get( 'title', '' ) if not title or not word.search( title ): errors.append( 'Need to add a title.' ) else: single_choice_str = request.POST.get( 'is_single_choice', '' ) is_single_choice = True if not single_choice_str: is_single_choice = False count = 0 options = [] for key, value in request.POST.items(): if key.startswith( 'option' ): if word.search( value ): count += 1 options.append({ 'key': key, 'value':value }) if count < 2: errors.append( 'Need 2 or more options.' ) else: poll = Poll( user= request.user, title= title, is_single_choice= is_single_choice ) poll.save() def sortById( element ): theKey = element[ 'key' ] theId = re.match( r'\w+(?P<id>\d+)', theKey ) return theId.group( 'id' ) options.sort( key= sortById ) for aOption in options: poll.option_set.create( text= aOption[ 'value' ] ) return HttpResponseRedirect( poll.get_url() ) context = { 'errors': errors, 'initial_options': range( 1, 4 ), 'title_length': POLL_TITLE_LENGTH, 'option_length': OPTION_TEXT_LENGTH } return render( request, 'add_poll.html', context )