Esempio n. 1
0
def guess(request, pk):
    form = AnswerForm(request.POST)
    puzzle = get_object_or_404(Puzzle.objects.select_for_update(), pk=pk)

    status_code = 200
    if form.is_valid() and puzzle.status != Puzzle.SOLVED:
        answer_text = __sanitize_guess(form.cleaned_data["text"])
        # If answer has already been added to the queue
        answer, created = Answer.objects.get_or_create(text=answer_text,
                                                       puzzle=puzzle)
        if created:
            puzzle.status = Puzzle.PENDING
            puzzle.save()
        else:
            return JsonResponse(
                {
                    "error":
                    '"%s" has already been submitted as a guess for puzzle "%s"'
                    % (answer_text, puzzle.name)
                },
                status=400,
            )
    else:
        return JsonResponse(
            {
                "error":
                'Answer form was invalid or puzzle was already solved for puzzle "%s"'
                % puzzle.name
            },
            status=400,
        )

    return JsonResponse({}, status=status_code)
Esempio n. 2
0
 def test_all_fields_required(self):
     form = AnswerForm(data={'user': '', 'content': '', 'question': ''})
     self.assertFalse(form.is_valid())
     user_error = str(form.errors['user'].as_data()[0].message)
     self.assertEqual(user_error, 'This field is required.')
     content_error = str(form.errors['content'].as_data()[0].message)
     self.assertEqual(content_error, 'This field is required.')
     question_error = str(form.errors['question'].as_data()[0].message)
     self.assertEqual(question_error, 'This field is required.')
Esempio n. 3
0
 def add_answer_to_question(request, 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.user_id = request.user.id
             answer.save()
Esempio n. 4
0
 def test_invalid_form_returns_error(self):
     self.client.post(reverse('account:login'), self.credentials)
     form = AnswerForm(data={'user': '', 'content': '', 'question': ''})
     response = self.client.post(reverse('answers:create_answer'),
                                 data={'answer_form': form})
     self.assertEqual(response.status_code, 400)
     response_message = response.json()['response']
     self.assertEqual(response_message, 'Invalid Answer')
Esempio n. 5
0
    def get(self, request, *args, **kwargs):
        # anonymous users cannot be used in fitler clause,
        # therefore assign None
        user = self.request.user if self.request.user.is_authenticated else None
        voted_for_question = (Question.objects
                                      .filter(votes__voter=user,
                                              votes__object_id=OuterRef('pk')))
        question_query = (Question.objects
                                  .select_related('user')
                                  .annotate(num_votes=Count('votes'),
                                            voted=Exists(voted_for_question)))
        question = get_object_or_404(question_query, slug=kwargs['slug'])
        question.num_views += 1
        question.save()

        answer_form_initial = {'question': question, 'user': self.request.user}
        context = {'vote_form': VoteForm(),
                   'answer_form': AnswerForm(initial=answer_form_initial),
                   'question': {'question': question, 'comments': []},
                   'answers': []}

        # get the comments for the question
        voted_for_comment = (Comment.objects
                                    .filter(votes__voter=user,
                                            votes__object_id=OuterRef('pk')))
        comment_query = (question.comments
                                 .prefetch_related('commenter')
                                 .annotate(num_votes=Count('votes'),
                                           voted=Exists(voted_for_comment))
                                 .order_by('created_at'))
        for comment in comment_query:
            context['question']['comments'].append(comment)

        # get the answers for the question
        voted_for_answer = (Answer.objects
                                  .filter(votes__voter=user,
                                          votes__object_id=OuterRef('pk')))
        answers = (Answer.objects
                         .prefetch_related('user')
                         .filter(question=question)
                         .annotate(num_votes=Count('votes'),
                                   voted=Exists(voted_for_answer))
                         .order_by('-accepted', '-num_votes', '-created_at'))
        for answer in answers:
            comments = []
            # get the comments for each answer
            comment_query = (answer.comments
                                   .prefetch_related('commenter')
                                   .annotate(num_votes=Count('votes'),
                                             voted=Exists(voted_for_comment))
                                   .order_by('created_at'))
            for comment in comment_query:
                comments.append(comment)
            # append this answer along with all its comments to context
            context['answers'].append({'answer': answer, 'comments': comments})

        return self.render_to_response(context)
Esempio n. 6
0
 def get_context_data(self, **kwargs):
     context = super(QuestionDisplay, self).get_context_data(**kwargs)
     Q = get_object_or_404(Question, pk=self.kwargs['pk'])
     self.questions_tags = Tag.objects.prefetch_related("question").filter(
         question=Q)
     self.questions_comments = Question.objects.prefetch_related(
         "question_comment").get(id=Q.pk)
     context['answer_form'] = AnswerForm()
     context['answer_comment_form'] = AnswerCommentForm()
     context['question_comment_form'] = QuestionCommentForm()
     context['questionstags'] = self.questions_tags
     context[
         'question_comments'] = self.questions_comments.question_comment.all(
         )
     return context
Esempio n. 7
0
def questions_detail(request, slug=None):
    question = Question.objects.filter(slug=slug).first()

    if not question:
        raise Http404

    try:
        for u_id in question.reputation_str.split(','):
            if int(u_id) > 0:
                question.reputation_count += 1
            elif int(u_id) < 0:
                question.reputation_count -= 1
            question.reputation_set.add(int(u_id))
    except:
        pass

    answers = question.answers
    answer_form = AnswerForm(request.POST or None)

    if request.method == 'POST':

        user = User.objects.filter(id=request.user.id).first()

        if user is None or user.is_authenticated == False:
            messages.error(request,
                           'Please Login before you perform this action')
            return redirect('%s?next=%s' % (LOGIN_URL, request.path))

        if not user.has_perm('answers.add_answer'):
            messages.error(
                request,
                'You have no permission to add answers. Please contact your admin.'
            )
            return redirect('%s?next=%s' % (LOGIN_URL, request.path))

        if answer_form.is_valid():
            answer = answer_form.save(commit=False)
            answer.user = request.user
            answer.question = question

            try:
                parent_id = int(request.POST.get('parent_id', None))
            except:
                parent_id = None
            if parent_id:
                parent_qs = Answer.objects.filter(id=parent_id)
                if parent_qs.exists() and parent_qs.count() == 1:
                    answer.parent = parent_qs.first()
                    answer.save()
                    messages.success(request, 'Reply added.')
                    return redirect(question.get_absolute_url())
                else:
                    return HttpResponse(
                        f'Multiple Answers with id: {parent_id}', status=500)

            answer.save()
            messages.success(request, 'Answer added.')
            return redirect(question.get_absolute_url())
        else:
            messages.error(request, 'Failed to add answer.')

    context = {
        'title': question.title,
        'question': question,
        'answers': answers,
        'answer_form': answer_form,
    }

    return render(request, 'question_detail.html', context)
Esempio n. 8
0
 def test_valid_form(self):
     question = Question.objects.first()
     form = AnswerForm(data={'user': self.user.id,
                             'content': 'test answer',
                             'question': question.id})
     self.assertTrue(form.is_valid())