django - 我可以使用 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")
解决方案
推荐阅读
- android - 如何在 React Native(IOS)推送通知中添加自定义操作按钮
- c - 在一个简单的 32 位内核中混合 C 和汇编代码
- laravel - laravel - 如何设置与 hasManyThrough 的关系?
- python - 列表中最大的偶数
- laravel - 按最高hasmany排序
- javascript - 如何在 JavaScript 中使用 appendChild() 将一个 div 容器附加到另一个 div 容器?
- c# - 如何用捏缩放游戏对象?
- php - 最大功能不显示多于一条记录Mysql
- c++ - C++ 多线程程序因 BUS 错误而崩溃
- mapbox-gl-js - 在 MapboxGL 上显示的 mvt 矢量图块