MultiValueDictKeyError generated in Django after POST request on login page

戏子无情 提交于 2019-12-04 06:23:43

I had the same error, and i did this and it worked. Change:

username = request.POST['username']
password = request.POST['password'] 

to:

username = request.POST.get('username')
password = request.POST.get('password')

The above handles both the POST and GET methods that may result. I hope this helped.

When a request resolves to a view that's wrapped with the @login_required decorator, the request is redirected to the specified URL if the user is not logged in. So attempting to resolve your main_page view while not logged in will cause the user's browser to issue a GET request to /login/. However, the view that handles that URL assumes a POST request:

username = request.POST['username']
password = request.POST['password']

The usual approach would be to follow the general pattern for using a form in a view: https://docs.djangoproject.com/en/dev/topics/forms/#using-a-form-in-a-view

Specifically, check the request.method attribute so you can behave appropriately on a GET request and render the form. Or use the built-in views, they're pretty easy to work with.

I was able to suppress error by following @Emack333 but then, the code on views.py was not working and then upon close inspection, I've found that error was not on view file, rather it was on HTML side.

This error got generated because there was a mismatch of name attribute on the HTML input tag and in your case, it was name attr is missing.

<input type = "text" id = "username" placeholder = "Username" name="username">

The real issue is the forms within your template.

You need to use the 'name=' attribute to assign the name of the key instead of the 'id=' attribute.

I just solved this for my own project and realized this was the culprit.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!