Ejemplo n.º 1
0
def question_details(request, question_key):
    ctx = {}

    question = get_object_or_404(Question, key=question_key)

    if request.method == 'POST':
        user = users.get_current_user()
        if user is None:
            return redirect(users.create_login_url(request.path))

        initial = {
            'author': users.get_current_user(),
            'question': question,
        }
        form = AnswerForm(request.POST, initial=initial)
        if form.is_valid():
            # XXX FIXME - why initial data does not exist in cleaned data?
            form.cleaned_data.update(initial)

            form.save()

            return redirect(reverse('questions_question_list'))
        ctx['answer_form'] = form

    else:
        ctx['answer_form'] = AnswerForm()


    ctx['question'] = question
    return render(request, 'questions/question_details.html', ctx)
Ejemplo n.º 2
0
def edit_answer(request, question_id, answer_id):
    """Edit an answer."""
    answer = get_object_or_404(Answer, pk=answer_id, question=question_id)
    answer_preview = None
    if answer.question.is_locked:
        raise PermissionDenied

    # NOJS: upload images, if any
    upload_imageattachment(request, answer)

    if request.method == 'GET':
        form = AnswerForm({'content': answer.content})
        return jingo.render(request, 'questions/edit_answer.html',
                            {'form': form, 'answer': answer})

    form = AnswerForm(request.POST)

    if form.is_valid():
        answer.content = form.cleaned_data['content']
        answer.updated_by = request.user
        if 'preview' in request.POST:
            answer.updated = datetime.now()
            answer_preview = answer
        else:
            log.warning('User %s is editing answer with id=%s' %
                        (request.user, answer.id))
            answer.save()
            return HttpResponseRedirect(answer.get_absolute_url())

    return jingo.render(request, 'questions/edit_answer.html',
                        {'form': form, 'answer': answer,
                         'answer_preview': answer_preview})
Ejemplo n.º 3
0
async def answer_create(request):
    """
    Answer form
    """
    id = int(request.query_params['next'].split('/')[2])
    next = request.query_params['next']
    results = (
        await Question.get(id=id)
        .prefetch_related("user", "tags")
    )
    session_user = request.user.username
    data = await request.form()
    form = AnswerForm(data)
    result = await User.get(username=session_user)
    if request.method == "POST" and form.validate():
        query = Answer(
            content=form.content.data,
            created=datetime.datetime.now(),
            answer_like=0,
            is_accepted_answer=0,
            question_id=results.id,
            ans_user_id=result.id,
        )
        await query.save()
        return RedirectResponse(BASE_HOST + next, status_code=302)
    return templates.TemplateResponse(
        "questions/answer_create.html", {
            "request": request,
            "form": form,
            "next": next
        }
    )
Ejemplo n.º 4
0
def edit_answer(request, answer_id):
    existing_answer = get_object_or_404(Answer, pk=answer_id, can_delete=True)

    if not request.user == existing_answer.user and \
       not request.user.has_perm('answers.change_answer'):
        raise PermissionDenied

    if request.method == 'POST':
        if request.user == existing_answer.user:
            modified_answer = DisabledAnswerForm(request.POST,
                                                 instance=existing_answer)
        else:
            modified_answer = AnswerForm(request.POST,
                                         instance=existing_answer)
        modified_answer.save()
        return HttpResponseRedirect(reverse('answers:show',
                                            args=(answer_id, )))
    else:
        existing_answer = get_object_or_404(Answer, pk=answer_id)
        if request.user == existing_answer.user:
            form = DisabledAnswerForm(instance=existing_answer)
        else:
            form = AnswerForm(instance=existing_answer)
        context = {'form': form, 'answer_id': answer_id}
        return render(request, 'answers/new.html', context)
Ejemplo n.º 5
0
Archivo: views.py Proyecto: tantek/kuma
def edit_answer(request, question_id, answer_id):
    """Edit an answer."""
    answer = get_object_or_404(Answer, pk=answer_id, question=question_id)
    answer_preview = None
    if answer.question.is_locked:
        raise PermissionDenied

    # NOJS: upload images, if any
    upload_imageattachment(request, answer)

    if request.method == 'GET':
        form = AnswerForm({'content': answer.content})
        return jingo.render(request, 'questions/edit_answer.html',
                            {'form': form, 'answer': answer})

    form = AnswerForm(request.POST)

    if form.is_valid():
        answer.content = form.cleaned_data['content']
        answer.updated_by = request.user
        if 'preview' in request.POST:
            answer.updated = datetime.now()
            answer_preview = answer
        else:
            log.warning('User %s is editing answer with id=%s' %
                        (request.user, answer.id))
            answer.save()
            return HttpResponseRedirect(answer.get_absolute_url())

    return jingo.render(request, 'questions/edit_answer.html',
                        {'form': form, 'answer': answer,
                         'answer_preview': answer_preview})
