Django中的MultiValueDictKeyError [英] MultiValueDictKeyError in Django

查看:100
本文介绍了Django中的MultiValueDictKeyError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


错误: -

Error:-

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

请求方法:GET请求URL:

Request Method: GET Request URL:

http://127.0.0.1:8000/StartPage/

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

Django Version: 1.4 Exception Type: MultiValueDictKeyError Exception Value:

Key用户名未找到

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>


推荐答案

当然,你没有通过用户名作为 GET 参数,同时获取 http://127.0.0.1:8000/StartPage/ 页面。

Sure, you are not passing username as a GET parameter while getting the http://127.0.0.1:8000/StartPage/ page.

尝试此操作并观察用户名: http://127.0.0.1:8000/StartPage?username=test

Try this and observe username printed: http://127.0.0.1:8000/StartPage?username=test.

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

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

另请参见:

  • Django request.GET
  • Django - taking values from POST request

这篇关于Django中的MultiValueDictKeyError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