class QuestionModelTest(TestCase): def setUp(self): self.q1 = Question() self.q1.question_text = "What is your question?" self.q1.pub_date = timezone.now() self.q1.save() self.q2 = Question() self.q2.question_text = "What is your next question?" self.q2.pub_date = timezone.now() self.q2.save() def tearDown(self): pass def test_save_and_retrieve_Question(self): saved_items = Question.objects.all() self.assertEqual(saved_items.count(), 2) self.assertEqual(saved_items[0].question_text, self.q1.question_text) self.assertEqual(saved_items[1].question_text, self.q2.question_text) def test_save_and_retrieve_Choice(self): self.q1.choice_set.create(choice_text = 'Choice 1', votes=0) self.q1.choice_set.create(choice_text = "Choice 2", votes=1) saved_items = Choice.objects.all() self.assertEqual(saved_items.count(), 2) self.assertEqual(saved_items[0].choice_text, "Choice 1") self.assertEqual(saved_items[1].choice_text, "Choice 2")
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/')
def save_m2m_data(data): test_dict = {} quest_dict = {} answer_dict = {} for key, value in data.items(): if 'token' in key: continue if 'test' in key: test_dict[key] = value else: key, num_key = key.split('_') if num_key not in quest_dict: quest_dict[num_key] = {} quest_dict[num_key][key] = value test = Test(title=test_dict['test_title'], description=test_dict['test_description']) test.save() for i in quest_dict: d = quest_dict[i] question = Question(title=d['question']) question.save() question.answer.create(title=d['correctanswer'], is_true=True) question.answer.create(title=d['answer-a']) question.answer.create(title=d['answer-b']) question.answer.create(title=d['answer-c']) test.question.add(question)
def test_form_renders_poll_choices_as_radio_inputs(self): # set up a poll with a couple of choices poll1 = Question(question_text='6 times 7', pub_date=timezone.now()) poll1.save() choice1 = Choice(question=poll1, choice_text='42', votes=0) choice1.save() choice2 = Choice(question=poll1, choice_text='The Ultimate Answer', votes=0) choice2.save() # set up another poll to make sure we only see the right choices poll2 = Question(question_text='time', pub_date=timezone.now()) poll2.save() choice3 = Choice(question=poll2, choice_text='PM', votes=0) choice3.save() # build a voting form for poll1 form = QuestionVoteForm(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_text), (choice2.id, choice2.choice_text), ]) # check it uses radio inputs to render self.assertIn('type="radio"', form.as_p())
def add_question(request): if 'Submit' in request.POST: new_question_title = request.POST['question_title'] new_question_text = request.POST['question_text'] new_question = Question(question_text=new_question_text, pub_date=timezone.now(), author=request.user, modification_time=timezone.now(), question_title=new_question_title) tag_string = request.POST['tags'] tags = tag_string.split(',') new_question.save() for new_tag in tags: new_tag_object = Tags(tag=new_tag) #new_tag_object.save() if Tags.objects.filter(tag=new_tag): new_question.tags.add(Tags.objects.get(tag=new_tag)) else: #print "not exists" #print Tags.objects.get(tag=new_tag) # print Tags.objects.get(tag=new_tag) # new_tag_object = Tags.objects.get(tag=new_tag) # print "get successfully" # new_question.tags.add(new_tag_object) # print "add successfully" new_tag_object.save() new_question.tags.add(new_tag_object) print "out of for" new_question.save() #print new_question.tags.all() return HttpResponseRedirect(reverse('polls:index')) elif 'Cancel' in request.POST: return HttpResponseRedirect(reverse('polls:ask')) else: return HttpResponse("Submit new question error")
def setUp(self): q = Question(question_text="What's new?", pub_date=timezone.now()) q.save() q.choice_set.create(choice_text='choice_text', votes=0) q.save() # self.browser = webdriver.Safari() self.browser = webdriver.Firefox()
def task_number_one(): print('gygomd') q_text = "Is the time {}{}".format(datetime.now(), '?') q = Question(question_text=q_text, pub_date=timezone.now()) q.save() print(q_text) print("The question has been saved.")
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 randomQuestionGenerator(users, tags): user = User.objects.get(id=random.randint(1, users - 1)) filename = "/home/nikita/web/ask_chizhikov/polls/management/commands/" + "q" + str( random.randint(1, 5)) + ".txt" f = open(filename, 'r') title = "" text = "" help = 0 for line in f: if line == "\n": help = 1 if help == 0: title += line else: text += line added_at = parse_datetime("2012-02-21 10:28:45") ##### q = Question(author=user, text=text, title=title, rating=random.randint(0, 50), added_at=added_at, answers=random.randint(0, 1000)) q.save() for i in range(0, 5): random_tag_id = random.randint(1, tags - 1) q.tag.add(Tag.objects.get(id=random_tag_id)) q.save()
def index(request): question_list = Question.objects.all() question_count = question_list.count() if request.method == 'GET': form = Myform() context = { "questions": question_list, "question_count": question_count, "form": form } return render(request, "polls/index.html", context) elif request.method == 'POST': form = Myform(request.POST) if form.is_valid(): question_text = form.cleaned_data['question_name'] q = Question(question_text=question_text, pub_date=timezone.now()) q.save() messages.add_message(request, messages.SUCCESS, "You have successfully added a poll") return redirect(request, "polls:index") #return render(request, "polls/ok.html") else: messages.add_message(request, messages.WARNING, "There was an error in your form") context = { "questions": question_list, "question_count": question_count, "form": form } return render(request, "polls/index.html", context) else: return render(request, "polls/oops.html")
def randomQuestionGenerator(users, tags): user = User.objects.get(id=random.randint(1, users - 1)) filename = "/home/nikita/web/ask_chizhikov/polls/management/commands/" + "q" + str(random.randint(1, 5)) + ".txt" f = open(filename, 'r') title = "" text = "" help = 0 for line in f: if line == "\n": help = 1 if help == 0: title += line else: text += line added_at = parse_datetime("2012-02-21 10:28:45") ##### q = Question(author=user, text=text, title=title, rating=random.randint(0, 50), added_at=added_at, answers=random.randint(0, 1000)) q.save() for i in range(0, 5): random_tag_id = random.randint(1, tags-1) q.tag.add(Tag.objects.get(id=random_tag_id)) q.save()
def test_root_url_shows_links_to_all_polls(self): # set up some polls poll1 = Question(question_text='6 times 7', pub_date=timezone.now()) poll1.save() poll2 = Question(question_text='life, the universe and everything', pub_date=timezone.now()) poll2.save() response = self.client.get('/polls/') # check we've used the right template self.assertTemplateUsed(response, 'polls/index.html') # check we've passed the polls to the template polls_in_context = response.context['latest_question_list'] #As it orders by the most recent first, change the order to test -> poll2, poll1 self.assertEquals(list(polls_in_context), [poll2, poll1]) # check the poll names appear on the page self.assertIn(poll1.question_text, response.content) self.assertIn(poll2.question_text, response.content) # check the page also contains the urls to individual polls pages poll1_url = reverse('polls:detail', args=[poll1.id,]) self.assertIn(poll1_url, response.content) poll2_url = reverse('polls:detail', args=[poll2.id,]) self.assertIn(poll2_url, response.content)
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 test_view_can_handle_votes_via_POST(self): # set up a poll with choices poll1 = Question(question_text='6 times 7', pub_date=timezone.now()) poll1.save() choice1 = Choice(question=poll1, choice_text='42', votes=1) choice1.save() choice2 = Choice(question=poll1, choice_text='The Ultimate Answer', votes=3) choice2.save() # set up our POST data - keys and values are strings post_data = {'choice': str(choice2.id)} # make our request to the view poll_url = '/polls/%d/vote/' % (poll1.id,) response = self.client.post(poll_url, data=post_data) #URL to redirect redirect_url = '/polls/%d/results/' % (poll1.id,) # 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, redirect_url)
def create_question(request): """ Create Question """ if request.method == 'POST': form = CreateQuestionForm(request.POST) if form.is_valid(): data = form.cleaned_data # Get Question Text (Required) question_text = data.get('question_text') # Create a empty list to group the choice text choices = [] for k, v in data.iteritems(): if k != 'question_text' and v != '': choices.append(v) # Instance and save a Question question = Question(question_text=question_text) question.save() # Create choices for question for choice_text in choices: question.choice_set.create(choice_text=choice_text) return HttpResponseRedirect(reverse('polls:index')) else: form = CreateQuestionForm() context = {'form': form} return render(request, 'polls/create.html', context)
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'))
def insert_question(text): q = Question(question_text=text, pub_date=timezone.now()) q.save() bind_choice(q.id, ['Not much', 'The sky', 'Just hacking again']) print '{0} insert question {1}: {2} into DB.'.format( q.pub_date, q.id, q.question_text)
def test_new_poll(self): #creating a poll object poll = Question() poll.question_text = "Shall we begin?" poll.pub_date = timezone.now() poll.save() self.assertEquals(poll.question_text, "Shall we begin?")
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 test_str(self): question = Question() question.question_text = "What's new?" question.pub_date = timezone.now() question.save() saved_item = Question.objects.all().first() self.assertEqual(saved_item.__str__(), "What's new?")
def enter_question(request): if request.method == 'POST': question_text = request.POST['question_text'] q = Question(question_text=question_text, pub_date=datetime.utcnow()) q.save() all_questions = Question.objects.all() return render(request, 'question.html', context={'questions': all_questions})
def test_index_shows_current_poll(self): date = timezone.now() poll = Question(question_text="Is this the present?", pub_date=date) poll.save() response = self.client.get( reverse('polls:index')) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, template_name='polls/index.html') # in my code, the list of questions is assigned to context variable 'questions' self.assertIn( poll, response.context['questions'] )
def test_add_question(): """ Test if we can add a question to the database safely """ pub_date = timezone.now() question = Question(question_text="Test question", pub_date=pub_date) question.save() assert question.question_text == "Test question" assert question.pub_date == pub_date
def test_was_published_recently_with_future_question(self): """ was_published_recently() возвращает False для вопроса, который имеет pub_date - будущее время """ time = timezone.now() + timezone.timedelta(days=30) future_question = Question(question_text='Абаракадабра?', pub_date=time) future_question.save() self.assertIs(future_question.was_published_recently(), False)
def test_was_published_recentlyd_true(self): first_question = Question() first_question.question_text = "have to be True" first_question.pub_date = timezone.now() first_question.save() saved_item = Question.objects.all().first() self.assertTrue(saved_item.was_published_recently())
def questions(request): from polls.models import Question from datetime import datetime q = Question(question_text='How do you fel today?', pub_date=datetime.now()) q.save() questions = Question.objects.all() return render(request, 'questions.html', context={'questions': questions})
def test_total_votes_poll(self): #creating a poll object p = Question(question_text='Can I vote?', pub_date=timezone.now()) p.save() self.assertEquals(p.total_votes(), 0) #searching in database all_polls_in_database = Question.objects.all() self.assertEquals(all_polls_in_database.count(), 1)
def test_create_choice(self): q = Question(question_text="What day is it?", pub_date=timezone.now()) q.save() c1 = Choice(choice_text="Monday", question=q) c2 = Choice(choice_text="Tuesday", question=q) c3 = Choice(choice_text="Sunday", question=q) c1.save() c2.save() c3.save() self.assertEqual(3, len(q.choice_set.all()))
def test_was_published_recentlyd_false(self): question = Question() question.question_text = "have to be False" question.pub_date = datetime.datetime(2015, 1, 1, 12, 30, 59, 0, timezone.utc) question.save() saved_item = Question.objects.all().first() self.assertFalse(saved_item.was_published_recently())
def index(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 = InputForm(request.POST) # check whether it's valid: if form.is_valid(): location = form.cleaned_data['location'] fromdate = form.cleaned_data['fromdate'] todate = form.cleaned_data['todate'] if (location == '1'): madrigalUrl = 'http://isr.sri.com/madrigal' else: madrigalUrl = 'http://madrigal.haystack.mit.edu/madrigal' user_fullname = 'Ashaki Gumbs' user_email = '*****@*****.**' user_affiliation = 'Boston University' testData = madrigalWeb.MadrigalData(madrigalUrl) expList = testData.getExperiments(61, fromdate.year, fromdate.month, fromdate.day, 0, 0, 0, todate.year, todate.month, todate.day, 0, 0, 0, local=1) # newcgiurl = madrigalWeb.MadrigalData(madrigalUrl) # expList = newcgiurl.getExperiments(61, fromdate.year,fromdate.month,fromdate.day,0,0,0, # todate.year,todate.month,todate.day,0,0,0, local=1) Question.objects.all().delete() for i in range(len(expList)): q = Question(pub_date=timezone.now(), madrigalUrl=expList[i].madrigalUrl, name=expList[i].name, realUrl=expList[i].realUrl, url=expList[i].url, madid=expList[i].id) q.save() # process the data in form.cleaned_data as required # ... # redirect to a new URL: return HttpResponseRedirect('/polls/listexp/') # if a GET (or any other method) we'll create a blank form else: form = InputForm() return render(request, 'polls/inputinfo.html', {'form': form})
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 save(self, owner, options): data = self.cleaned_data time = timezone.now() q = Question(question_text=data['question_text'], pub_date=time, owner=owner) q.save() for i in range(len(options)): Options.objects.create(question=q, option_text=options[i]['option_text'], votes=0) return q
def index(request): q = get_object_or_404(Question, id=1) try: q = Question.objects.get(id=2) except Question.DoesNotExist: q = Question() q.question_text = "" q.save() return HttpResponse("Hello, world. New Resposne ")
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(): # process the data in form.cleaned_data as required new_question = Question() new_question.body = Gymkhana_body.objects.get( nameofbody=form.cleaned_data['body']) new_question.question_text = form.cleaned_data['question'] new_question.pub_date = timezone.now() new_question.save() choice1 = Choice() choice1.question = new_question choice1.choice_text = form.cleaned_data['choice1'] choice1.votes = 0 choice1.save() if form.cleaned_data['choice2']: choice2 = Choice() choice2.question = new_question choice2.choice_text = form.cleaned_data['choice2'] choice2.votes = 0 choice2.save() if form.cleaned_data['choice3']: choice3 = Choice() choice3.question = new_question choice3.choice_text = form.cleaned_data['choice3'] choice3.votes = 0 choice3.save() if form.cleaned_data['choice4']: choice4 = Choice() choice4.question = new_question choice4.choice_text = form.cleaned_data['choice4'] choice4.votes = 0 choice4.save() # redirect to a new URL: messages.add_message(request, messages.SUCCESS, 'Thanks for your suggestion!') return HttpResponseRedirect('/') # if a GET (or any other method) we'll create a blank form else: form = QuestionForm() return render(request, 'organisation/addquestion.html', {'form': form})
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 create_poll(request): if not request.POST: raise Http404 else: if request.POST['question_text']: q = Question(question_text=request.POST['question_text'], pub_date=timezone.now()) q.save() return HttpResponseRedirect(reverse('polls:create_choices', args=(q.id,))) else: return render(request, 'polls/index.html', { 'error_message': 'The question cannot be empty.', })
def test_index_excludes_future_poll(self): """A poll with future pub_date should not be included in the index""" date = timezone.now() poll = Question(question_text="Is this the present?", pub_date=date) poll.save() date = timezone.now() + datetime.timedelta(minutes=2) future_poll = Question(question_text="Is this the future?", pub_date=date) future_poll.save() response = self.client.get(reverse('polls:index')) self.assertEquals(response.status_code, 200) # in my code, the list of questions is assigned to context variable 'questions' self.assertIn( poll, response.context['questions'] ) self.assertNotIn( future_poll, response.context['questions'] )
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_question_has_chice(self): question = Question() question.question_text = "has choice" question.pub_date = timezone.now() question.save() question.choice_set.create(choice_text='Not much', votes=0) question.choice_set.create(choice_text='The sky', votes=0) saved_item = Question.objects.get(pk=1) self.assertEqual(saved_item.choice_set.count(), 2) self.assertEqual(saved_item.choice_set.first().choice_text, 'Not much')
def make_metal_poll(bandname,opinions): pub = timezone.now() marks = '?' * random.randint(1,5) question = bandname + marks chosen = random.sample(opinions,5) choices = list() for c in chosen: votes = random.randint(1,1000) choices.append(Choice(choice_text=c,votes=votes)) p = Question(question_text=question,pub_date=pub) p.save() p.choice_set=choices return p
def test_query_question(self): q = Question(question_text="question_text_005_001") q.save() q = Question(question_text="question_text_005_002") q.save() query = "question_text=question_text_005_001" url = reverse("polls:question-list") url = "{0}?{1}".format(url, query) response = self.client.get(url, **self.auth_headers) _j = json.loads(response.content) self.assertEqual(1, len(_j)) self.assertEqual("question_text_005_001", _j[0]["question_text"])
def test_create_choice(self): q = Question(question_text="question_text_007") q.save() q2 = Question(question_text="question_text_008") q2.save() url = reverse("polls:choice-list") data = {"choice_text": "choice_text_001", "question": q2.id} response = self.client.post(url, data, **self.auth_headers) self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content) self.assertEqual(q2.id, json.loads(response.content)["question"])
def add(request): question = request.POST.get('question') choice1 = request.POST.get('choice1') choice2 = request.POST.get('choice2') q = Question(question_text=question, pub_date=timezone.now()) q.save() c = Choice(question=q, choice_text=choice1) c.save() c = Choice(question=q, choice_text=choice2) c.save() return HttpResponseRedirect(reverse('polls:index'))
def create(self, request): '''creates question object and assosiates it with the user''' serializer = self.serializer_class(data=request.data) if serializer.is_valid(): print serializer.validated_data ques = Question(pub_date=datetime.datetime.now(), **serializer.validated_data) ques.createdby = request.user ques.save() response = self.serializer_class(ques) return Response(response.data, status=status.HTTP_200_OK) else: return Response({'error':'Invalid data'}, status=status.HTTP_400_BAD_REQUEST)
def test_view_shows_percentage_of_votes(self): # set up a poll with choices poll1 = Question(question_text='6 times 7', pub_date=timezone.now()) poll1.save() choice1 = Choice(question=poll1, choice_text='42', votes=1) choice1.save() choice2 = Choice(question=poll1, choice_text='The Ultimate Answer', votes=2) choice2.save() response = self.client.get('/polls/%d/results/' % (poll1.id, )) # check the percentages of votes are shown, sensibly rounded self.assertIn('33 %: 42', response.content) self.assertIn('67 %: The Ultimate Answer', response.content)
def test_query_none_question(self): q = Question(question_text="question_text_008_001") q.save() q = Question( question_text="question_text_008_002", pub_date=Utils.parse_datetime("2018-11-14 10:00:00")) q.save() query = "pub_date= to 2018-11-13 00:00:00" url = reverse("polls:question-list") url = "{0}?{1}".format(url, query) response = self.client.get(url, **self.auth_headers) _j = json.loads(response.content) self.assertEqual(0, len(_j), response.content)
def test_page_shows_poll_title_and_no_votes_message(self): # set up two polls, to check the right one is displayed poll1 = Question(question_text='6 times 7', pub_date=timezone.now()) poll1.save() poll2 = Question(question_text='life, the universe and everything', pub_date=timezone.now()) poll2.save() response = self.client.get('/polls/%d/' % (poll2.id, )) # check we've used the poll template self.assertTemplateUsed(response, 'polls/detail.html') # check we've passed the right poll into the context self.assertEquals(response.context['question'], poll2) # check the poll's question appears on the page self.assertIn(poll2.question_text, response.content)
def post(request): if request.method == 'POST': question_form = QuestionForm(request.POST) choice_form = ChoicesForm(request.POST) if all([question_form.is_valid(), choice_form.is_valid()]): question = Question( question_text=question_form.cleaned_data['question_text'], pub_date=timezone.now()) question.save() choices = request.POST.getlist('choices_text') for choice in choices: question.choices_set.create( choices_text=choice, votes=0) return HttpResponse("saved") else: return HttpResponse('f**k')
def handle(self, *args, **options): for dossier, sous_dossiers, fichiers in os.walk('/neuro/users/chris/data'): for fichier in fichiers: fullpath = os.path.join(dossier, fichier) print(fullpath) try: ds = pydicom.read_file(fullpath) print(ds.PatientName) try: print(ds.SeriesDescription) b = Question(question_text=description) b.save() #description = ds.SeriesDescription #Question.get(question_text=description) #Question.save() #question_text=description #print (question_text) #Question.question_text= 'how are you today' #Question.save() #database_connexion = sqlite.connect('polls.sqlite') #cursor = database_connexion.cursor() #cursor.execute("insert into Question values (null,?,?)", (question_text)) #database_connexion.commit() #cursor.close() #q=Question(question_text="description") #q=save() #c.execute("test", (description)) #c.close() except NameError: print('not possible to know this information') try: print(ds.SeriesNumber) except NameError: print('not possible to know this information') except pydicom.errors.InvalidDicomError: print('not possible to know this information')
def test_choice_can_calculate_its_own_percentage_of_votes(self): poll = Question(question_text='who?', pub_date=timezone.now()) poll.save() choice1 = Choice(question=poll,choice_text='me',votes=2) choice1.save() choice2 = Choice(question=poll,choice_text='you',votes=1) choice2.save() self.assertEquals(choice1.percentage(), 100 * 2 / 3.0) self.assertEquals(choice2.percentage(), 100 * 1 / 3.0) # also check 0-votes case choice1.votes = 0 choice1.save() choice2.votes = 0 choice2.save() self.assertEquals(choice1.percentage(), 0) self.assertEquals(choice2.percentage(), 0)
def test_view_shows_total_votes(self): # set up a poll with choices poll1 = Question(question_text='6 times 7', pub_date=timezone.now()) poll1.save() choice1 = Choice(question=poll1, choice_text='42', votes=1) choice1.save() choice2 = Choice(question=poll1, choice_text='The Ultimate Answer', votes=2) choice2.save() response = self.client.get('/polls/%d/results/' % (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('/polls/%d/results/' % (poll1.id, )) self.assertIn('1 vote', response.content) self.assertNotIn('1 votes', response.content)
def test_diferent_number_of_votes_in_question_and_choice(self): #creating a poll object p = Question(question_text='How are you?', pub_date=timezone.now()) p.save() #creating first choice c1 = Choice(question=p, choice_text='Fine', votes=2) c1.save() #creating second choice c2 = Choice(question=p, choice_text='Cool', votes=4) c2.save() #correct number of choices in question number_of_votes = p.total_votes() self.assertEquals(number_of_votes, 6)
def test_page_shows_choices_using_form(self): # set up a poll with choices poll1 = Question(question_text='time', pub_date=timezone.now()) poll1.save() choice1 = Choice(question=poll1, choice_text="PM", votes=0) choice1.save() choice2 = Choice(question=poll1, choice_text="Gardener's", votes=0) choice2.save() response = self.client.get('/polls/%d/' % (poll1.id, )) # check we've passed in a form of the right type #Not in the Django official tutorial #self.assertTrue(isinstance(response.context['form'], QuestionVoteForm)) # and check the form is being used in the template, # by checking for the choice text self.assertIn(choice1.choice_text, response.content.replace(''', "'")) self.assertIn(choice2.choice_text, response.content.replace(''', "'"))
class TestPollQuestion(TestCase): def setUp(self): pub_date = datetime.now(tz=tz) - timedelta(days=5) self.instance = Question(question_text="What is your favourite beach?", pub_date=pub_date) self.instance.save() def test_new_question(self): pub_date = datetime.now(tz=tz) new = Question.objects.create(question_text="What?", pub_date=pub_date) assert(new.question_text == 'What?') def test_question_count(self): self.assertEqual(len(Question.objects.all()), 1) def test_pubdate_is_past(self): self.assertTrue(self.instance.pub_date < datetime.now(tz=tz))
def add_question(request): data = { 'msg': 'hello api!!!', 'status': 'ok', } request_dict = request.GET question_text = request_dict.get('question_text') if question_text: question = Question( question_text=question_text, pub_date=datetime.datetime.now()) question.save() msg = '存储了 %s' % (question) else: msg = 'question_text 参数没有传入数据' data['status'] = 'error' data['msg'] = msg return JsonResponse(data)
def test_saving_and_retrieving_questions(self): tz = timezone.get_default_timezone() question = Question() question.question_text = 'Who is the most famous actress?' question.pub_date = datetime.datetime( 2012, 3, 31, 11, 30, 5, 182371, tzinfo=tz ) question.save() saved_questions = Question.objects.all() self.assertEqual(saved_questions.count(), 1) saved_question = saved_questions[0] self.assertIn('Who is the most famous actress?', repr(saved_question), ) self.assertEqual(saved_question.question_text, 'Who is the most famous actress?') self.assertEqual(saved_question.pub_date, datetime.datetime(2012, 3, 31, 11, 30, 5, 182371, tzinfo=tz)) self.assertFalse(saved_question.was_published_recently())
from polls.models import Question, Choice # Import the model classes we just wrote. # No questions are in the system yet. Question.objects.all() # Create a new Question. # Support for time zones is enabled in the default settings file, so # Django expects a datetime with tzinfo for pub_date. Use timezone.now() # instead of datetime.datetime.now() and it will do the right thing. from django.utils import timezone q = Question(question_text="What's new?", pub_date=timezone.now()) # Save the object into the database. You have to call save() explicitly. q.save() # Now it has an ID. Note that this might say "1L" instead of "1", depending # on which database you're using. That's no biggie; it just means your # database backend prefers to return integers as Python long integer # objects. print(q.id) # Access model field values via Python attributes. print(q.question_text) print(q.pub_date) # Change values by changing the attributes, then calling save(). q.question_text = "What's up?"