Django中的MultiValueDictKeyError
当我发起一个获取请求(get request)时,会出现这个错误,而在发起发送请求(post request)时却没有。
错误信息:
在 /StartPage/ 发生 MultiValueDictKeyError 错误
"Key 'username' not found in <QueryDict: {}>"
请求方式: 获取请求 请求网址:
http://127.0.0.1:8000/StartPage/
Django 版本: 1.4 异常类型: MultiValueDictKeyError 异常 值:
"找不到键 'username' "
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)
urls.py 文件
from polls.views import *
urlpatterns = patterns('',
# Examples:
url(r'^$', main_page),
url(r'^StartPage/$', Start_Page)
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>
Start_Page.html 文件
<html>
<head>
</head>
<body>
This is the StartPage
Entered user name == {{username}}
Entered password == {{password}}
</body>
</html>
2 个回答
2
确保你收到的请求中没有disabled这个词。如果你获取的字段里包含disabled,就会出现这个错误。为了修复这个问题,确保你的字段里没有disabled这个词。
举个例子:
<input name="numberid" disabled class="form-control" value="{{p.id}}" type="text"></div>
在我的情况下,disabled这个关键词就是导致错误的原因。
12
当然,你在访问 http://127.0.0.1:8000/StartPage/
页面时,没有把 username
作为 GET
参数传过去。
试试这个链接,看看 username
是怎么显示的: http://127.0.0.1:8000/StartPage?username=test
。
使用 get()
方法,这样可以避免出现 MultiValueDictKeyError
的错误:
request.GET.get('username', '')
另外,你可以参考: