Example #1
0
def question(request, qid):
    try:
        question = question_counter(Question.objects.get(id=qid))
    except:
        raise Http404("No matches Questions the given query.")

    if request.method == 'POST':
        form = AnswerForm(data=request.POST)
        if form.is_valid() and request.user.is_authenticated:
            answer = Answer.objects.create(author=request.user.profile,
                                           text=form.cleaned_data['text'],
                                           question=question)
    else:
        form = AnswerForm()
    page_obj, _ = paginate(Answer.objects.get_answer_by_likes(question),
                           request)
    tags = Tag.objects.get_popular()
    return render(
        request, 'question.html', {
            'user': request.user,
            'form': form,
            'question': question,
            'page_obj': page_obj,
            'tags': tags,
        })
Example #2
0
def answer(id):
    # Figure out if answer already exists
    question = Question.query.get(int(id))
    answer = Answer.query.filter_by(question=question).first()

    form = AnswerForm()
    # If answer doesn't yet exist
    if answer is None:
        if form.validate_on_submit():
            answer = Answer(body=form.body.data,
                            author=current_user,
                            question=question)
            db.session.add(answer)
            db.session.commit()
            flash(f'Your response has been recorded')
            return redirect(url_for('profile', username=current_user.username))
    elif request.method == 'GET':
        form.body.data = answer.body
    # Validate an existing answer
    elif form.validate_on_submit():
        answer.body = form.body.data
        db.session.commit()
        flash(f'Your response has been edited')
        return redirect(url_for('profile', username=current_user.username))
    return render_template('answer.html',
                           form=form,
                           question=question,
                           title='Answer')
Example #3
0
def question(qid):
    question = Question.query.get(qid)
    question.date = question.date.strftime("%c")

    answers = db.session.query(Answer).filter(Answer.question_id.in_(
        (qid))).all()
    answers_count = len(answers)

    answer_form = AnswerForm()
    if request.method == "POST":
        if answer_form.is_submitted():
            answer = Answer(question_id=qid,
                            answerer_id=current_user.id,
                            answerer_name=current_user.first_name + " " +
                            current_user.last_name,
                            content=answer_form.answer.data)

            db.session.add(answer)
            db.session.commit()

            return redirect(url_for('question', qid=qid))
        else:
            return render_template(f'main/question.html',
                                   question=question,
                                   form=answer_form,
                                   answers=answers,
                                   answers_count=answers_count)
    if request.method == "GET":
        return render_template(f'main/question.html',
                               question=question,
                               form=answer_form,
                               answers=answers,
                               answers_count=answers_count)
Example #4
0
def question(request, qid):
    question = get_object_or_404(Question, id=qid)
    if request.method == "GET":
        form = AnswerForm()
    else:
        form = AnswerForm(data=request.POST)
        if form.is_valid() and request.user.is_authenticated:
            answer = Answer.objects.create(text=form.cleaned_data["field"],
                                           author=request.user,
                                           question=question)

            CL.publish(
                f"question{question.id}", {
                    "answer":
                    render_to_string("inc/answer.html", {
                        "answer": answer,
                    })
                })

    answers = Answer.objects.get_by_question(question)
    token = jwt.encode({"sub": "some_name"}, HMAC_TOKEN)
    return render(
        request, "question.html", {
            "form": form,
            "question": question,
            "answers": answers,
            "is_owner": (question.author == request.user),
            "TOKEN": token.decode(),
        })
Example #5
0
def game():

    # protect route - if user is not logged in 
    # they will be redirect back to the index page
    if not 'user' in session:
        return redirect(url_for('index'))


    # if a new game has begun start the timer
    if session['new_game'] == 1:
        session['new_game'] = 0
        session['start_time'] = time.time()


    
    # Answer Checking
    answer_form = AnswerForm()
    if answer_form.validate_on_submit():

        # if the answer is correct - increase the correct score
        if session['game'][session['index'] - 1]['answer'] ==  answer_form.answer.data.lower():
            session['current_score'] += 1
        
        # otherwise - it must be empty or a wrong answer
        else:
            if not answer_form.answer.data:
                # if answer is empty
                flash(f'answer field cannot be empty')
            else:
                # if answer is wrong
                flash(f'Incorrect answer! You guessed {answer_form.answer.data}, try again..')

            # return the same question
            # prevent index increasing
            session['index'] -= 1
            return redirect(url_for('game'))


    # If the game is over 
    # Write users scores to json file to save them
    # then redirect to leaderboard to show results
    if session['index'] >= 30:
        set_session_scores()
        return redirect(url_for('leaderboard'))


    # increase index pagination to show ther next question logo
    # continue to track the players time - pass time to jinja
    session['index'] += 1
    session['current_time'] = round(time.time() - session['start_time'])


    # default - render game.html
    # if a question is passed - a new question will render
    return render_template('game.html', endpoint="game", answer_form=answer_form)
Example #6
0
def deal_with_answer(request, question):
    form = AnswerForm(request.POST)
    print('arrive deal_with_answer')
    if form.is_valid():
        answer = form.cleaned_data['answer']
        c = Answer(answerer=request.user.profile, belong_to_question=question)
        c.content = answer
        c.save()
        return AnswerForm
    else:
        return form
Example #7
0
    def post(self, request, pk):
        if not request.user.is_authenticated:
            return HttpResponseRedirect(reverse('login'))

        form = AnswerForm(request.POST)
        if not form.is_valid():
            return render(request, 'question.html', {'form': form})
        new_answer = form.save(commit=False)
        new_answer.author = request.user.user
        new_answer.question_id = pk
        new_answer.save()
        return HttpResponseRedirect(reverse('question', args=(pk, )))
Example #8
0
def index():
    form = AnswerForm()
    form.generate_form()
    if form.validate_on_submit():
        ans = str(dict(request.form))
        print(ans)
        print(type(ans))
        print('啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊')
        current_user.ans = str(dict(request.form))
        db.session.commit()
        return redirect(url_for('success'))
    return render_template('index.html', title='Answer', form=form)
Example #9
0
def check_answer():
    form = AnswerForm()
    if form.validate_on_submit():
        print("original " + form.original.data)
        print("answer " + form.answer.data)
        if form.original.data == form.answer.data:
            flash('Correct!')
            print("Correct input!")
        else:
            flash('Wrong!')
            print("Incorrect input!")
    return render_template('index.html', form=form)
Example #10
0
def question(request, question_id):
    try:
        question = Question.objects.get_single(int(question_id))
    except Question.DoesNotExist:
        raise Http404()

    # answers = question.answer_set.all()

    # question_ = get_object_or_404(Question, pk=question_id)
    answers = question.answer_set.all()

    likes = getQuestionPageLikes(question, answers, request.user)

    page = get_page(answers, request, 3)
    tags = Tag.objects.count_popular()
    form = AnswerForm()

    if request.method == "POST":
        form = AnswerForm(request.POST)
        if form.is_valid():
            ans = form.save(question, request.user)
            return HttpResponseRedirect('%s?page=%d' % (reverse(
                'question', kwargs={'question_id': question.id}), ans.id))
        else:
            form = AnswerForm()
    return render(
        request, 'question.html', {
            'question': question,
            'answers': page,
            'tags': tags,
            'form': form,
            'likes': likes[0],
            'dislikes': likes[1],
            'islike': likes[2]
        })
Example #11
0
def question(request, qid):
    context['question'] = Question.objects.get(pk=qid)
    form = AnswerForm(request.POST)

    if request.POST:
        if form.is_valid():
            answer = Answer.objects.create(
                question=context['question'],
                text=form.cleaned_data.get('textarea'),
                author=request.user.profile)

    context['answers'] = Answer.objects.hottest(qid)
    context['form'] = form
    return render(request, 'question.html', context)
def create(question_id):
    form = AnswerForm()
    question = Question.query.get_or_404(question_id)
    if form.validate_on_submit():
        content = request.form['content']
        answer = Answer(content=content,
                        create_date=datetime.now(),
                        user=g.user)
        question.answer_set.append(answer)
        db.session.commit()
        return redirect('{}#answer_{}'.format(
            url_for('question.detail', question_id=question_id), answer.id))
    return render_template('question/question_detail.html',
                           question=question,
                           form=form)
Example #13
0
def main():
    return render_template('main.html',
                           login=LoginForm(),
                           signup=SignupForm(),
                           movie=SelectMovieForm(),
                           question=QuestionForm(),
                           answer=AnswerForm())
Example #14
0
def answer(question_id):
    form = AnswerForm()
    question = Questions.query.filter_by(id=question_id).first()
    if not question:
        flash('Looks like this question is not available')
        return redirect(url_for('main_page'))
    if request.method == 'POST' and form.validate():
        answer_text = request.form['answer']
        user = g.user.id
        answer = Answers(answer_text, user, question.id)
        db_session.add(answer)
        db_session.commit()
        flash('Your answer successfully submitted')
        return redirect(url_for('main_page'))
    return render_template('answers.html', title='Add answer',
                           question=question, form=form)
