本文整理汇总了Python中polls.models.Choice.save方法的典型用法代码示例。如果您正苦于以下问题:Python Choice.save方法的具体用法?Python Choice.save怎么用?Python Choice.save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类polls.models.Choice
的用法示例。
在下文中一共展示了Choice.save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: add_choice
# 需要导入模块: from polls.models import Choice [as 别名]
# 或者: from polls.models.Choice import save [as 别名]
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})
示例2: test_view_can_handle_votes_via_POST
# 需要导入模块: from polls.models import Choice [as 别名]
# 或者: from polls.models.Choice import save [as 别名]
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)
示例3: get_question
# 需要导入模块: from polls.models import Choice [as 别名]
# 或者: from polls.models.Choice import save [as 别名]
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})
示例4: test_form_renders_poll_choices_as_radio_inputs
# 需要导入模块: from polls.models import Choice [as 别名]
# 或者: from polls.models.Choice import save [as 别名]
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)
# 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())
示例5: test_create_some_choices_for_a_poll
# 需要导入模块: from polls.models import Choice [as 别名]
# 或者: from polls.models.Choice import save [as 别名]
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)
示例6: write_new
# 需要导入模块: from polls.models import Choice [as 别名]
# 或者: from polls.models.Choice import save [as 别名]
def write_new(request, methods=['POST']):
if request.POST['question'] and request.POST['choice1'] and request.POST['choice2']:
q=Question()
q.title=request.POST['question']
q.save()
c1=Choice()
c1.questions=q
c1.options=request.POST['choice1']
c1.save()
c2=Choice()
c2.questions=q
c2.options=request.POST['choice2']
c2.save()
if request.POST['choice3']:
c3=Choice()
c3.questions=q
c3.options=request.POST['choice3']
c3.save()
if request.POST['choice4']:
c4=Choice()
c4.questions=q
c4.options=request.POST['choice4']
c4.save()
if request.POST['choice5']:
c5=Choice()
c5.questions=q
c5.options=request.POST['choice5']
c5.save()
return HttpResponseRedirect('/poll/')
示例7: generate_elements
# 需要导入模块: from polls.models import Choice [as 别名]
# 或者: from polls.models.Choice import save [as 别名]
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)
示例8: test_creating_some_choices_for_a_poll
# 需要导入模块: from polls.models import Choice [as 别名]
# 或者: from polls.models.Choice import save [as 别名]
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)
示例9: test_creating_some_choices_for_a_poll
# 需要导入模块: from polls.models import Choice [as 别名]
# 或者: from polls.models.Choice import save [as 别名]
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)
示例10: vote
# 需要导入模块: from polls.models import Choice [as 别名]
# 或者: from polls.models.Choice import save [as 别名]
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})
示例11: VoteTests
# 需要导入模块: from polls.models import Choice [as 别名]
# 或者: from polls.models.Choice import save [as 别名]
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,)))
示例12: test_choice_can_calculate_its_own_percentage_of_votes
# 需要导入模块: from polls.models import Choice [as 别名]
# 或者: from polls.models.Choice import save [as 别名]
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)
示例13: test_unicode
# 需要导入模块: from polls.models import Choice [as 别名]
# 或者: from polls.models.Choice import save [as 别名]
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))
示例14: createdb
# 需要导入模块: from polls.models import Choice [as 别名]
# 或者: from polls.models.Choice import save [as 别名]
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()
示例15: handle
# 需要导入模块: from polls.models import Choice [as 别名]
# 或者: from polls.models.Choice import save [as 别名]
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')