def post(self, request, slug): answer_question = Question.objects.get(slug=slug) body = request.POST['details'] writer = UserOtherDetails.objects.get(user=request.user) date_written = date.today() time_written = timezone.now().time().strftime('%H:%M') question = answer_question answer = Answer() answer.question_string = answer_question.title answer.body = body answer.writer = writer answer.date_written = date_written answer.time_written = time_written answer.question = question answer.save() answer_question.no_of_answers += 1 answer_question.save() writer.increase_no_of_answers() writer.save() return redirect('/questions/' + question.slug)
def post(self, request, slug): answer_question = Question.objects.get(slug=slug) body = request.POST['details'] writer = UserOtherDetails.objects.get(user=request.user) question = answer_question answer = Answer() answer.question_string = answer_question.title answer.body = body.replace("'", "'") answer.writer = writer answer.question = question answer.author = writer if request.POST.get('anonymous'): answer.anonymous = True answer.save() if answer.anonymous: AnonymousAnswerWriters(answer=answer, user=request.user).save() answer_question.no_of_answers += 1 answer_question.save() writer.increase_no_of_answers() writer.save() return redirect('/questions/' + question.slug)
def create(self, request, **kwargs): puzzle = None with transaction.atomic(): puzzle = get_object_or_404(Puzzle, pk=self.kwargs["puzzle_id"]) serializer = self.get_serializer(data=request.data, context={"puzzle": puzzle}) serializer.is_valid(raise_exception=True) text = serializer.validated_data["text"] answer = Answer(text=text, puzzle=puzzle) if puzzle.hunt.answer_queue_enabled: puzzle.status = Puzzle.PENDING else: # If no answer queue, we assume that the submitted answer is the # correct answer. puzzle.status = Puzzle.SOLVED answer.status = Answer.CORRECT puzzle.answer = answer.text if puzzle.chat_room: transaction.on_commit( lambda: chat.tasks.handle_puzzle_solved.delay( puzzle.id, answer.text)) answer.save() transaction.on_commit( lambda: AnswerViewSet._maybe_update_meta_sheets_for_feeder( puzzle)) if google_api_lib.enabled() and puzzle.sheet: transaction.on_commit( lambda: google_api_lib.task.rename_sheet.delay( sheet_url=puzzle.sheet, name=f"[SOLVED] {puzzle.name}")) puzzle.save() return Response(PuzzleSerializer(puzzle).data)
def create_quiz(request): """ View for quiz creation page. if GET method, renders quiz creation page. on POST, reads all the info, user entered and saves quiz, it questions and theirs answers. Redirects to homepage if created successfully, renders same page otherwise. """ if request.method == "GET": return render(request, 'create_quiz.html') quiz_name = request.POST.get('quiz_name') q_num = 1 quiz = Quiz.create(name=quiz_name, user_id=request.user.id) while quiz and str(request.POST.get('question_' + str(q_num))) != 'None': q_text = str(request.POST.get('question_' + str(q_num))) points = int(request.POST.get('question_pts_' + str(q_num))) question = Question.create(q_text, quiz.id, points) a_num = 1 while question and str( request.POST.get(f'answer_{q_num}_{a_num}')) != 'None': answer = str(request.POST.get(f'answer_{q_num}_{a_num}')) is_correct = bool(request.POST.get(f'is_correct_{q_num}_{a_num}')) Answer.create(answer, is_correct, question.id) a_num += 1 q_num += 1 if quiz: return redirect('homepage') return redirect('create_quiz')
def q_and_a_creation(q_body, a_body): length = len(Question.objects.all()) q_new = Question(body=q_body, address=(length + 1)) a_new = Answer(body=a_body, address=(length + 1)) add_new_data_to_db_files(q_new, a_new) q_new.save() a_new.save() return [q_new.address, a_new.address]
def create_answer(interview, question, content="This is an answer", rating=None): answer = Answer(interview=interview, question=question, content=content, rating=rating) answer.save() return answer
def test_create_answer_model_with_answer(self): answer = Answer(pk=1, interview=self.interview, question=self.question, content='This is an answer') answer.save() answer_from_db = Answer.objects.get(pk=1) self.assertEqual(answer.content, answer_from_db.content, "Comparing text content") self.assertEqual(answer.interview, answer_from_db.interview, "Comparing interview object")
def test_create_answer_model_with_rating(self): answer = Answer(pk=1, interview=self.interview, question=self.question, rating=3) answer.save() answer_from_db = Answer.objects.get(pk=1) self.assertEqual(answer.rating, answer_from_db.rating, "Comparing rating content") self.assertEqual(answer.interview, answer_from_db.interview, "Comparing interview object")
def test_answer(self): answer = Answer(title='bla', content='bleee') answer.save() response = self.client.get(reverse('answer', args=[answer.id])) self.assertEqual(response.status_code, 200) self.assertEqual( response.json(), { "title": 'bla', 'answer': 'bleee', 'id': answer.id, 'categories': [], 'sources': [] })
def save_model(self, request, obj, form, change): super(TestAdmin, self).save_model(request, obj, form, change) if form.cleaned_data.get('file_field'): obj.question_set.all().delete() question_list = pasre_test_format( get_full_text( form.cleaned_data['file_field'].file ) ) for question in question_list: instance = Question.objects.create( test=obj, text=question['text'], klass=question['klass'], points_amount=question['points_amount'], ) answers = [] for answer in question['answers']: answers.append( Answer( text=answer['text'], is_true=answer['is_true'], question=instance)) Answer.objects.bulk_create(answers)
def test_get_cat_parent(self): """Check if getting categories when providing the parent works,""" self.question.save() self.other_question.save() # add a sub category - this should be ignored parent = Category(question=self.question, title='parent cat') parent.save() for cat in ['cat 1', 'cat 2', 'cat 3']: cat = Category(question=self.question, title=cat, parent=parent) cat.save() # add a category for a different question Category(question=self.other_question, title='sub cat').save() # add a random answer answer = Answer(title='asd', content='ase') answer.save() parent.answers.add(answer) response = self.client.get( reverse('category', args=[self.question.id, parent.id])) self.assertEqual(response.status_code, 200) self.assertEqual( response.json(), { 'question': 1, 'parent': parent.parent_id, 'title': 'parent cat', 'answers': [{ 'id': 1, 'title': 'asd' }], 'categories': [{ 'id': 2, 'title': 'cat 1' }, { 'id': 3, 'title': 'cat 2' }, { 'id': 4, 'title': 'cat 3' }] })
def test_get_cat_no_parent(self): """Check if getting categories without providing the parent works,""" self.question.save() self.other_question.save() for cat in ['cat 1', 'cat 2', 'cat 3']: cat = Category(question=self.question, title=cat) cat.save() # add a sub category - this should be ignored Category(question=self.question, title='sub cat', parent=cat).save() # add a category for a different question Category(question=self.other_question, title='sub cat').save() answer = Answer(title='asd', content='ase') answer.save() response = self.client.get( reverse('categories', args=[self.question.id])) self.assertEqual(response.status_code, 200) self.assertEqual( response.json(), { 'question': 1, 'parent': None, 'title': self.question.content, 'answers': [], 'categories': [{ 'id': 1, 'title': 'cat 1' }, { 'id': 2, 'title': 'cat 2' }, { 'id': 3, 'title': 'cat 3' }] })
def create(self, request, **kwargs): puzzle = None with transaction.atomic(): puzzle = get_object_or_404(Puzzle, pk=self.kwargs["puzzle_id"]) serializer = self.get_serializer( data=request.data, context={"puzzle": puzzle} ) serializer.is_valid(raise_exception=True) text = serializer.validated_data["text"] answer = Answer(text=text, puzzle=puzzle) if puzzle.hunt.answer_queue_enabled: puzzle.status = Puzzle.PENDING else: # If no answer queue, we assume that the submitted answer is the # correct answer. puzzle.status = Puzzle.SOLVED answer.status = Answer.CORRECT puzzle.answer = answer.text if puzzle.chat_room: transaction.on_commit( lambda: chat.tasks.handle_puzzle_solved.delay( puzzle.id, answer.text ) ) transaction.on_commit( lambda: chat.tasks.cleanup_puzzle_channels.apply_async( args=(puzzle.id,), countdown=1800 # clean up in 30 minutes ) ) answer.save() transaction.on_commit( lambda: AnswerViewSet._maybe_update_meta_sheets_for_feeder(puzzle) ) transaction.on_commit( lambda: AnswerViewSet._maybe_update_sheets_title(puzzle) ) puzzle.save() return Response(PuzzleSerializer(puzzle).data)
def test_source(self): """Check if sources get returned correctly.""" answer = Answer(title='bla', content='bleee') answer.save() for i in range(3): s = Source(name='source %s' % i, url='http://bla.%s.com' % i) s.save() answer.sources.add(s) response = self.client.get(reverse('answer', args=[answer.id])) self.assertEqual(response.status_code, 200) self.assertEqual( response.json(), { "title": 'bla', 'answer': 'bleee', 'id': answer.id, 'categories': [], 'sources': [ { 'id': 1, 'name': 'source 0', 'url': 'http://bla.0.com' }, { 'id': 2, 'name': 'source 1', 'url': 'http://bla.1.com' }, { 'id': 3, 'name': 'source 2', 'url': 'http://bla.2.com' }, ] })
def answer(request, activity_id, answer_id=None, template="admin/trans_answer_edit.html"): is_new = False ok = verify(request) if ok != None: return ok try: activity = PlayerActivity.objects.untranslated().get(pk=int(activity_id)) except PlayerActivity.DoesNotExist: raise Http404 ("PlayerActivity with id %s does not exist" % activity_id) if (request.POST.has_key("submit_btn") and request.POST["submit_btn"] == "Cancel"): return HttpResponseRedirect(reverse("admin:manage-answers", args=[activity_id])) if answer_id is not None and answer_id != 'None': answer = get_object_or_404(Answer, pk=int(answer_id)) else: answer = Answer(activity=activity) is_new = True errors = {} form = AnswerForm(instance=answer, data=request.POST or None) if request.method == "POST": if form.is_valid(): try: answer = form.save(commit=False) answer.activity = activity answer.save() return HttpResponseRedirect(reverse("admin:manage-answers", args=[activity_id])) except Exception, err: #transaction.rollback() print "error while saving answer: %s" % str(err) log.error("error while saving answer: %s" % str(err)) errors.update({"Updating mission": "Server error took place. Please contact the admin."}) else: if form.errors: errors.update(form.errors)
def test_categories(self): """Check if categories get returned correctly.""" answer = Answer(title='bla', content='bleee') answer.save() question = Question(content='asd') question.save() for i in range(3): c = Category(title='cat %s' % i, question=question) c.save() answer.categories.add(c) response = self.client.get(reverse('answer', args=[answer.id])) self.assertEqual(response.status_code, 200) self.assertEqual( response.json(), { "title": 'bla', 'answer': 'bleee', 'id': answer.id, 'sources': [], 'categories': [ { 'id': 1, 'title': 'cat 0' }, { 'id': 2, 'title': 'cat 1' }, { 'id': 3, 'title': 'cat 2' }, ] })
def setUp(self): self.user = User.objects.create(username='******', password='******') test = Test.objects.create(title='ТЕСТ', slug='test', description='empty', estimate_method=Test.ESTIMATE_METHODS[0][0]) for idx in range(20): question = Question.objects.create(test=test, text='Вопрос %s' % idx) answers = [] for a_idx in range(4): answers.append( Answer(text='Ответ %s' % a_idx, is_true=random() > 0.5, question=question)) Answer.objects.bulk_create(answers)
def calculate_score(request, questions): """ Function to calculate score for a quiz. Returns rounded value for better view. """ quiz_score = 0 for question in questions: user_answers = [{ f"{answer.id}": bool(request.POST.get(f"checkbox_answer_{answer.id}")) } for answer in question.answers] question_result = 0 for answer in user_answers: question_result += Answer.is_correct_answer(answer) quiz_score += question_result / len(question.answers) * question.points return round(quiz_score, 2)
def set_answers(self, user, answers): if self.has_passed_by(user) is True: raise ValidationError('the same user can`t answer on quiz twice') accepted_question_ids = sorted( [answer['question'] for answer in answers]) question_ids = sorted( [question.id for question in self.get_questions()]) if accepted_question_ids != question_ids: raise ValidationError( 'passed invalid question_id or not all the answers to the questions sent' ) for answer in answers: if QuestionChoice.objects.filter( question_id=answer['question'], id=answer['choice']).exists() is False: raise ValidationError('passed invalid choice_id') Answer.objects.bulk_create([ Answer(user=user, question_id=answer['question'], choice_id=answer['choice']) for answer in answers ])
def test_create_answer_with_invalid_rating(self): answer = Answer(pk=1, interview=self.interview, question=self.question, rating=1000) self.assertRaises(ValidationError, answer.full_clean)
def handle(self, *args, **options): Answer.fetch_data()
def add_answers(): for i in range(len(set_answers())): a_1 = Answer(body=set_answers()[i]['body'], address=set_answers()[i]['address']) a_1.save()
def handle(self, *args, **options): tzone = timezone.get_current_timezone() if not options['o'] or (options['o'] and 'user' in options['o']): # 生成用户数据 print('正在生成用户数据...') for i in range(50): User.objects.create_user(username=('test' + str(i)), nickname=fake.name(), password='******', email=fake.free_email(), sex=random.choice(['F', 'M']), intro=fake.sentence(), work=fake.company()) print('用户数据生成完成!') if not options['o'] or (options['o'] and 'relationship' in options['o']): # 生成关注关系 print('正在生成用户关系...') user_count = User.objects.count() for i in range(user_count): try: u = User.objects.get(id=i) except User.DoesNotExist: continue follow_limit = random.randint(5, 10) for _ in range(follow_limit): u.follow(random.randint(1, user_count)) print('用户关系生成完成!') if not options['o'] or (options['o'] and 'ask' in options['o']): # 生成问题 print('正在生成问题...') user_count = User.objects.count() topic_list = [ '互联网', 'Python', '编程', '游戏', '金融', '信息', '健身', 'NBA', '深圳市', '科技', '芯片', '电脑', '电影', '音乐', '法律', '大学', '中国' ] for i in range(user_count): try: u = User.objects.get(id=i) except User.DoesNotExist: continue ask_limit = random.randint(1, 10) for _ in range(ask_limit): topics = random.sample(topic_list, random.randint(1, 3)) ask = Ask.objects.create( title=fake.sentence(), content=fake.text(), author=u, create_time=fake.past_datetime(start_date="-2y", tzinfo=tzone), ) ask.add_topics(topics) print('问题生成完成!') if not options['o'] or (options['o'] and 'answer' in options['o']): # 生成答案 print('正在生成答案...') user_count = User.objects.count() ask_count = Ask.objects.count() answer_list = [] for i in range(user_count): try: u = User.objects.get(id=i) except User.DoesNotExist: continue ask_limit = random.randint(5, 30) for _ in range(ask_limit): content = fake.text(max_nb_chars=1000) ask = Ask.objects.get(id=random.randint(1, ask_count)) answer_list.append( Answer( author=u, content_text=content, content=content, ask=ask, create_time=fake.past_datetime(start_date="-2y", tzinfo=tzone), )) Answer.objects.bulk_create(answer_list) answer_list = [] print('答案生成完成!') if not options['o'] or (options['o'] and 'comment' in options['o']): # 生成评论 print('正在生成评论...') user_count = User.objects.count() answer_count = Answer.objects.count() comment_list = [] for i in range(user_count): try: u = User.objects.get(id=i) except User.DoesNotExist: continue answer_limit = 100 for _ in range(answer_limit): try: answer = Answer.objects.get( id=random.randint(1, answer_count)) except Answer.DoesNotExist: continue comment_list.append( Comment( content=fake.sentence(), author=u, answer=answer, create_time=fake.past_datetime(start_date="-2y", tzinfo=tzone), )) Comment.objects.bulk_create(comment_list) comment_list = [] print('评论生成完成!') if not options['o'] or (options['o'] and 'vote' in options['o']): # 生成点赞数据 print('正在点赞...') user_count = User.objects.count() answer_count = Answer.objects.count() answer_limit = 200 vote_list = [] for i in range(user_count): try: u = User.objects.get(id=i) except User.DoesNotExist: continue answer_list = random.sample(range(answer_count), answer_limit) for answer_id in answer_list: try: answer = Answer.objects.get(id=answer_id) except Answer.DoesNotExist: continue # u.voteup(answer) if u.is_voted(answer) is False: vote_list.append(answer) answer.voteup() u.vote_answers.add(*vote_list) vote_list = [] print('点赞完成!') if not options['o'] or (options['o'] and 'collection' in options['o']): # 生成点赞数据 print('正在收藏...') user_count = User.objects.count() answer_count = Answer.objects.count() collection_list = [] for i in range(user_count): try: u = User.objects.get(id=i) except User.DoesNotExist: continue answer_list = random.sample(range(answer_count), random.randint(5, 30)) for answer_id in answer_list: try: answer = Answer.objects.get(id=answer_id) except Answer.DoesNotExist: continue if u.is_collected(answer) is False: collection_list.append(answer) u.collections.add(*collection_list) collection_list = [] print('收藏完成!')