我对我遇到的问题感到很困惑,我希望有人可以指出我的错误。
我在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
仅重定向到当前页面(该网址是当前网址,我认为应该等于.
)。自从我重定向到当前页面后,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数据。我不知道为什么会这样,请帮忙。感谢。
答案 0 :(得分:7)
您似乎遇到了Chrome 25中的错误(请参阅Chromium issue 177855),该错误正在处理重定向错误。它已在Chrome 26中修复。
您的原始代码是正确的,尽管可以像布兰登所暗示的那样稍微简化一下。我建议你做 redirect after a successful post request,因为它可以防止用户意外重新提交数据(除非他们的浏览器有错误!)。
答案 1 :(得分: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
方法。如果您的网址需要更改,它会使您的代码更容易重构。