MultiValueDictKeyError generated in Django after POST request on login page

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

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