我正在使用Django教程进行探戈,我已经成功完成了教程,但是我在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 HttpResponseRedirect vs render_to_response - how to get a login form to behave the way I need it to
另外,这里:Django form redirect using HttpResponseRedirect
最后这里:Django: What is the difference b/w HttpResponse vs HttpResponseRedirect vs render_to_response
我仍然不完全理解如何使用httpresponseredirect。求你了,救命。
提前感谢任何回应的人。

最佳答案

这是防止用户在处理服务器端的初始POST请求后重新提交表单的常见做法。
如果在处理post请求后不使用httpresponseredirect,可能会导致无意中将多个重复行插入数据库或多次发送确认电子邮件等。

09-17 12:47