Python – MultiValueDictKeyError in Django

djangopython

I get this Error when I do a get request and not during post requests.

Error:-

MultiValueDictKeyError at /StartPage/

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

Request Method: GET Request URL:

http://127.0.0.1:8000/StartPage/

Django Version: 1.4 Exception Type: MultiValueDictKeyError Exception
Value:

"Key 'username' not found in "

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>

Best Answer

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

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

Use get() and avoid MultiValueDictKeyError errors:

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

See also:

Related Topic