Python 确认表单重新提交-Django通过重定向修复
当我刷新页面或“提交回”按钮时,我收到一个表单重新提交错误。为了防止在post请求后出现此错误,我将其重定向到一个新页面,该页面将显示实际页面…当我这样做时…在单击mainpge.html上的“提交”按钮后,我收到以下错误 错误: NoReverseMatch at/startpage/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
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
将用于反向解析名称reverse
这里的措辞可能有点误导。通过其URL模式名称查找视图,因此当文档说它采用视图名称时,实际上意味着指向视图的URL模式的名称,而不是视图本身的名称。由于reverse
在urlpatterns
(在urls.py
中)中查找URL模式,因此需要向其中添加testpage
,以便通过reverse
找到它:
url(r'^whatever/$', testpage, name='testpage')
显然,您可以在第一个参数中放入任何您想要的模式,并且需要为第二个参数导入view函数。name
部分是reverse
用来查找URL的部分