2013-03-08 88 views
10

我很困惑我有这个问题,我希望有人能指出我的错误。Django:POST方法后重定向到当前页面显示重新发布警告

我在views.py中有一个方法,它绑定到一个具有表单的模板。代码如下所示:

def template_conf(request, temp_id): 
    template = ScanTemplate.objects.get(id=int(temp_id)) 
    if request.method == 'GET': 
     logging.debug('in get method of arachni.template_conf')  
     temp_form = ScanTemplateForm(instance=template)) 
     return render_response(request, 'arachni/web_scan_template_config.html', 
           { 
           'template': template, 
           'form': temp_form, 
           }) 
    elif request.method == 'POST': 
     logging.debug('In post method') 
     form = ScanTemplateForm(request.POST or None, instance=template) 
     if form.is_valid(): 
      logging.debug('form is valid') 
      form.save() 
      return HttpResponseRedirect('/web_template_conf/%s/' %temp_id) 

此页面的行为是这样的:当我按下“提交”按钮,程序进入POST分公司,并成功地执行在分支机构的一切。然后HttpResponseRedirect只重定向到当前页面(该url是当前网址,我认为应该等于.)。之后,GET分支自我重定向到当前页面后被执行,并且页面成功返回。但是,如果我刷新页面,此时,浏览器返回一个确认警告:

The page that you're looking for used information that you entered. 
Returning to that page might cause any action you took to be repeated. 
Do you want to continue? 

如果我确认,POST数据将被张贴到后端一次。看起来像浏览器仍然保存着以前的POST数据。我不知道为什么会发生这种情况,请帮助。谢谢。

+0

+1我有完全相同的问题。我有类似的代码,但它似乎只能在Firefox中正常工作。 – 2013-03-08 16:21:45

+0

@KevinDiTraglia:哦,我以前没有尝试过Firefox,但看起来像firefox做的工作。很奇怪...... – 2013-03-08 16:26:36

+0

@KevinDiTraglia这是Chrome 25中的一个错误,请参阅下面的答案。 – Alasdair 2013-03-10 15:33:48

回答

2

如果您的表单操作设置为“。”,则不需要执行重定向。浏览器警告不在您控制范围内以覆盖。您的代码可以大大简化:

# Assuming Django 1.3+ 
from django.shortcuts import get_object_or_404, render_to_response 

def template_conf(request, temp_id): 
    template = get_object_or_404(ScanTemplate, pk=temp_id) 
    temp_form = ScanTemplateForm(request.POST or None, instance=template) 

    if request.method == 'POST': 
     if form.is_valid(): 
      form.save() 
      # optional HttpResponseRedirect here 
    return render_to_response('arachni/web_scan_template_config.html', 
      {'template': template, 'form': temp_form}) 

这将简单地坚持您的模型并重新呈现视图。如果您想在拨打.save()后做一个HttpResponse重定向到不同的视图,那么这不会导致浏览器警告您必须重新提交POST数据。

此外,对于您将重定向到的URL模式进行硬编码并不需要,也不是好习惯。使用django.core.urlresolvers中的reverse方法。如果你的URL需要改变,它会让你的代码更容易重构。

+0

非常感谢您的建议。学到了很多。一个问题:在Django 1.4中是“渲染”方法吗?我目前正在安装1.3。 – 2013-03-08 18:37:09

+0

是的,render仅在1.4.x +中可用。如果您使用1.3,则需要使用render_to_response。 – Brandon 2013-03-08 18:40:44

+0

我已经更新了Django 1.3.x兼容代码示例 – Brandon 2013-03-08 18:43:04

7

看起来您正遇到Chrome 25中的错误(请参阅Chromium issue 177855),该错误正在处理错误地重定向。它已在Chrome 26中修复。

您的原始代码是正确的,但可以按照Brandon的建议稍微简化。我建议你redirect after a successful post request,因为它可以防止用户意外地重新提交数据(除非他们的浏览器有错误!)。

+0

回答这个问题永远不会太晚!感谢您的信息和我的代码确认。 +1 – 2013-03-11 03:03:30

相关问题