我在收到请求时收到此错误,而不是在发布请求期间收到此错误.
错误:-
/ StartPage /的MultiValueDictKeyError
Run Code Online (Sandbox Code Playgroud)"Key 'username' not found in <QueryDict: {}>"请求方法:GET请求URL:
Run Code Online (Sandbox Code Playgroud)http://127.0.0.1:8000/StartPage/Django版本:1.4异常类型:MultiValueDictKeyError异常值:
"密钥'用户名'未找到"
views.py
from django.shortcuts import render_to_response
from django.views.decorators.csrf import csrf_exempt
from django.template import Context, RequestContext
@csrf_exempt
def main_page(request):
return render_to_response('main_page.html')
@csrf_exempt
def Start_Page(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('Start_Page.html',variables)
Run Code Online (Sandbox Code Playgroud)
urls.py
from polls.views import *
urlpatterns = patterns('',
# Examples:
url(r'^$', main_page),
url(r'^StartPage/$', Start_Page)
Run Code Online (Sandbox Code Playgroud)
main_page.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>
Run Code Online (Sandbox Code Playgroud)
Start_Page.html
<html>
<head>
</head>
<body>
This is the StartPage
Entered user name == {{username}}
Entered password == {{password}}
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
ale*_*cxe 11
当然,在获取页面时,您不会username作为GET参数传递http://127.0.0.1:8000/StartPage/.
试试这个并观察打印用户名:http://127.0.0.1:8000/StartPage?username=test.
使用get()并避免MultiValueDictKeyError错误:
request.GET.get('username', '')
Run Code Online (Sandbox Code Playgroud)
也可以看看: