确认表单重新提交 - 通过重定向修复Django

0 投票
1 回答
2536 浏览
提问于 2025-04-18 06:37

我在刷新页面或点击返回按钮时遇到了表单重新提交的错误。为了避免这个问题,在发送完请求后,我把用户重定向到一个新页面,这个页面会显示实际的内容。但是,当我在mainpage.html上点击提交按钮时,就出现了下面的错误。

错误信息: 在/startpage/处没有找到匹配的反向路径。

Reverse for 'testpage' with arguments '()' and keyword arguments '{}' not found.

views.py

from django.shortcuts import render_to_response, redirect
from django.views.decorators.csrf import csrf_exempt
from django.template import Context, RequestContext
@csrf_exempt
def mainpage(request):
    return render_to_response('mainpage.html')

@csrf_exempt
def startpage(request):
    if request.method == 'POST':
       print 'post', request.POST['username']
    else:
       print 'get', request.GET['username']
    variables = RequestContext(request,{'username':request.POST['username'],
           'password':request.POST['password']})
    #return render_to_response('startpage.html',variables)
    return redirect('testpage')

def testpage(request):
    variables = {}
    return render_to_response('startpage.html',variables)                                                           

urls.py

urlpatterns = patterns('',
    url(r'^$',mainpage),
    url(r'^startpage',startpage),

startpage.html

<html>
<head>
<head>
</head>
<body>
<input type="submit" id="test1" value="mainpage">
This is the StartPage
Entered user name ==   {{username}}
Entered password  == {{password}}
</body>
</html>

mainpage.html

<html>
<head>
</head>
<body>
This is the body
<form method="post" action="/startpage/">{% csrf_token %}
Username: <input type="text" name="username">
Password: <input type="password" name="password">
<input type="submit" value="Sign with password">
</form>
</body>
</html>

1 个回答

0

根据文档redirect可以接受以下三种类型的参数:

  1. 一个模型:会调用这个模型的get_absolute_url()函数。
  2. 一个视图名称,可能还带有参数:会使用urlresolvers.reverse来反向解析这个名称。
  3. 一个绝对或相对的URL,直接用作重定向的位置。

如果你传入一个没有以协议开头且不包含斜杠的字符串,这个参数就会被识别为名称,并传递给reverse

这里的表述可能有点误导。reverse是通过URL模式名称来查找视图的,所以当文档说它接受一个视图名称时,其实是指指向视图的URL模式的名称,而不是视图本身的名称。因为reverse会在你的urlpatterns(在urls.py文件中)查找URL模式,所以你需要把testpage添加进去,这样reverse才能找到它:

url(r'^whatever/$', testpage, name='testpage')

显然,你可以在第一个参数中放入任何你想要的模式,并且需要导入视图函数作为第二个参数。name部分就是reverse用来查找URL的依据。

撰写回答