[英]MultiValueDictKeyError in Django
我在执行 get 请求时而不是在 post 请求期间收到此错误。
错误:-
MultiValueDictKeyError 在 /StartPage/
"Key 'username' not found in <QueryDict: {}>"
请求方式:GET 请求地址:
http://127.0.0.1:8000/StartPage/
Django 版本:1.4 异常类型:MultiValueDictKeyError 异常值:
“在”中找不到关键的“用户名”
视图.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)
网址.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>
当然,在获取http://127.0.0.1:8000/StartPage/
页面时,您没有将username
作为GET
参数传递。
试试这个并观察打印的用户名: http://127.0.0.1:8000/StartPage?username=test
。
使用get()
并避免MultiValueDictKeyError
错误:
request.GET.get('username', '')
也可以看看:
确保您收到的请求不包含disabled 。 如果您获取的字段包含disabled 。 它会给出这个错误。 因此,为了解决这个问题,请确保您的领域中没有禁用词。 例如
<input name="numberid" disabled class="form-control" value="{{p.id}}" type="text"></div>
就我而言, disabled关键字导致了此错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.