首页 > 解决方案 > 我可以使用 POST 方法重定向吗?

问题描述

在我的网站上,用户可以回答问题。如果用户在问题上单击(GET 请求),则调用 question_detail 视图并使用问题对象渲染 question_detail.html 模板。如果用户单击提交按钮,则会将 POST 请求发送到呈现 question_detail_solution.html 的同一 question_detail 视图。在此模板上,用户可以提交由 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")

标签: djangodjango-formsdjango-templatesdjango-viewsdjango-urls

解决方案


推荐阅读