Ejemplo n.º 6
0
def question_detail_view(request, pk):
    def _run_business_logic(question, answer_form, user):
        print("calling")
        print(question)
        print(answer_form.cleaned_data['answer'])
        print(user)
        answer_business = AnswerQuestion(
            question,
            answer_form.cleaned_data['answer'],
            user,
        )
        #        answer_business.execute_answer()
        try:
            answer_business.execute_answer()
            print("f")
        except Exception as err:
            print("ff")
            pass

    question = get_object_or_404(Question, pk=pk)

    if request.method == 'POST':
        answer_form = AnswerForm(request.POST or None)
        if answer_form.is_valid():
            print(question)
            _run_business_logic(question, answer_form, request.user)
            question.answered()

    answer_form = AnswerForm
    return render(request, 'question_detail.html', {
        'answer_form': answer_form,
        'question': question
    })
Ejemplo n.º 7
0
async def answer_create(request):
    """
    Answer form
    """
    request_path_id = int(request.query_params["next"].split("/")[2])
    request_query_next = request.query_params["next"]
    data = await request.form()
    form = AnswerForm(data)
    u = User
    session_user = (
        await u.select(u.id, u.username)
        .where(u.username == request.user.username)
        .first()
        .run()
    )
    if request.method == "POST" and form.validate():
        query = Answer(
            content=form.content.data,
            created_at=datetime.datetime.now(),
            answer_like=0,
            is_accepted_answer=0,
            question=request_path_id,
            ans_user=session_user["id"],
        )
        await query.save().run()
        return RedirectResponse(
            BASE_HOST + request_query_next, status_code=302
        )
    return templates.TemplateResponse(
        "questions/answer_create.html",
        {"request": request, "form": form, "next": request_query_next},
    )
Ejemplo n.º 8
0
def create_answer(request, question_id):
    form = AnswerForm(request.POST)
    new_answer = form.save(commit=False)
    new_answer.date = datetime.datetime.now()
    question = get_object_or_404(Question, pk=question_id)
    new_answer.question = question
    new_answer.user = request.user
    new_answer.save()
    return redirect('questions:show', question_id)
Ejemplo n.º 9
0
def create_answer(request):
    if request.method == 'POST':
        form = AnswerForm(request.POST)
        if form.is_valid():
            return redirect("/")
    else:
        form = AnswerForm()

    context = {'form': form}
    context = add_user(request, context)
    return render(request, "form.html", context)
Ejemplo n.º 10
0
 def post(self, request, question_id):
     form = AnswerForm(request.POST)
     if form.is_valid():
         answer = Answer(
             text=form.cleaned_data["text"],
             question_id=question_id,
             author=request.user,
         )
         answer.save()
         return redirect("question", question_id)
     context = {
         'answer_form': form,
     }
     return render(request, 'questions/question.html', context)
Ejemplo n.º 11
0
def question(request, pk):
    question = get_object_or_404(Question, pk=pk)
    form = AnswerForm(initial={'question': question})
    return render(request, 'questions/question.html', {
        'question': question,
        'form': form
    })
Ejemplo n.º 12
0
def add_answer(request, pk):
    context = RequestContext(request)
    registered = False
    if request.method == 'POST':
        answer_form = AnswerForm(data=request.POST, initial={'user': request.user, 'question': pk})
        if answer_form.is_valid():
            answer_form.instance.user = request.user
            answer_form.instance.question = Question.objects.get(id=pk)
            answer_form.save()
            registered = True
        else:
            print answer_form.errors
    else:
        answer_form = AnswerForm()
    return render(request, 'answer/new.html', {
            'answer_form': answer_form, 'registered': registered, 'question': Question.objects.get(id=pk) })
Ejemplo n.º 13
0
 def get_context_data(self, **kwargs):
     context = super(QuestionDetail, self).get_context_data(**kwargs)
     context['form'] = AnswerForm(initial={
         'question': self.object,
         'author': self.request.user
     })
     return context
