【发布时间】:2014-04-05 07:35:35
【问题描述】:
我正在使用 Django 教程做 Tango,我已经成功完成了教程,但是我在 official Django Polls tutorial 中注意到了以下内容:
def vote(request, question_id):
p = get_object_or_404(Question, pk=question_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': p,
'error_message': "You didn't select a choice.",
})
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
这里要注意的部分是“在成功处理 POST 数据后总是返回一个 HttpResponseRedirect”。但是,在 Tango with Django 教程中:
def add_page(request, category_name_url):
context = RequestContext(request)
category_name = decode_url(category_name_url)
if request.method == 'POST':
form = PageForm(request.POST)
if form.is_valid():
page = form.save(commit=False)
try:
cat = Category.objects.get(name=category_name)
page.category = cat
except Category.DoesNotExist:
return render_to_response('rango/add_category.html', {}, context)
page.views = 0
page.save()
return category(request, category_name_url)
else:
print(form.errors)
else:
form = PageForm()
return render_to_response('rango/add_page.html',
{'category_name_url': category_name_url,
'category_name' : category_name,
'form' : form}, context)
尽管使用了 POST 数据,但请注意缺少 HttpResponseRedirect。不知道这样对不对?
我看过这里:Django HttpResponseRedirect
这里:Django: HttpResponseRedirect not working
另外,这里:Django form redirect using HttpResponseRedirect
最后在这里:Django: What is the difference b/w HttpResponse vs HttpResponseRedirect vs render_to_response
我仍然不完全了解如何使用 HttpResponseRedirect。请帮忙。
提前感谢任何回复的人。
【问题讨论】:
-
+1 因为你做了一些非常彻底的研究。 :)
-
是的,TWD 在这里显然是错误的。有谁知道他们是否接受补丁?
-
@BlueIce 我在发帖前学会了研究。我对论坛并不陌生,只是对 SO 很陌生,对于没有尽快回复,我深表歉意。我以为没有人回答我的问题,因为我没有收到电子邮件或任何东西。感谢所有伟大的回应。我不知道他们是否接受补丁。我在一个问题中提出了它。这里:github.com/leifos/tango_with_django/issues/16