def qgroup(request, qg_id): qgroup = get_object_or_404(QuestionGroup, id=qg_id) gr_key = 'qgroup__{}'.format(qg_id) collected = request.session.get(gr_key, default={}) form = None if request.method == 'POST': form = AnswerForm(request.POST) if form.is_valid(): q = get_object_or_404(Question, id=form.cleaned_data['question_id']) answer = get_object_or_404(Answer, id=form.cleaned_data['answer']) collected[str(q.id)] = [ answer.id, answer.is_right, ] request.session[gr_key] = collected if len(collected) == qgroup.question_set.count(): return redirect(reverse('result', kwargs={'qg_id': qg_id})) if collected: question = qgroup.question_set.exclude(id__in=collected.keys()).first() else: question = qgroup.question_set.first() if not question: return redirect(reverse('result', kwargs={'qg_id': qg_id})) return render(request, 'polls/qgroup.html', { 'form': form, 'qgroup': qgroup, 'question': question, })
def get_answer(request): form = AnswerForm(request.POST or None) if request.method == "POST": if form.is_valid(): answer_text = form.cleaned_data["answer_text"] date_added = form.cleaned_data["date_added"] question = form.cleaned_data["question"] Answer.objects.create(answer_text=answer_text, date_added=date_added, question=question) return HttpResponse("IT WORKED") return render(request, template_name="my_name.html", context={"form": form})
def question(request, question_id): context = {} try: question_ = Question.objects.get(pk=question_id) except ObjectDoesNotExist: raise Http404 form = AnswerForm() user = get_authenticate_user(request) answers = Logic.get_order(question=question_) last_month = datetime.today() - timedelta(days=90) # tags = Tag.objects.annotate( # Tags=Count('question__tags')).order_by('-Tags').filter(question__created__gte=last_month)[:10] # users = CustomUser.objects.annotate( # Users=Count('question__author', distinct=True)).order_by('-Users').filter(question__created__gte=last_month)[:10] page = paginate(request, answers) if user: if request.method == 'POST': form = AnswerForm(request.POST) if form.is_valid(): answer = Answer.objects.create( author=user, content=form.cleaned_data.get('content'), created=datetime.now(), question=question_) answer.save() context.update({'anchor': answer.id}) answers = Logic.get_order(question=question_) page_number = 1 for index, item in enumerate(answers): if item.id == answer.id: page_number = ((index + 1) / 5) + 1 paginator = Paginator(answers, 5) page = paginator.page(page_number) context.update({'question': question_, 'answer_list': page, 'user': user, }) response = render(request, 'questions.html', context) return response