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') # user_id = session['user_id'] # print(1, user_id, content, question_id) # user = User.query.filter(User.id == user_id).first() quest = Question.query.filter(Question.id == question_id).first() answer = Answer() answer.author = g.user answer.content = content answer.question = quest db.session.add(answer) db.session.commit() return redirect(url_for('detail', question_id=question_id))
def view_question(request, question_id): errors = [] try: question = Question.objects.prefetch_related('tags').select_related( 'author').get(id=question_id) except Question.DoesNotExist: raise Http404("Question does not exist") is_my = (request.user.id == question.author.id) if request.method == 'POST': # validate answer_text = request.POST.get('answer') if not answer_text: errors.append('Empty answer not allowed') answer_text = answer_text[:8192] with transaction.atomic(): try: new_answer = Answer() new_answer.question = question new_answer.author = request.user new_answer.content = answer_text new_answer.create_date = timezone.now() new_answer.save() except Exception as e: errors.append("Unable to save answer: %s" % e.message) question.answers_count = Answer.objects.filter( question_id=question.id).count() question.save() if not errors: redirect('view_question', question.id) return render(request, 'answers/answer.html', { 'question': question, 'errors': errors, 'is_my': is_my })
def fetchAnswers(self, q_id, start, count): query = ( "SELECT id, owner_id, content, c_time FROM answers WHERE q_id = %s ORDER BY c_time DESC LIMIT %s OFFSET %s ;" ) cursor = self.db.cursor() ret = [] cursor.execute(query, (q_id, int(count), int(start))) for (id, owner_id, content, c_time) in cursor: answer = Answer() answer.id = id answer.question_id = q_id answer.owner_id = owner_id answer.content = content answer.create_time = c_time ret.append(answer) cursor.close() return ret