Ejemplo n.º 14
0
def new_answer(request, question_id):
    if request.user.is_authenticated():
        form = AnswerForm()
        context = {'form': form, 'question_id': question_id}
        return render(request, 'questions/answers/new.html', context)
    else:
        return redirect('accounts:sign_in')
Ejemplo n.º 15
0
Archivo: views.py Proyecto: tantek/kuma
def _answers_data(request, question_id, form=None, watch_form=None,
                  answer_preview=None):
    """Return a map of the minimal info necessary to draw an answers page."""
    question = get_object_or_404(Question, pk=question_id)
    answers_ = paginate(request, question.answers.all(),
                        per_page=constants.ANSWERS_PER_PAGE)
    vocab = [t.name for t in Tag.objects.all()]  # TODO: Fetch only name.
    feed_urls = ((reverse('questions.answers.feed',
                          kwargs={'question_id': question_id}),
                  AnswersFeed().title(question)),)
    frequencies = dict(FREQUENCY_CHOICES)

    is_watching_question = (
        request.user.is_authenticated() and (
        QuestionReplyEvent.is_notifying(request.user, question) or
        QuestionSolvedEvent.is_notifying(request.user, question)))
    return {'question': question,
            'answers': answers_,
            'form': form or AnswerForm(),
            'answer_preview': answer_preview,
            'watch_form': watch_form or _init_watch_form(request, 'reply'),
            'feeds': feed_urls,
            'tag_vocab': json.dumps(vocab),
            'frequencies': frequencies,
            'is_watching_question': is_watching_question,
            'can_tag': request.user.has_perm('questions.tag_question'),
            'can_create_tags': request.user.has_perm('taggit.add_tag')}
Ejemplo n.º 16
0
def QuestionsPage(request):
    if request.user.registered:
        if request.user.user_profile.win == True:
            return redirect(reverse('win_page'))
        else:
            if request.method == 'GET':
                try:
                    question = Question.objects.get(current=True)
                except ObjectDoesNotExist:
                    request.user.user_profile.win = True
                    request.user.user_profile.save()
                    return redirect(reverse('win_page'))
                answer_form = AnswerForm()
                return render(request,'Questions/questionspage.html',{"question":question,"answer_form":answer_form})
            elif request.method == 'POST':
                question = Question.objects.get(current=True)
                answer_form=AnswerForm(request.POST,request.FILES)
                if answer_form.is_valid():
                    recieved_file = request.FILES['file']
                    sample_file = open(os.path.join(settings.BASE_DIR,'files/output/'+question.title+".txt"), 'rb')
                    flag = True
                    line1 = recieved_file.readline()
                    
                    line2 = sample_file.readline()
                    while line1 != bytes('#','utf-8') or line2 != bytes('#','utf-8'):
                        print(line1,line2)
                        if line1 != line2:
                            flag = False
                            break
                        line1 = recieved_file.readline()
                        line2 = sample_file.readline()
                    print(flag)
                    sample_file.close
                    if flag:
                        request.user.user_profile.win = True
                        request.user.user_profile.time_counter = int(format(datetime.now(), 'U'))
                        request.user.user_profile.save()
                        return redirect(reverse('win_page'))
                    else:
                        answer_form.add_error('file',"Oops, This is not the answer we expected")
                        return render(request,'Questions/questionspage.html',{"question":question,"answer_form":answer_form})
                else:
                    return render(request,'Questions/questionspage.html',{"question":question,"answer_form":answer_form})
                    
    else:
        return redirect(reverse('register_page'))
Ejemplo n.º 17
0
def answer(request):
    if request.method == 'POST':
        form = AnswerForm(request.POST)
        if form.is_valid():
            user = request.user
            answer = Answer()
            answer.user = request.user
            answer.question = form.cleaned_data.get('question')
            answer.description = form.cleaned_data.get('description')
            answer.save()
            user.profile.notify_answered(answer.question)
            return redirect(u'/questions/{0}/'.format(answer.question.pk))
        else:
            question = form.cleaned_data.get('question')
            return render(request, 'questions/question.html', {'question': question, 'form': form})
    else:
        return redirect('/questions/')
Ejemplo n.º 18
0
def update_answer(request, answer_id):
    answer = get_object_or_404(Answer, pk=answer_id)

    if not request.user == answer.user:
        return redirect('questions:show', answer.question)

    form = AnswerForm(request.POST)

    if form.is_valid():
        answer.date_updated = datetime.datetime.now()
        answer.text = form.cleaned_data['text']
        answer.save()

        return redirect('questions:show', answer.question.id)

    context = {'form': form}
    return render(request, 'questions:edit_answer', context)
