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()
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)