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

Python 确认表单重新提交-Django通过重定向修复,python,django,Python,Django,当我刷新页面或“提交回”按钮时,我收到一个表单重新提交错误。为了防止在post请求后出现此错误,我将其重定向到一个新页面,该页面将显示实际页面…当我这样做时…在单击mainpge.html上的“提交”按钮后,我收到以下错误 错误: NoReverseMatch at/startpage/ Reverse for 'testpage' with arguments '()' and keyword arguments '{}' not found. views.py from django.sh

当我刷新页面或“提交回”按钮时,我收到一个表单重新提交错误。为了防止在post请求后出现此错误,我将其重定向到一个新页面,该页面将显示实际页面…当我这样做时…在单击mainpge.html上的“提交”按钮后,我收到以下错误

错误: NoReverseMatch at/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)                                                           
url.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>

这是起始页
输入的用户名=={{username}
输入的密码=={{password}}
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>

这是尸体
{%csrf_令牌%}
用户名:
密码:
根据,重定向采用以下三种方式之一:

  • 模型:将调用模型的
    get\u absolute\u url()
    函数
  • 视图名称,可能带有参数:
    urlresolvers.reverse
    将用于反向解析名称
  • 绝对或相对URL,将用作重定向位置的原样
  • 通过传递一个不以协议开头且不包含斜杠的字符串,参数被识别为名称,并被传递到
    reverse

    这里的措辞可能有点误导。通过其URL模式名称查找视图,因此当文档说它采用视图名称时,实际上意味着指向视图的URL模式的名称,而不是视图本身的名称。由于
    reverse
    urlpatterns
    (在
    urls.py
    中)中查找URL模式,因此需要向其中添加
    testpage
    ,以便通过
    reverse
    找到它:

    url(r'^whatever/$', testpage, name='testpage')
    
    显然,您可以在第一个参数中放入任何您想要的模式,并且需要为第二个参数导入view函数。
    name
    部分是
    reverse
    用来查找URL的部分