Django中的MultiValueDictKeyError

时间:2014-05-08 01:06:54

标签: python django

当我收到请求时,我得到错误,而不是在帖子请求期间。

  

错误: -

     

/ StartPage /

处的MultiValueDictKeyError
"Key 'username' not found in <QueryDict: {}>"
     

请求方法:GET请求URL:

http://127.0.0.1:8000/StartPage/
     

Django版本:1.4异常类型:MultiValueDictKeyError异常   价值:

     

&#34; Key&#39;用户名&#39;未在&#34;

中找到

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 个答案:

答案 0 :(得分: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', '') 

另见:

答案 1 :(得分:2)

确保您收到的请求不包含已禁用。如果您要获取的字段包含已禁用。它将给出此错误。 因此,为了解决此问题,请确保您的字段中没有 disabled 单词。 例如

 <input  name="numberid" disabled class="form-control"  value="{{p.id}}" type="text"></div>

就我而言, 已禁用 关键字是导致此错误的原因。