本文整理汇总了Python中polls.models.Choice类的典型用法代码示例。如果您正苦于以下问题:Python Choice类的具体用法?Python Choice怎么用?Python Choice使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Choice类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_choice_str
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')
示例2: get_question
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})
示例3: generate_elements
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)
示例4: test_unicode
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!')
示例5: add_choice
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})
示例6: vote
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})
示例7: VoteTests
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 = 'test'
user = User(username='test')
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,)))
示例8: test_unicode
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))
示例9: test_form_renders_poll_choices_as_radio_inputs
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())
示例10: createdb
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()
示例11: handle
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')
示例12: test_creating_new_choice_and_saving_it_to_the_database
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)
示例13: setUp
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()
示例14: test_saving_and_retrieving_choices
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)
示例15: create_poll
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