6
votes

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>
2

2 Answers

11
votes

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:

2
votes

Make sure the request you are getting doesn't contains disabled. If the field which you are getting contains disabled. It will give this error. So, in order to solve this make sure your don't have a disabled word in your field. e.g

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

In my case, the disabled keyword was causing this error.