def admin_answer(key,question_id): sql = mysql() datakey = sql.select('keyword') length = len(datakey) all = 0 for i in range(length): if all > 10: break num = 0 for j in range(5): if datakey[i][j+3] in key: num += 1 if num > 2: all += 1 #content = datakey[i][1]+": "+datakey[i][2] content = '<span>'+datakey[i][1]+'<a href="'+ datakey[i][2]+'" target="_blank">点击查看</a></span>' answer = Answer(content=content) user = User.query.filter(User.isAdmin == 1).first() print user if user: answer.author = user question = Question.query.filter(Question.id == question_id).first() answer.question = question db.session.add(answer) db.session.commit()
def receive_ans_ajax(request, round_number): if request.is_ajax() and request.method == 'POST': json_data = json.loads(request.readline()) player = request.user.player room_query = GameRoom.objects.filter(players__id=player.id) room = room_query[0] round_query = GameRound.objects.filter(room__id=room.id) cur_round = round_query.filter(round_number=round_number)[0] for key in json_data: value = json_data[key] field_query = Field.objects.filter(short_name=key) field = field_query[0] if len(value) >0: valid = value[0].lower() == cur_round.cur_letter.lower() else: valid = False ans = Answer(roundd=cur_round, player=player, field=field, ans=value, valid=valid,points= 10 if valid else 0 ) ans.save() return HttpResponse("OK") else: if not request.is_ajax(): return HttpResponse('Only ajax is allowed') elif not request.method == 'POST': return HttpResponse(request.method + ' is not allowed') else: return HttpResponse('unknown error')
def save(self): self.cleaned_data['author'] = self._user self.cleaned_data['question'] = Question.objects.get( id=self.cleaned_data['question']) answer = Answer(**self.cleaned_data) answer.save() return answer
def manage_questions(): form = AddQuestionForm() import_form = ImportQuestionsForm() if form.validate_on_submit(): q = Question(title=form.question.data, text=form.caption.data, points=form.points.data, number=form.number.data) db.session.add(q) db.session.commit() for answer in form.answers.data.split('\n'): a = Answer(question_id=q.id) if answer.startswith('+'): answer = answer.replace('+', '', 1).lstrip() a.is_correct = True a.text = answer db.session.add(a) db.session.commit() return redirect(url_for('manage_questions')) q = Question.query.order_by(Question.number).all() if not q: form.number.data = 0 else: form.number.data = q[-1].number + 10 form.points.data = 1 return render_template('questions.html', form=form, questions=Question.query.all(), show_correct=True, editable=True, import_form=import_form, shuffle=(lambda x: x))
def save(self): question = Question.objects.get(pk=self.cleaned_data.get('question')) answer = Answer(text = self.cleaned_data['text'], question=question, author=self._user) answer.save() return answer
def add_answer(): question_id = request.form.get('question_id') content = request.form.get('answer_content') answer = Answer(content=content, report_reasons_and_times='A@0|B@0|C@0|D@0', report_total=0) user_id = session.get('user_id') user = User.query.filter(User.id == user_id).first() user.number_of_comment = user.number_of_comment + 1 user.point = user.point + 10 if user.point >= 50 and user.point < 100: user.grade = 2 elif user.point >= 100 and user.point < 200: user.grade = 3 elif user.point >= 200 and user.point < 500: user.grade = 4 elif user.point < 50 and user.point >= 0: user.grade = 1 else: user.grade = 5 answer.author = user # answer.author_id = user_id answer.question = Question.query.filter(Question.id == question_id).first() db.session.add(answer) db.session.commit() return redirect(url_for('detail', question_id=question_id))
def set_answers(user_id, answers=None, current_user=None): if not user_id: user_id = current_user.id if current_user else None if not current_user.id == user_id: raise ForbiddenException( f'User {current_user.id} is not permitted to answer for {user_id}') application = Application.get_for_user(user_id) if not application: raise ForbiddenException(f'User {user_id} is not an applicant') elif application.is_submitted: raise ForbiddenException( f'Cannot modify answers to a submitted application') for answer in answers: answer_record = Answer.query.filter_by( question_id=answer['question_id'], application_id=application.id).one_or_none() if not answer_record: answer_record = Answer(question_id=answer['question_id'], text=answer.get('text', ''), application_id=application.id) db.session.add(answer_record) else: answer_record.text = answer.get('text', '') db.session.commit() db.session.commit()
def load(): first_page = Page(url="http://www.example.com") first_page_key = first_page.put() first_q = Question( q="איפה זה האזור הממוזג?", who="קובי", page=first_page_key, answers=[ Answer(a="אנא עארף?", who="בניד"), Answer( a="לא יודע, אבל נשמע נעים", who="יוסי", ), ], ).put_async() second_q = Question( q="מה היה הנזק מסופת הטורנדו החזקה בהיסטוריה?", who="קובי", page=first_page_key, answers=[ Answer( a="לא יודע", who="בניד", ), ], ).put_async()
def add_answer(get_data): ''' @summary: to add multi-choice answer @param: <data> answer data dictionary ''' data = {} answer_text = get_data.get('answer_text') answer_rating = get_data.get('answer_rating','') presentation_order = get_data.get('presentation_order') question_id = get_data.get('question_id') status_cd = get_data.get('status_cd') created_by = get_data.get('created_by') now_date = datetime.now() if answer_text and answer_rating and presentation_order.isdigit() and question_id and status_cd and created_by: answer_data = Answer( answer_text = answer_text, answer_rating = answer_rating, presentation_order = presentation_order, question_id = question_id, status_cd = status_cd, created_by = created_by, updated_by = created_by, created_date = now_date, updated_date = now_date) answer_data.save() data['status'] = 1 data['msg'] = 'Answer Added succssfully' data['data'] = {'question_id': answer_data.question_id, 'answer_id': answer_data.answer_id} else: data['status'] = 0 data['msg'] = 'Some fields are missing' return data
def form_valid(self, form): for f in form.forms: answer = Answer(user=self.candidate, question=f.instance, answer=f.cleaned_data['answer']) answer.save() return super(GetTest, self).form_valid(form)
def save(self): if self._user.is_authenticated(): self.cleaned_data['author'] = self._user url = '/question/'+ str(self.cleaned_data['question'])+'/' # bad pracrtice hardcoded link self.cleaned_data['question'] = Question.objects.get(id=self.cleaned_data['question']) answer = Answer(**self.cleaned_data) answer.save() return url
def save(self): if self._user.is_anonymous(): self.cleaned_data['author_id'] = 1 else: self.cleaned_data['author'] = self._user answer = Answer(**self.cleaned_data) answer.save() return answer
def _calculate(self, unit): answer = Answer( result=False, option_id=None, ) answer.task = self._task answer.session = self._session super()._calculate(unit, True)
def test_answer_grade_retuns_1_when_correct(): """ Assumption: when an answer is correct it should return 1 else 0 :return: """ question = QuestionBuilder.create_question() answer = Answer(question, question._correct_choice) assert answer.grade() == Decimal(1)
def save(self, user_id): user = User.objects.get(id=user_id) self.cleaned_data['author'] = user question = Question.objects.get(id=self.cleaned_data['question']) self.cleaned_data['question'] = question answer = Answer(**self.cleaned_data) answer.save() return answer
def add_answer(): request_body = request.get_json() now = datetime.datetime.now() answer = Answer(id_question=request_body["id_question"], id_user=request_body["id_user"], description=request_body["description"], link=request_body["link"], created=now, last_update=now) answer.save() DBManager.commitSession() return jsonify({"status": "OK", "msg": "Answer added", "answer": answer.serialize()}), 200
def seed(): reset_db() userlist = [ User(first_name='Max', last_name='HvA'), User(first_name='Menno', last_name='HvA'), User(first_name='Robert', last_name='HvA') ] for user in userlist: user.hash_password('qwerty') quizlist = [ Quiz(name='My first time using JavaScript', user_id=1), Quiz(name='JavaScript functions', user_id=2) ] questionlist = [ Question(name='Printing', description='Print out Hello World!', answer='Hello World!', quiz_id=1), Question( name='Adding up the numbers', description='Use your knowledge to add up the numbers 1 and 2', answer='3', quiz_id=1), Question(name='Multiplying numbers', description='Multiply 5 by 4', answer='20', quiz_id=1) ] answerlist = [ Answer(input='console.log("Hello World!")', user_id=1, question_id=1), Answer(input='1+2', user_id=1, question_id=2), Answer(input='5*4', user_id=1, question_id=3), ] for user in userlist: session.add(user) session.commit() for quiz in quizlist: session.add(quiz) session.commit() for question in questionlist: session.add(question) session.commit() for answer in answerlist: session.add(answer) session.commit()
def save(self, user=None): data = self.cleaned_data question = Question.objects.get(pk=data['question']) text = data['text'] answer = Answer(question=question, text=text, author=user) answer.save() return answer
def test_voting_security(self): answer = Answer.create(question = self.question, text= 'fake answer', creator = self.avatar) self.app.get(answer.voting_url+'/up', status = 302) answer = Answer.get(answer.key()) self.assertEqual(answer.vote_count, 1) self.logout() self.app.get(answer.voting_url+'/down', status = 302) answer = Answer.get(answer.key()) self.assertEqual(answer.vote_count, 1)
def post(self, boragle_slug, question_slug): question = Question.find_by_slug(question_slug) avatar = self.get_avatar_for_boragle(question.boragle) assert avatar, question answer = self.read('answer') if not(answer and answer.strip()): raise PostingError('Please provide an answer') Answer.create(question = question, text = answer, creator = avatar) page = self.calc_last_page(question.answer_count, settings.answer_page_size) self.redirect(question.url+'?page='+str(page))
def guardar_resp(question, resp): """ Esta funcion guarda la respuesta de una pregunta. :Param question: objeto Question :Param resp: String """ a = Answer(respuesta=question, text_resp=resp) print "se guardo la pregunta: ", a a.save()
def save(self): user = User(username='******' + str(int(time.time())), password='******' + str(int(time.time()))) user.save() self.cleaned_data['author'] = user question = Question.objects.get(id=self.cleaned_data['question']) self.cleaned_data['question'] = question answer = Answer(**self.cleaned_data) answer.save() return answer
def add_questions(data): for question, answers, correct in data: q = Question(question=question, correct=correct) q.save() for answer in answers.split(','): ans = Answer(question_id=q.id, answer=answer.strip()) ans.save() print('Sample data we added')
def add_answer(): answer_content = request.form.get('answer_content') question_id = request.form.get('question_id') answer = Answer(answer_content=answer_content, question_id=question_id) # user_id=session.get('user_id') # user=User.query.filter(User.id==user_id).first() answer.author = g.user db.session.add(answer) db.session.commit() return redirect(url_for('detail', question_id=question_id))
def add_answer(): print('add answer') answer = Answer() question_id = request.form.get('question_id') answer.question_id = question_id answer.content = request.form.get('content') answer.author_id = session.get('user_id') db.session.add(answer) db.session.commit() return redirect(url_for('detail', question_id=question_id))
def add_answer(): content = request.form.get('answer_content') question_id = request.form.get('question_id') answer = Answer(content=content) answer.author = g.user question = Question.query.filter(Question.id == question_id).first() answer.question = question db.session.add(answer) db.session.commit() return redirect(url_for('detail', question_id=question_id))
def set_answer(puzzle_name, player_id, question, content_type, content): player = Player.get(Player.id == player_id) puzzle, _ = Puzzle.get_or_create(name=puzzle_name) try: answer = Answer.get((Answer.puzzle == puzzle) & (Answer.player == player)) except Answer.DoesNotExist: answer = Answer(puzzle=puzzle, player=player) answer.question = question if content_type == 'text': answer.value = content elif content_type == 'image': filename = '%s_%s.jpg' % (puzzle.id, player.id) path = '%s/images/%s' % (STATIC_DIR, filename) with open(path, 'wb') as fp: fp.write(content) answer.value = 'image:' + filename elif content_type == 'video': filename = '%s_%s.mp4' % (puzzle.id, player.id) path = '%s/videos/%s' % (STATIC_DIR, filename) with open(path, 'wb') as fp: fp.write(content) answer.value = 'video:' + filename answer.save()
def form_valid(self, form): Questions = form.instance.QuestionSet.Questions.all() request = self.request.POST form.clean() for question in Questions: if request.__contains__(str( question.pk)) and request.get(str(question.pk)) != '': if Answer.objects.filter(Question=question.pk, Survey=form.instance.pk).exists(): newAnswear = Answer.objects.get(Question=question.pk, Survey=form.instance.pk) newAnswear.Options.clear() else: newAnswear = Answer(Question=question, Survey=form.instance) newAnswear.save() if question.InputType.pk == settings.TEXT_ID: newAnswear.Text = request.get(str(question.pk)) if question.InputType.pk == settings.NUMERIC_ID: newAnswear.Numeric = request.get(str(question.pk)) if question.InputType.pk == settings.BOOL_ID: newAnswear.Bool = bool(int(request.get(str(question.pk)))) if question.InputType.pk == settings.OPTIONS_ID: for option in request.getlist(str(question.pk)): selectedOption = GetOption(option) newAnswear.Options.add(selectedOption) newAnswear.save() else: if Answer.objects.filter(Question=question.pk, Survey=form.instance.pk).exists(): Answer.objects.filter(Question=question.pk, Survey=form.instance.pk).delete() return super(FillSurvey, self).form_valid(form)
def add_answer(): content = request.form.get('answer_content') answer = Answer(content=content) answer.question_id = request.form.get('question_id') answer.author_id = session['user_id'] db.session.add(answer) db.session.commit() return redirect(url_for('issues.detail', question_id=answer.question_id))
def answer(): content = request.form.get('answer') user_id = session.get('user_id') answer = Answer(answer_content = content) # answer.author = User.query.filter(User.id == user_id).first() answer.author = g.user question_id = request.form.get('question_id') answer.question = Question.query.filter(Question.id == question_id).first() db.session.add(answer) db.session.commit() return redirect(url_for('detail',detail_id = question_id))
def add_answer(): question_id = request.form.get('question_id') question_model = Question.query.filter(Question.id == question_id).first() content = request.form.get('answer_content') answer = Answer(content=content) answer.question = question_model answer.author = g.user db.session.add(answer) db.session.commit() #return redirect(url_for('detail',question_id=question_id)) return render_template('detail.html', question=question_model)
def save(self): # getting Question by ID print 'AnswerF save: %s (%s)' % ( self.cleaned_data, self.cleaned_data['question']) q_id = int(self.cleaned_data['question']) quest = Question.objects.get(id = q_id) #ans = Answer(**self.cleaned_data) ans = Answer(text = self.cleaned_data['text']) ans.author_id = 1 quest.answer_set.add(ans) quest.save() return ans
def createQuestion(match_id): player_id = request.form['player_id'] correct = request.form['correct'] == '1' tags = request.form.getlist('tags[]') answer = Answer(player_id, correct) question = Question(tags, answers=[answer.asJSON()]) question.save() match = MatchFinder().find(match_id) match.addQuestionAndAnswer(question, answer) return "OK " + str(question._id)
def add_answer(): content = request.form.get("answer_content") question_id = request.form.get("question_id") answer = Answer(content = content) user_id = session.get("user_id") user = User.query.filter(User.id == user_id).first() answer.author = user question = Question.query.filter(Question.id == question_id).first() answer.question = question db.session.add(answer) db.session.commit() return redirect(url_for("detail", question_id = question_id))
def add_answer(): # content = request.form.get('answer_content') question_id = request.form.get('question_id') form = ContentForm() content = form.body.data answer = Answer(content=content) answer.author = g.user question = Question.query.filter(Question.id == question_id).first() answer.question = question db.session.add(answer) db.session.commit() return redirect(url_for('review', question_id=question_id, form=form))
def save(self): # getting Question by ID print 'AnswerF save: %s (%s)' % (self.cleaned_data, self.cleaned_data['question']) q_id = int(self.cleaned_data['question']) quest = Question.objects.get(id=q_id) #ans = Answer(**self.cleaned_data) ans = Answer(text=self.cleaned_data['text']) ans.author_id = 1 quest.answer_set.add(ans) quest.save() return ans
def add_answer(): answer_content = request.form.get('answer_content') user_id = session.get('user_id') user1 = User.query.filter(User.id == user_id).first() question_id = request.form.get('question_id') question1 = Question.query.filter(Question.id == question_id).first() answer1 = Answer(content=answer_content) answer1.author = user1 answer1.question = question1 db.session.add(answer1) db.session.commit() return redirect(url_for('detail', question_id=question_id))
def mutate(self, info, data): user = CreateAnswer.get_user_object(data.submitted_by) question = CreateAnswer.get_question_object(data.question) answer = Answer(key=str(uuid4()), choice=data.choice, question=question, submitted_by=user) answer.save() return CreateAnswer(answer=answer)
def write_answer(): if request.method == 'GET': question_id = request.args.get('question') link = request.args.get('link') or '' if question_id is not None: return render_template('write_answer.html', disable=True, question=Question.query.filter_by(id=question_id).first_or_404().title, link=link) return render_template('write_answer.html', link=link) else: question_get = request.form.get('question') question_desc = request.form.get('question_desc') link = request.form.get('link') desc = request.form.get('desc') private = request.form.get('private') # off=None tags = unicode(request.form.get('tags')).split(',') if (question_get is None and request.args.get('question') is None) or desc is None or link is None: abort(403) author = g.user if question_get == u"我的快速启动": question = Question.query.filter_by(id=request.args.get('question'), author=author).first_or_404() else: question = Question.query.filter_by(id=request.args.get('question')).first() if question is None: question = Question(title=question_get, author=author, desc=question_desc) if private is None: g.my_theme_normal.questions.append(question) else: g.my_theme_normal.questions.append(question) question.private = True db.session.add(question) db.session.commit() else: if question.private and g.user.id != question.author.id: abort(403) for tag in tags: if tag is not None: Tag.get_or_create(tag).add_to_tag(question) if not Answer.verify_link(link): flash(MESSAGE_BOX_CN['link_fail']) return render_template('write_answer.html', question=question_get, link=link, desc=desc, question_desc=question_desc) if Answer.query.filter_by(link=link, question=question, desc=desc).first() is not None: flash(MESSAGE_BOX_CN['link_fail_same']) return render_template('write_answer.html', question=question_get, link=link, desc=desc, question_desc=question_desc) answer = Answer(link=link, desc=desc, author=author, question=question) db.session.add(answer) db.session.commit() if g.user.id != question.author.id: Message.send_message(question.author, render_template('msg/msg_item_answer.html', sender=g.user, answer=answer, question=question)) send_email(question.author.email, MESSAGE_BOX_CN['email_prefix_new_link'], 'email/msg_answer', sender=g.user, answer=answer) flash(MESSAGE_BOX_CN['write_success']) return redirect(url_for('view_question', id=answer.question.id, _anchor="answer-"+str(answer.id)))
def post(self): parse = reqparse.RequestParser() parse.add_argument('qid', type=int) parse.add_argument('atype', type=int) parse.add_argument('meaning', type=str) parse.add_argument('fromWhat', type=str) parse.add_argument('example', type=str) args = parse.parse_args() qid = args.get('qid') atype = args.get('atype') meaning = args.get('meaning') fromWhat = args.get('fromWhat') example = args.get('example') # 判断对应的question是否存在 try: question = Question.query.get(qid) except: print("{} question get: {} failure...".format( time.strftime("%Y-%m-%d %H:%M:%S"), qid)) response = make_response( jsonify(code=12, message='question get fail')) return response # 如果对应question不存在,则返回错误 if not question: print("{} question get: {} failure...".format( time.strftime("%Y-%m-%d %H:%M:%S"), qid)) response = make_response( jsonify(code=12, message='question get fail')) try: answer = Answer(qid=qid, atype=atype, meaning=meaning, fromWhat=fromWhat, example=example, created_time=int(time.time())) db.session.add(answer) db.session.commit() response = make_response( jsonify(code=0, message='OK', data={'answer': answer.to_json()})) return response except: print("{} answer add: {} failure...".format( time.strftime("%Y-%m-%d %H:%M:%S"), qid)) db.session.rollback() response = make_response( jsonify(code=21, message='answer add fail')) return response finally: db.session.close()
def question(request): if request.method == 'POST' : req = simplejson.loads(request.body,strict=False) # get the json parameters,username,course,questionnumber and answer username = req['username'] course = req['course'] role = req['role'] quetionnumber = req['questionnumber'] answer = req['answer'] #check the parameter validating #store to the db ans = Answer(question_id = questionnumber, course_id = course,text = answer) ans.save()
def run(self): Answer.query.delete() db.session.commit() for file_name in glob(os.path.join(ANSWERS_DIR, '**/*.csv')): with open(file_name, 'rb') as csvfile: locale = file_name.split('/')[-2] csv_reader = csv.reader(csvfile) for row in csv_reader: answer = Answer() answer.locale = locale answer.text = unicode(row[0], 'utf-8') db.session.add(answer) db.session.commit()
def set_answer(puzzle_name, player_id, question, content_type, content): player = Player.get(Player.id == player_id) puzzle, _ = Puzzle.get_or_create(name=puzzle_name) try: answer = Answer.get( (Answer.puzzle == puzzle) & (Answer.player == player)) except Answer.DoesNotExist: answer = Answer(puzzle=puzzle, player=player) answer.question = question if content_type == 'text': answer.value = content elif content_type == 'image': filename = '%s_%s.jpg' % (puzzle.id, player.id) path = '%s/images/%s' % (STATIC_DIR, filename) with open(path, 'wb') as fp: fp.write(content) answer.value = 'image:' + filename elif content_type == 'video': filename = '%s_%s.mp4' % (puzzle.id, player.id) path = '%s/videos/%s' % (STATIC_DIR, filename) with open(path, 'wb') as fp: fp.write(content) answer.value = 'video:' + filename answer.save()
def filldb(request, cou): for x in range(0, int(cou)): q = Question(title = "Question #"+str(x), text = "Just a question with number "+str(x)) q.rating = x q.author_id = 1 q.added_at = date(2016, 03, 1+x) q.save() q.added_at = date(2016, 03, 1+x) for y in range(1, x+2): a = Answer(text = "answer #"+str(y)+" for question #"+str(x)) a.author_id = 1 q.answer_set.add(a) q.save() return HttpResponse("OK")
def user_profile(): """Displays the user profile page""" user = users.get_current_user() question_count = Question.count_for(user) answer_count = Answer.count_for(user) form = ProspectiveUserForm() all_prospective_users = ProspectiveUser.get_for(user) prospective_user = all_prospective_users.get() if request.method == 'POST': if prospective_user is None: prospective_user = ProspectiveUser ( login = user, origin_location = get_location(form.origin_location.data), notification_radius_in_km = form.notification_radius_in_km.data, screen_name = form.screen_name.data ) else: prospective_user.origin_location = get_location(form.origin_location.data) prospective_user.notification_radius_in_km = form.notification_radius_in_km.data prospective_user.screen_name = form.screen_name.data try: prospective_user.put() subscribe_user_for_nearby_questions(prospective_user.key.id()) flash(u'Home location successfully saved.', 'success') return redirect(url_for('user_profile')) except CapabilityDisabledError: flash(u'App Engine Datastore is currently in read-only mode.', 'info') return redirect(url_for('user_profile')) return render_template('user_profile.html', user=user, prospective_user=prospective_user, question_count=question_count, answer_count=answer_count, form=form)
def reply_question(question_id): user_id = session['user_id'] data = json.loads(request.data) data['author_id'] = user_id data['question_id'] = question_id answer = Answer(**data) result = answer.save() if result: answer = answer.to_dict() author = User.query.get(user_id).to_dict() answer['author'] = author socketio.emit('question' + str(question_id), answer, namespace='/qa') return jsonify({'status': 1 if result else 0})
def handleForm(request): new_title = request.POST['title'] new_author = request.POST['author'] new_desc = request.POST['desc'] answers = [] for i in range(1, 20): input_name = "answer" + str(i) if input_name in request.POST: s = request.POST[input_name].replace("'", "") answers.append(s) new_survey = Survey(title=new_title, author=new_author, desc=new_desc) new_survey.save() for answer in answers: new_answer = Answer(survey=new_survey, text=answer, votes=0) new_answer.save() return HttpResponseRedirect('/survey/' + str(new_survey.id))
def answer_question(request, question_id): if request.user.is_authenticated(): if request.method == 'POST': form = AnswerForm(request.POST) if form.is_valid(): question = Question.objects.get(id = question_id) author = request.user text = form.cleaned_data['answer'] answer = Answer(text = text, author = author, question = question) answer.save() return view_question(request, question_id) else: pass #TODO: validar cuando el formulario de errores. else: return HttpResponseRedirect('/cuentas/login')
def get_rev_set_raw(rev): qs = [] #first object to be the description of the revision lect_class = LectClass.get(rev.lect_class) rev_desc = { 'lecturer':rev.user.name, 'institution':rev.user.institution, 'title':rev.title, 'class':lect_class.name, 'description':rev.description, 'created':rev.created.strftime("%B %d, %Y") } qs.append(rev_desc) questions = Question.gql('WHERE revision = :1',rev).fetch(100) #how do we fetch all the Qs? for q in questions: answers = Answer.gql('WHERE question=:1',q) ans = [] for a in answers: ans.append(a.answer) question = { 'question':q.question.replace("\n","").replace("\r",""), 'answers':ans } qs.append(question) return qs
def showanswer(request):#q,a1,a2 if request.POST: quest = request.POST['ques'] ques_lst = Question.objects.all() samelst = [0]*len(ques_lst) queslst = [0]*len(ques_lst)#wenti xiangsidu anslst = [0]*len(ques_lst) ans = []#daan zuijia ques = [] for i in range (0,len(ques_lst)): samelst[i] = difflib.SequenceMatcher(None, quest, ques_lst[i].question).ratio()#jisuan xiangsidu queslst[i] = samelst[i] ansl = ques_lst[i].answers.all() maxlen = 0 maxindex = 0 for j in range (0,len(ansl)): if len(ansl[j].answer)>maxlen: maxlen = len(ansl[j].answer) maxindex = j samelst[i] += maxlen/250#daan de youxianxing anslst[i] = maxindex#yigewenti de zuichangdaan #return HttpResponse(ques_lst[i].question) ans += [ansl[maxindex].answer] inda = samelst.index(max(samelst))#zuiyou wenti #wenti chuanguoqu for i in range(0,3):#xunhuan 3 ci indq = queslst.index(max(queslst)) ques += [ques_lst[indq].question] queslst[indq] = 0 usern = request.session.get('username')#baoun wenti user1 = User.objects.get(username = usern) if quest in ques_lst: multiple_question = Question.objects.get(question = quest) user1.myquestions.add(multiple_question) else: ansbest = Answer.objects.get(answer = ans[inda]) multiple_answer = Answer(answer = ans[inda],score = ansbest.score) multiple_answer.save() multiple_question = Question(question = quest) multiple_question.save() multiple_question.answers.add(multiple_answer) user1.myquestions.add(multiple_question) return render_to_response('showanswer.html',{'question':quest, 'answer':ans[inda],'queslst':ques})#showanswer return render_to_response('showanswer.html')
def save(self, commit=True): test = super(TestAdminForm, self).save(False) file = self.cleaned_data['file'] questions_count = self.cleaned_data['questions_count'] if file: test_name = test.name test.save() AnswerResult.objects.filter(answer__question__test=test).delete() AnswerChoice.objects.filter(question__test=test).delete() TestPass.objects.filter(test=test).delete() Answer.objects.filter(question__test=test).delete() Question.objects.filter(test=test).delete() questions = parser(file) count = 0 cur_test = test for i, question in enumerate(questions): count += 1 q = Question(test=cur_test, question=question['question']) if question['text_answer']: q.text_answer = question['text_answer'] q.save() else: q.save() for answer in question['answers']: a = Answer(question=q) a.answer = answer['text'] a.correct = answer['correct'] a.save() if questions_count and count >= questions_count: if (len(questions) - i) >= questions_count: cur_test.name = '%s [%s-%s]' % (test_name, i+1-count, i+1) cur_test.save() cur_test = copy(test) cur_test.pk = None cur_test.save() else: cur_test.name = '%s [%s-%s]' % (test_name, i+1-count, len(questions)) cur_test.save() count = 0 return test
def question_display(request, question_id): try: question = Question.objects.get_by_id(question_id) except: raise Http404 if request.method == 'POST': request_text = request.POST.get('text') new_answer = Answer(text = request_text, author = UserProfile.objects.get(user_account = request.user), date = datetime.datetime.now(), question = Question.objects.get_by_id(question_id)) new_answer.save() answer_data = { 'answer_text' : request_text, 'answer_author': request.user.username, 'answer_id': new_answer.id, } requests.post('http://127.0.0.1:7777/pub', json = answer_data, headers = {'content-type': 'application/json'}) return HttpResponseRedirect('/question/{}/?p={}#{}'.format(question_id, request.GET.get('p',1), new_answer.id)) answer_list = Answer.objects.get_by_question(question) page_n = request.GET.get('p',1) paginator = Paginator(answer_list, 5) paginator.baseurl = 'http://localhost/question/{}/?p='.format(question_id) try: page_objects = paginator.page(page_n) except: raise Http404 return render(request, 'question.html', { 'question': question, 'page_objects': page_objects, 'page_title': 'Question', 'paginator': paginator, })
def post(self, request, *args, **kwargs): form = forms.PostViewForm(request.POST) try: if(form.is_valid()): post_id = kwargs['post_id'] q = Question.objects.get(id=post_id) answer = Answer(user=request.user, question=q, content=request.POST.get('answer_content', '')) answer.save() return HttpResponseRedirect("/posts/" + post_id) answers = sorted(Answer.objects.filter(question=q), key=attrgetter('id')) # views.create(title) context = RequestContext(request, {'first_name': request.user.username, 'question':q, 'answers': answers}) return render_to_response(self.template, context_instance=context) except ValidationError as v: return HttpResponseBadRequest(json.dumps(v.mesage_dict)) except Exception as e: return HttpResponseBadRequest(json.dumps({'error': e.message}))
def statistics(request): _check_for_admin() question = get_question() chooses = question.chooses answers = dict((ans.key().id(), {"answer":ans, "count": 0, "chooses":[]}) for ans in question.answers) for choose in chooses: for answer in Answer.get(choose.answers): if answer: key = answer.key() id = key.id() answers[id]["count"] += 1 answer = Answer.get(key) answers[id]["chooses"] = Choose.gql("where answers = :1 order by when", answer).fetch(200) return render_to_response('statistics.html', { 'answers':sorted(answers.items(), key=lambda a:a[1]["count"], reverse=True) }, context_instance=RequestContext(request))
def player_home(name): players = Player.objects(name=name) if not players: abort(404) player = players[0] answer_count = Answer.objects(player=player).count() return render_template('player_home.html', name=name , answer_count=answer_count)
def answer(request): result = dict() result['code'] = 0 result['message'] = 'success' answer_type = '' if request.method == 'POST': check = ['user', 'target_user', 'query_id', 'message'] inputs = dict() for field in check: if request.POST[field]: value = request.POST[field] inputs[field] = value else: print 'Error: Parameter ' + field + ' is missing' result['code'] = 1 result['message'] = 'Error: Parameter ' + field + ' is missing' return HttpResponse(json.dumps(result)) try: user = User.objects.get(phone=inputs['user']) target_user = User.objects.get(phone=inputs['target_user']) query = Query.objects.get(id=inputs['query_id']) if user.gender == 'M' : new_answer = Answer(user = user, target_user = target_user, query = query, message = inputs['message']) new_answer.save() else: print 'Error: Answering is only valid for male user' result['code'] = 1 result['message'] = 'Error: Answering is only valid for male user' return HttpResponse(json.dumps(result)) except Exception as e: print str(e) result['code'] = 1 result['message'] = 'Error: Unregisted User OR Not exist Query' return HttpResponse(json.dumps(result)) return HttpResponse(json.dumps(result))
def save(self, commit=True): if not self.cleaned_data['answer']: if self.fields['answer'].required: raise ValidationError, _('This field is required.') return ans = Answer() ans.question = self.question ans.session_key = self.session_key if self.user.is_authenticated(): ans.user = self.user else: ans.user = None ans.interview_uuid = self.interview_uuid ans.text = self.cleaned_data['answer'] if commit: ans.save() return ans
def destroy_seed(): objects = [] objects.extend(Question.objects()) objects.extend(Player.objects()) objects.extend(Answer.objects()) objects.extend(BodyMediaData.objects()) for o in objects: o.delete() return 'ouch'
def commit_post_add(request): """ajax提交答案""" name = request.session.get('name') form = AnswerForm(request.POST) if request.method == "POST" and name and form.is_valid(): data = form.cleaned_data qid = data['qid'] text = data['text'] # text = html.replace('<', '<').replace('>', '>') #待改 question = Question.objects.get(id=int(qid)) # 答案数 + 1 question.q_times += 1 question.save() # 保存到数据库 user = User.objects.get(name=name.split()[0]) answer = Answer(user=user, question=question, text=text) answer.save() # 待修改 return HttpResponse('ok') else: return HttpResponse('error')
def question(request, qid, **kwargs): session_data = {} if local.request.session['uid']: session_data['user_name'] = User.get_by_id(local.request.session['uid'])[0].name try: question = Question.get_by_id(qid)[0] except TypeError: return not_found(request) question.views += 1 question.update() edit = question.latest_edit()[0] category = Category.get_by_id(question.category_id)[0] user = User.get_by_id(question.user_id)[0] question_data = { 'title' : str(edit.title), 'category' : str(category.name), 'votes' : str(question.votes), 'author' : str(user.name), 'author_id' : str(user.id), 'avatar' : str(user.avatar), 'views' : str(question.views), 'created' : str(question.created), 'body' : str(edit.body), } try: answers_list = Answer.get(where=('question_id', qid), order=('votes', 'desc')) answer_data_list = [] for answer in answers_list: answer_user = User.get_by_id(answer.user_id)[0] answer_edit = AnswerEdit.get(where=('answer_id', answer.id))[0] answer_data = { 'votes' : str(answer.votes), 'author' : str(answer_user.name), 'author_id' : str(answer_user.id), 'avatar' : str(answer_user.avatar), 'body' : str(answer_edit.body), } answer_data_list.append(answer_data) except TypeError: answer_data_list = False page = Page(session_data) page.title = str(edit.title) + ' - Meno' content = Thread(question_data, answer_data_list) local.request.session['last'] = request.base_url return respond(page.render(content))