Example #15
0
def question_for_anonymous(id):
    ques = Items.query.filter_by(id=id).first()
    ansform = AnswerForm()
    ans_ = Answer.query.filter(Answer.belongtoques == id).all()
    ans_id_ = []
    for a in ans_:
        ans_id_.append(a.id)
    ans = Items.query.filter(Items.types == 2).filter(
        Items.ans_id.in_(ans_id_)).all()
    pt = PostTag.query.filter_by(postid=id).all()
    the_ques_tags_id = []
    related = []
    for p in pt:
        the_ques_tags_id.append(p.tagid)
    the_ques_tags = Items.query.filter(Items.id.in_(the_ques_tags_id)).all()
    rposts_rcds = PostTag.query.filter(
        PostTag.tagid.in_(the_ques_tags_id)).all()
    ansnum = Answer.query.filter(Answer.belongtoques == id).count()
    for r in rposts_rcds:
        related.append(r.postid)
    related = list(set(related))
    if len(related) != 0:
        related.remove(id)
        rposts = Items.query.filter(Items.id.in_(related)).all()
    else:
        rposts = []

    return render_template('questions.html', ques = ques, form = ansform, Permission = Permission, \
    ans = ans,  tags= the_ques_tags, ansnum = ansnum, rposts = rposts)
Example #16
0
def question(request, qid):
    q = get_object_or_404(Question, pk=qid)
    if request.method == 'POST':
        form = AnswerForm(request.user.profile, q, data=request.POST)
        if form.is_valid():
            form.save()
    content, page = pagination(
        Answer.objects.question_answers(q),
        request,
        per_page=5,
    )
    return render(request, 'question.html', {
        'question': q,
        'answers': content,
        'page': page,
        **tags_and_users,
    })
Example #17
0
def question(request, id):
    last_id = Question.objects.latest('id').pk
    if id > last_id:
        id = last_id

    question = get_object_or_404(Question, id=id)
    answers = pagination(Answer.objects.answers(id), request, per_page=3)

    answers_votes = {}
    question_vote = {}
    if request.user.is_authenticated:
        answers_votes = VoteAnswer.objects.reaction(alist=list(answers.object_list.values_list('id', flat=True)),
                                                    aid=request.user.profile)

        question_vote = VoteQuestion.objects.reaction(qlist=[question.id, ],
                                                      aid=request.user.profile)

    if request.method == 'POST':
        form = AnswerForm(data=request.POST, profile=request.user.profile, question=question)
        if form.is_valid():
            form.save()
            # return redirect(reverse('question', kwargs={'id': id}) + '?page=last')
            return redirect(reverse('question', kwargs={'id': id}))

    else:
        form = AnswerForm(None, None)

    return render(request, 'question_page.html', {
        'title': f'Question {id}',
        'answers_votes': answers_votes,
        'votes': question_vote,
        'question': question,
        'answers': answers,
        'form': form
    })
Example #18
0
def question_answer(request, pk):
    last_id = Question.objects.latest('id').pk
    if pk > last_id:
        pk = last_id

    question = get_object_or_404(Question, id=pk)
    if request.method == 'POST':
        form = AnswerForm(data=request.POST,
                          author=request.user.author,
                          question=question)
        if form.is_valid():
            form.save()
            return redirect(
                reverse('question', kwargs={'pk': pk}) + '?page=last')

    else:
        form = AnswerForm(None, None)
    return render(
        request, "question_answer.html", {
            'questions': Question.objects.one_question(pk),
            'style': False,
            'comments': pagination(
                Answer.objects.answers(pk), request, per_page=3),
            'form': form
        })
Example #19
0
def answer(question_id):
    form = AnswerForm()
    question = Questions.query.filter_by(id=question_id).first()
    if not question:
        flash('Looks like this question is not available')
        return redirect(url_for('main_page'))
    if request.method == 'POST' and form.validate():
        answer_text = request.form['answer']
        user = g.user.id
        answer = Answers(answer_text, user, question.id)
        db_session.add(answer)
        db_session.commit()
        flash('Your answer successfully submitted')
        return redirect(url_for('main_page'))
    return render_template('answers.html',
                           title='Add answer',
                           question=question,
                           form=form)
Example #20
0
def test(request):
    if request.method == "POST":
        context = {
            'pk': request.example,
        }
        return render(request, 'app/test.html', context)
    else:
        form = AnswerForm()
        context = {}
        return render(request, 'app/test.html', context)
Example #21
0
 def get(self, request, pk):
     q = Question.objects.get_one(
         pk,
         request.user.user.id if request.user.is_authenticated else None)
     if len(q) == 0:
         raise Http404('Question doesn\'t found')
     context = paginate(Answer.objects.get_by_question(pk), request, 3)
     context['question'] = q[0]
     context['form'] = AnswerForm()
     return render(request, 'question.html', context)
Example #22
0
def question(question_id):

    q = Question.query.filter_by(id=question_id).first()
    if q.answered == True or q.receiver_id != current_user.id:
        return redirect(url_for('index'))
    form = AnswerForm()

    if form.validate_on_submit():
        q.answered = True
        q.answer = form.answer.data
        q.answer_timestamp = datetime.utcnow()
        db.session.add(q)
        db.session.commit()
        return (redirect('/user/' + current_user.username)
                )  # Need to be changed on 'Profile' page

    return render_template('question.html',
                           question=q,
                           form=form,
                           page='Answer')
Example #23
0
def post(post_id):
    post = Post.query.filter_by(id=post_id).first()
    if post is None:
        flash('Post with id: {} not found.'.format(post_id))
        return redirect(url_for('index'))

    form = AnswerForm()
    if form.validate_on_submit():
        answer = Answer(body=form.post.data,
                        participant=current_user,
                        parent=post)
        db.session.add(answer)
        db.session.commit()
        flash('Your answer saved!')
        return redirect(url_for('post', post_id=post_id))
    answers = Answer.query.filter_by(post_id=post_id)
    return render_template('post.html',
                           title='Post',
                           form=form,
                           post=post,
                           answers=answers)
Example #24
0
def choice_add(request, question_id):
    question = QuestionQuiz.objects.get(id=question_id)
    if request.method == 'POST':
        form = AnswerForm(request.POST)
        if form.is_valid():
            if question.answers_set.count() < 4:
                choice = form.save(commit=False)
                choice.question = question
                choice.vote = 0
                choice.save()
                #form.save()
            else:
                #messages.info(request, 'Esta pregunta ya tiene 4 respuestas.')
                return render(
                    request, 'polls/detail.html', {
                        'title': 'Respuestas asociadas a la pregunta:',
                        'question': question,
                        'max_answ': 'Esta pregunta ya tiene 4 respuestas.',
                    })
    else:
        form = AnswerForm()
    #return render_to_response ('choice_new.html', {'form': form, 'poll_id': poll_id,}, context_instance = RequestContext(request),)
    return render(
        request, 'polls/choice_new.html', {
            'title': 'Pregunta:' + question.question_text,
            'form': form,
            'ans_count': question.answers_set.count(),
        })
Example #25
0
def question(request, id):
    if request.method == "GET":
        form = AnswerForm(initial={
            'id_question': id,
        })

    if request.method == "POST":
        form = AnswerForm(data=request.POST)
        if form.is_valid():
            answer = form.save(commit=False)
            answer.question_id = form.cleaned_data['id_question']
            answer.author = request.user.users
            answer.save()
            return redirect(
                reverse('question',
                        kwargs={'id': form.cleaned_data['id_question']}))

    data = paginator(Answers.objects.answers_by_question(id), request)
    info = QuestionsLikes.objects.likes([Questions.objects.one_question(id)],
                                        request.user.pk)[0]
    vote_answer = AnswersLikes.objects.likes(data, request.user.pk)

    return render(
        request, 'answer.html', {
            'id': id,
            'one_question': Questions.objects.one_question(id),
            'data': data,
            'ans_data': zip(data, vote_answer),
            'info': info,
            'form': form
        })
Example #26
0
def main():
    movie = request.args.get('movie')
    if movie:
        url = 'https://www.omdbapi.com/?apikey=227f7057&' + 't=' + movie
        data = requests.get(url).json()
        return render_template('main.html',
                               data=data,
                               login=LoginForm(),
                               signup=SignupForm(),
                               question=QuestionForm(),
                               answer=AnswerForm())
    else:
        return redirect(url_for('home'))
