Django:POST方法显示重新发布警告后重定向到当前页面

Sha*_*ang 10 django post redirect

我对这个问题很困惑,我希望有人可以指出我的错误.

我在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)
Run Code Online (Sandbox Code Playgroud)

这个页面的行为是这样的:当我按下"提交"按钮时,程序进入POST分支,并成功执行分支中的所有内容.然后HttpResponseRedirect唯一重定向到当前页面(该url是当前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?
Run Code Online (Sandbox Code Playgroud)

如果我确认,帖子数据将再次发布到后端.好像浏览器仍然保留以前的POST数据.我不知道为什么会这样,请帮忙.谢谢.

Ala*_*air 7

您似乎遇到了Chrome 25中的错误(请参阅Chromium issue 177855),该错误正在处理重定向错误.它已在Chrome 26中修复.

你的原始代码是正确的,尽管它可以像布兰登所暗示的那样略微简化.我建议您在成功发布请求后进行 重定向,因为它可以防止用户意外重新提交数据(除非他们的浏览器有错误!).


Bra*_*don 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})
Run Code Online (Sandbox Code Playgroud)

这将简单地保留您的模型并重新渲染视图。如果您想在调用后将HttpResponse 重定向到不同的.save()视图,则不会导致浏览器警告您必须重新提交 POST 数据。

此外,没有必要对要重定向到的 URL 模式进行硬编码,这也不是一个好的做法。使用reversedjango.core.urlresolvers 中的方法。如果您的 URL 需要更改,它将使您的代码在以后重构起来更加容易。