我可以使用POST方法重定向吗?

时间:2019-11-19 09:41:58

标签: django django-forms django-templates django-views django-urls

在我的网站上,用户可以回答问题。如果用户单击(获取请求)某个问题,则会调用question_detail视图,并将该问题与问题对象放在一起。如果用户单击“提交”按钮,则POST请求将发送到呈现问题_HTML_HTML的同一问题/数据库视图。在此模板上,用户可以提交由add_comment_to_question视图处理的评论表单。提交评论后,我希望将用户重定向回相同的question_detail_solution.html模板。将相同的上下文传递到模板中很重要。我可以使用add_comment_to_question中的POST方法进行重定向,这是最佳做法吗?还是我应该定义另一个呈现Question_detail_solution.html的视图,并从question_detail(POST)和add_comment_to_question重定向到该视图?或者是其他东西?谢谢您的回答!

def question_detail(request, pk):
    question = get_object_or_404(Question, pk=pk)
    user_profile = Profile.objects.get(user=request.user)
    solved_questions = user_profile.solved_questions.all()
    if request.method == 'GET':
        context = {'question':question}
        return render(request, 'question_detail.html', context)
    else:
        try:
            answer = int(request.POST['choice'])
            is_correct = question.choice_set.get(id=answer).correct

            if is_correct:
                user_profile.solved_questions.add(question)

            form = CommentForm()

            context = {'question':question, 'answer':answer, 'correct':is_correct,
            'form':form}
            return render(request, 'question_detail_solution.html', context)
        except KeyError:
            messages.error(request, "Please make a choice!")
            context = {'question': question}
            return render(request, 'question_detail.html', context)

def add_comment_to_question(request, pk):
    question = get_object_or_404(Question, pk=pk)
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.question = question
            comment.author = request.user
            comment.save()
            return redirect('question_detail', pk=question.id)
    else:
        return HttpResponse("sth is wrong")

0 个答案:

没有答案