[英]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.