Ejemplo n.º 19
0
def handle_answer_submission(request, question):
    candidates = Candidate.objects.filter(member__id=request.user.id)
    if not candidates.exists():
        return redirect('questions:answers', pk=question.id)
    candidate = candidates.get()
    if Answer.objects.filter(
            candidate=candidate,
            question=question).exclude(status='rejected').exists():
        return redirect('questions:answers', pk=question.id)
    form = AnswerForm(request.POST)
    if not form.is_valid():
        return show_answers(request, question, form)
    answer = form.save(commit=False)
    answer.candidate = candidate
    answer.question = question
    answer.save()
    return redirect('questions:answers', pk=question.id)
Ejemplo n.º 20
0
def answer(request):
    if request.method == 'POST':
        form = AnswerForm(request.POST)
        if form.is_valid():
            user = request.user
            answer = Answer()
            answer.user = request.user
            answer.question = form.cleaned_data.get('question')
            answer.description = form.cleaned_data.get('description')
            answer.save()
            user.profile.notify_answered(answer.question)
            return redirect(u'/questions/{0}/'.format(answer.question.pk))
        else:
            question = form.cleaned_data.get('question')
            return render(request, 'questions/question.html', {'question': question, 'form': form})
    else:
        return redirect('/questions/')
Ejemplo n.º 21
0
def answers(request, question_id):
    # Could possibly use get_object_or_404 here
    question = Question.objects.get(pk = question_id)

    form = AnswerForm()
    if request.method == "POST":
        username = None
        form = AnswerForm(request.POST)
        if request.user.is_authenticated():
            username = request.user.username
            if form.is_valid():
                body = form.cleaned_data['body']

                user = User.objects.get(username=username)

                Answer.objects.create(body=body, user=user, answer_to=question)

                # No redirecting, just refreshing same page.

            else:
                form = AnswerForm()

    answers = reversed(Answer.objects.filter(answer_to=question).order_by('created_at'))
    context = {'question': question, 'answers': answers}  # Including one question and zero or more answers
    return render(request, 'answers.html', context, {'form': form, })
Ejemplo n.º 22
0
def answer_update(request, slug=None, pk=None):
    question = get_object_or_404(Question, slug=slug)
    instance = get_object_or_404(Answer, pk=pk)
    if instance.user != request.user:
        raise Http404
    else:
        form = AnswerForm(request.POST or None, instance=instance)
        if form.is_valid():
            answer = form.save(commit=False)
            answer.user = request.user
            answer.question = question
            answer.save()
            # messages.success(request, 'Answer was Updated.')
            return redirect(question.get_absolute_url())
        context = {"form": form,
                   "title": "Update Answer"
                   }
    return render(request, "questions/answer.html", context)
Ejemplo n.º 23
0
 def get(self, request, question_id):
     question = Question.objects.get(id=question_id)
     answers = question.answer_set.order_by('created_at').all()
     context = {
         'question': question,
         'answers': answers,
         "answer_form": AnswerForm(),
     }
     return render(request, 'questions/question.html', context)
Ejemplo n.º 24
0
def edit_answer(request, answer_id):
    answer = get_object_or_404(Answer, pk=answer_id)

    if not request.user == answer.user:
        return redirect('questions:show', answer.question)

    form = AnswerForm(instance=answer)
    context = {'form': form, 'question': answer.question, 'answer': answer}
    return render(request, 'answers/edit.html', context)
Ejemplo n.º 25
0
def reply(request, question_id):
    """Post a new answer to a question."""
    question = get_object_or_404(Question, pk=question_id)
    answer_preview = None
    if question.is_locked:
        raise PermissionDenied

    form = AnswerForm(request.POST)

    # NOJS: delete images
    if 'delete_images' in request.POST:
        for image_id in request.POST.getlist('delete_image'):
            ImageAttachment.objects.get(pk=image_id).delete()

        return answers(request, question_id=question_id, form=form)

    # NOJS: upload image
    if 'upload_image' in request.POST:
        upload_imageattachment(request, question)
        return answers(request, question_id=question_id, form=form)

    if form.is_valid():
        answer = Answer(question=question, creator=request.user,
                        content=form.cleaned_data['content'])
        if 'preview' in request.POST:
            answer_preview = answer
        else:
            answer.save()
            ct = ContentType.objects.get_for_model(answer)
            # Move over to the answer all of the images I added to the
            # reply form
            up_images = question.images.filter(creator=request.user)
            up_images.update(content_type=ct, object_id=answer.id)
            statsd.incr('questions.answer')

            if Setting.get_for_user(request.user,
                                    'questions_watch_after_reply'):
                QuestionReplyEvent.notify(request.user, question)

            return HttpResponseRedirect(answer.get_absolute_url())

    return answers(request, question_id=question_id, form=form,
                   answer_preview=answer_preview)
