I am stuck in this small issue. I have a page where the user needs to log in. after login everything is fine. but once the user is logged in, if he hits the address bar with enter, this error – Key 'username' not found in <QueryDict: {}> is coming and showing error on the page.
this is my code for logging in:
if request.path == '/cms/':
request.session['username'] = request.POST['username']
request.session['password'] = request.POST['password']
#check for login
if User.objects.exists():
u=User.objects.get(id=1)
if u.username==request.session['username'] and u.password==request.session['password']:
#do some stuff here, cos i am logged in
now, if i reload the page, it is fine, but with enter not. should i save the POST data into session? what is happenning here actually?
thanks a lot
What does
request.POSTcontain? It does not contain the username. To find out what it contains you can print request.POST which should show up on your dev server, or you can log the value somewhere or you can enter debugger and inspect usingimport pdb; pdb.set_trace()python dictionaries have
getmethod for this caserequest.POST.get('username')If the key is not found it returns
Noneby default instead of aKeyErrorare you making a post request to your view?
The above form would post the
usernameandpasswordfields. I think it is truley important to read https://docs.djangoproject.com/en/dev/topics/auth/ in its entirety, and learn how to use django built in user management. Django provides User objects (which it looks like you are using) and provides all the necessary functions to manage their authentication.It is important because: