【问题标题】:MultiValueDictKeyError in DjangoDjango中的MultiValueDictKeyError
【发布时间】:2014-06-25 05:04:21
【问题描述】:

我在执行获取请求而不是在发布请求期间收到此错误

错误:-

MultiValueDictKeyError at /StartPage/

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

请求方法:GET 请求地址:

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)

urls.py

from polls.views import *
urlpatterns = patterns('',
    # Examples:
     url(r'^$', main_page),
     url(r'^StartPage/$', Start_Page)

ma​​in_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>

【问题讨论】:

    标签: python django


    【解决方案1】:

    当然,在获取http://127.0.0.1:8000/StartPage/ 页面时,您没有将username 作为GET 参数传递。

    试试这个并观察打印的用户名:http://127.0.0.1:8000/StartPage?username=test

    使用get() 并避免MultiValueDictKeyError 错误:

    request.GET.get('username', '') 
    

    另见:

    【讨论】:

      【解决方案2】:

      确保您收到的请求不包含disabled。如果您获得的字段包含 disabled。它会给出这个错误。 因此,为了解决这个问题,请确保您的字段中没有 disabled 字样。 例如

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

      在我的例子中,disabled 关键字导致了这个错误。

      【讨论】:

        猜你喜欢
        • 2020-05-24
        • 1970-01-01
        • 1970-01-01
        • 2018-04-13
        • 1970-01-01
        • 2015-09-12
        • 2022-12-12
        • 2020-02-03
        • 2021-11-30
        相关资源
        最近更新 更多