Ejemplo n.º 26
0
def reply(request, question_id):
    """Post a new answer to a question."""
    question = get_object_or_404(Question, pk=question_id)
    answer_preview = None
    if question.is_locked:
        raise PermissionDenied

    form = AnswerForm(request.POST)

    # NOJS: delete images
    if 'delete_images' in request.POST:
        for image_id in request.POST.getlist('delete_image'):
            ImageAttachment.objects.get(pk=image_id).delete()

        return answers(request, question_id, form)

    # NOJS: upload image
    if 'upload_image' in request.POST:
        upload_imageattachment(request, question)
        return answers(request, question_id, form)

    if form.is_valid():
        answer = Answer(question=question,
                        creator=request.user,
                        content=form.cleaned_data['content'])
        if 'preview' in request.POST:
            answer_preview = answer
        else:
            answer.save()
            ct = ContentType.objects.get_for_model(answer)
            # Move over to the answer all of the images I added to the
            # reply form
            up_images = question.images.filter(creator=request.user)
            up_images.update(content_type=ct, object_id=answer.id)
            statsd.incr('questions.answer')

            if Setting.get_for_user(request.user,
                                    'questions_watch_after_reply'):
                QuestionReplyEvent.notify(request.user, question)

            return HttpResponseRedirect(answer.get_absolute_url())

    return answers(request, question_id, form, answer_preview=answer_preview)
Ejemplo n.º 27
0
 def get_context_data(self, **kwargs):
     question = self.get_object()
     data = super(QuestionDetailView, self).get_context_data(**kwargs)
     data["topic_list"] = Topic.objects.all().annotate(
         question_count=Count("questions"))
     data['form'] = AnswerForm(initial={"question": self.object})
     if self.request.user.is_authenticated():
         data['user_voted'] = not question.votes.exists(
             self.request.user.id)
     else:
         data['user_voted'] = False
     return data
Ejemplo n.º 28
0
def answer(request, qid):

    #fromDB!!! 4DZ
    mainQuestion = Question.manager.get(pk=int(qid))

    userAnswers = Answer.manager.all_answers_by_question(qid)

    userAnswers = paginate(userAnswers, request, 5)

    if request.method == "POST":
        form = AnswerForm(request.POST)

        if form.is_valid():
            answer = form.save(mainQuestion, request.user)
            return HttpResponseRedirect(
                reverse('questions:answer', kwargs={'qid': mainQuestion.pk}))
    else:
        form = AnswerForm()

    topMembers = UserImaged.objects.order_by('-rating').all()[:5]

    topTags = Tag.objects.get_popular_tags()

    context = {
        'form': form,
        'mainQuestion': mainQuestion,
        'userAnswers': userAnswers,
        'topMembers': topMembers,
        'topTags': topTags
    }
    return render(request, 'answer/answer.html', context)
Ejemplo n.º 29
0
def new_answer(request, id):
    if models.Question.objects.filter(id=id).exists():
        if request.method == 'POST':
            form = AnswerForm(request.POST)
            if form.is_valid():
                #answeredQuestion = Question.objects.get_by_id(id)[0]
                answeredQuestion = get_object_or_404(models.Question, pk=id)
                answer = models.Answer.objects.create(
                    author=request.user,
                    create_date=timezone.now(),
                    text=form.cleaned_data['text'],
                    question_id=answeredQuestion.id)
                answer.save()
                return redirect('/question/{}/add_answer/'.format(id))
        else:
            form = AnswerForm()
        #return render(request, 'question/new_answer.html', {'form': form})
        return render(
            request, 'questions.html', {
                'form':
                form,
                'question':
                get_object_or_404(models.Question, pk=id),
                'answers':
                paginate(request,
                         models.Answer.objects.get_hot_for_answer(id)),
                'tags':
                paginate(request, models.Tag.objects.hottest())[:10],
                'users':
                paginate(request, models.CustomUser.objects.by_rating())[:10],
                'page_objects':
                paginate(request,
                         models.Answer.objects.get_hot_for_answer(id)),
            })
    else:
        raise Http404
Ejemplo n.º 30
0
def show_answers(request, question, form=None, current_region=None):
    is_candidate = check_candidate(request)
    candidate_answers = Answer.objects.filter(
        question__id=question.id, candidate__member__id=request.user.id)
    allow_answer = is_candidate and not candidate_answers.exclude(
        status='rejected').exists()
    has_answered = is_candidate and candidate_answers.filter(status='approved')
    answers = Answer.objects \
        .filter(question__id=question.id, status='approved') \
        .annotate(url=Concat(Value(f'{NCG_VOTING_URL}/nominate/status/'), 'candidate__candidate_code')) \
        .order_by('candidate__position', 'created_at')
    if current_region:
        answers = answers.filter(candidate__position=current_region)
    pending_answers = is_candidate and candidate_answers.filter(
        status='pending')
    rejects = candidate_answers.filter(status='rejected')
    if rejects.exists():
        reject = rejects.order_by('-created_at')[0]
    else:
        reject = None
    region_list = [
        {
            'code': None,
            'readable': 'All regions'
        },
    ]
    region_list += [{
        'code': position_tuple[0],
        'readable': position_tuple[1]
    } for position_tuple in Candidate.POSITION_CHOICES]
    current_region_readable = next(item['readable'] for item in region_list
                                   if item['code'] == current_region)
    if not form:
        form = AnswerForm()
    return render(
        request, 'questions/answers.html', {
            'allow_answer': allow_answer,
            'answers': answers,
            'current_region_code': current_region,
            'current_region_readable': current_region_readable,
            'form': form,
            'has_answered': has_answered,
            'pending_answer': pending_answers,
            'question': question,
            'reject': reject,
            'region_list': region_list,
            'vote_url': NCG_VOTING_URL,
        })
Ejemplo n.º 31
0
def question_detail(request, slug=None):
    global upvote, downvote, vote_count
    same_user = False
    upvote = False
    downvote = False
    question = get_object_or_404(Question, slug=slug)
    # votes = Vote.objects.filter(question_id=question.id)
    # vote_count = votes.filter(Q(upvote__exact=1) | Q(downvote__exact=1)).count()
    # print(vote_count)
    try:
        q = QuestionTotal.objects.get(question_id=question.id)
        vote_count = q.total
    except:
        vote_count = 0
    print(vote_count)
    answers_list = Answer.objects.filter(question=question)
    context = {"question": question,
               "answers_list": answers_list,
               "vote_count": vote_count,
               "same_user": same_user,
               "upvote": upvote,
               "downvote": downvote
               }
    if request.user.is_authenticated:
        form = AnswerForm(request.POST or None)
        if form.is_valid():
            answer = form.save(commit=False)
            answer.user = request.user
            answer.question = question
            answer.save()
            # messages.success(request, 'Answer was Posted.')
            form = AnswerForm()
        try:
            v = Vote.objects.get(question_id=question.id, user_id=request.user.id)
            if v:
                same_user = True
            else:
                same_user = False
            if v.upvote == 1 and v.downvote == 0:
                upvote = True
                downvote = False
            elif v.upvote == 0 and v.downvote == 1:
                upvote = False
                downvote = True
        except:
            same_user = False
        context = {"question": question,
                   "form": form,
                   "answers_list": answers_list,
                   "vote_count": vote_count,
                   "same_user": same_user,
                   "upvote": upvote,
                   "downvote": downvote
                   }
    return render(request, "questions/question_detail.html", context)
Ejemplo n.º 32
0
def create_answer(request):
    if request.method == 'POST':
        # Set the submission_date automatically.
        form = AnswerForm(request.POST)
        if form.is_valid():
            print form.cleaned_data
            form.save()
            return HttpResponseRedirect(reverse('answers:list'))
        else:
            context = {'form': form}
            return render(request, 'answers/new.html', context)
    else:
        form = AnswerForm()
        context = {'form': form}
        return render(request, 'answers/new.html', context)
Ejemplo n.º 33
0
def add_answer_to_question(request, username, pk):
    question = get_object_or_404(Question, pk=pk)
    if request.method == "POST":
        form = AnswerForm(request.POST)
        if form.is_valid():
            answer = form.save(commit=False)
            answer.question = question
            answer.save()
            return redirect('questions:single', username= question.user.username, pk=question.pk)
    else:
        form = AnswerForm()
        return render(request, 'questions/answer_form.html', {'form': form})
Ejemplo n.º 34
0
def question_view(request, question_id):
    question = Questions.objects.get_by_id(question_id)
    answers = Answers.objects.get_answers_by_question_id(question_id)
    if request.method == "POST":
        form = AnswerForm(request.POST)
        if form.is_valid():
            form.save(request.user, question)
        return redirect(resolve_url('question', question_id=question_id))

    else:
        form = AnswerForm(None)
    return render(
        request, 'question.html', {
            'question': question,
            'question_id': question_id,
            'answers': answers,
            'form': form
        })
Ejemplo n.º 35
0
def question(request, question_id):
    question = Question.object.get_question(question_id)
    answers = Answer.object.get_question(question_id)
    answers_on_page = paginate(answers, request, 3)

    if request.POST:
        form = AnswerForm(request.user, question, data=request.POST)
        if form.is_valid():
            answer = form.save()
            return redirect(
                reverse('question', kwargs={'question_id': question.pk}))
    else:
        form = AnswerForm(request.user, question)

    context = {'question': question, 'answers': answers_on_page, 'form': form}
    return render(request, 'question.html', context)
Ejemplo n.º 36
0
def question(request, question_id=None):
    COUNT_ON_PAGE = 30
    q = get_object_or_404(Question, id=question_id)
    if request.method == "POST":
        # Добавление ответа
        form = AnswerForm(request.user, q, request.POST)
        if form.is_valid():
            new_answer = form.save()

            async_to_sync(channel_layer.group_send)(
                "question_%s" % question_id, {
                    'id': new_answer.pk,
                    'text': new_answer.text,
                    'avatar': new_answer.user.profile.avatar.url,
                    'type': 'new_answer'
                })

            answers = q.answers.hot_answers()
            # Ищу индекс нового ответа
            index = 1
            for ans in answers:
                if ans == new_answer:
                    break
                index += 1
            page = math.ceil(index / COUNT_ON_PAGE)  # страница c новым ответом
            return HttpResponseRedirect(
                '/question/{}?page={}#answer_{}'.format(
                    question_id, page, new_answer.pk))
    else:
        form = AnswerForm(request.user, q)
    answers = q.answers.hot_answers()
    page, page_range = paginate(request,
                                answers,
                                default_limit=COUNT_ON_PAGE,
                                pages_count=7)
    return render(
        request, 'questions/question.html', {
            'question': q,
            'answers': page.object_list,
            'page': page,
            'page_range': page_range,
            'form': form
        })
Ejemplo n.º 37
0
def question(request, question_id):
    """
    Question page
    """
    data = {}

    # overlay ask form
    data['questionform'] = QuestionForm()

    # active page title
    data['active'] = 'question'

    # new answer form
    data['form'] = AnswerForm()

    # optimized question query
    q = Question.objects.filter(id=int(question_id))\
        .select_related('author',
                        'author__user', 'author__user_username',
                        'author__user_id', 'answer',
                        'answer__author', 'answer__author__user__username',
                        'answer__author__user__id',
                        )

    # check if question exists
    if len(q) == 0:
        raise Http404

    q = q[0]

    # get all answers
    query = q.answers.all().select_related('author',
                                           'author__user',
                                           'author__user_username',
                                           'author__user_id')

    # pagination
    paginator = Paginator(query, 30)
    page_number = request.GET.get('page', '1')

    try:
        page = paginator.page(page_number)
    except PageNotAnInteger:
        page = paginator.page(1)
    except EmptyPage:
        page = paginator.page(paginator.num_pages)

    data['question'] = q
    data['answers'] = page

    # new answer handling
    if request.method == 'POST':
        form = AnswerForm(request.POST)
        data['form'] = form

        if form.is_valid():
            user = request.user
            question_user = QuestionsUser.objects.filter(user=user)

            # check if user exists
            if len(question_user) == 0:
                return HttpResponseForbidden()

            # create new answer
            question_user = question_user[0]
            content = form.cleaned_data['content']
            a = Answer(author=question_user, content=content, question=q)
            a.save()

            # redirect to question page
            return redirect(q.get_absolute_url())
    q.visit()

    return render(request, "question.html", data)