def question():
    if CLOSE_WEBSITE:
        return redirect(url_for('index'))
    else:
        n_question = current_user.number_answers()
        form = AnswerForm()
        question_id = session['question_id']
        current_question = Question.query.get(question_id)

        if form.validate_on_submit():
            # flash('Your answered:'+str(form.choice.data)+' to question :'+str(current_question.id)+' known '+str(form.known.data))
            if Question.query.get(question_id).ongoing_user == current_user.id and datetime.utcnow()-current_question.ongoing_since > LOCK_TIME:
                flash('You took too long to answer (more than '+str(int(LOCK_TIME.total_seconds()//60))+' minutes)! Here is a new example.')
                current_question.ongoing_since = MIN_DATE
                current_question.ongoing_user = -1
                db.session.commit()
            else:
                aborted = current_question.answer(form.choice.data,current_user,recognised=form.known.data,difficulty=form.difficulty.data)
                if aborted:
                    flash('Something went wrong! Here is a new example.')
                    current_question.ongoing_since = MIN_DATE
                    current_question.ongoing_user = -1
                    db.session.commit()

            session['question_id'] = current_user.next_question()
            Question.query.get(session['question_id']).ongoing_since = datetime.utcnow()
            Question.query.get(session['question_id']).ongoing_user = current_user.id
            db.session.commit()
            return redirect(url_for('question'))

        # flash(str([current_question.id, question_id]))
        # import datetime as dt
        # all_questions = Question.query.filter(Question.ongoing_since>datetime.utcnow()-LOCK_TIME).all()
        # print "current_user",current_user.id
        # for question in all_questions:
        #     print question, question.ongoing_since, question.ongoing_user

        return render_template('question.html', number=n_question+1,filepaths = current_question.get_filepaths(), form=form, debug=app.debug)
Example #28
0
def one_question_page(request, num_quest):
    question = Question.objects.one_question(int(num_quest))

    answers = Answer.objects.answers_by_que(int(num_quest))

    page_obj, page = paginate(answers, request)

    best_members = UserProfile.objects.best_members()
    popular_tags = Tag.objects.popular_tags()

    if request.method == 'GET':
        form = AnswerForm()
    else:
        form = AnswerForm(data=request.POST)
        if form.is_valid() and request.user.is_authenticated:
            que = Question.objects.get(id=num_quest)
            answer = Answer.objects.create(author=request.user.userprofile,
                                           question=que,
                                           text=form.cleaned_data['text'])
            que.answers += 1
            que.save()
            answer.save()
            print(page)
            return redirect(
                reverse('one_question', kwargs={'num_quest': que.pk}) +
                f"?page={len(page_obj)}")

    return render(
        request, 'one_question_page.html', {
            'question': question[0],
            'answers': page_obj,
            'page': page,
            'form': form,
            'tags': tags,
            'num_q': num_quest,
            'popular_tags': popular_tags,
            'best_members': best_members
        })
Example #29
0
def answers():
    form = AnswerForm()
    if form.validate_on_submit and request.method == 'POST':
        q_id = request.args.get('q_id')
        q_obj = FilQuestions.query.filter(FilQuestions.id == q_id).first()
        q_obj.ans_text = form.answer.data
        db.session.commit()
        return redirect(url_for('answers'))

    all_quest = current_user.ans_part.all()
    print(all_quest)
    return render_template('que_to_be_ansd.html',
                           form=form,
                           questions=all_quest)
Example #30
0
def assessment():
    assessment: Assessment = Assessment.get_new_assessment(current_user.id)
    
    if assessment is None:
        flash("No more assessments!")
        return redirect(url_for('index' ))

    userAssessment: UserAssessment = UserAssessment.query.filter_by(user_id=current_user.id, assessment_id=assessment.id).first()
    answer_form = AnswerForm()

    if answer_form.validate_on_submit():
        if answer_form.answer.data == assessment.answer:
            flash("Correct!")
            userAssessment.completed = True
            userAssessment.correct = True
        else:
            flash("Incorrect!")
            userAssessment.completed = True
            userAssessment.correct = False

        db.session.commit()
        return redirect(url_for('assessment'))

    return render_template('AssessmentPage.html', assessment=assessment, answer_form=answer_form)
Example #31
0
def question(request, qid):
    question = Question.objects.select_related().get(id=qid)
    if request.method == 'GET':
        form = AnswerForm()
    elif request.method == 'POST':
        form = AnswerForm(data=request.POST)
        if form.is_valid():
            answer = form.save(commit=False)
            answer.author = request.user.profile
            answer.question = question
            answer.save()
            form = AnswerForm()
    answers = question.answer_set.order_by('-rating').all()
    answers_per_page = paginate(answers, request)
    return render(request, 'question.html', {
        'question': question,
        'answers': answers_per_page,
        'form': form,
    })