Q: MultiValueDictKeyError at /account/register Error:
MultiValueDictKeyError at /account/register
'first_name'
Request Method: POST
Request URL:    http://127.0.0.1:8000/account/register
Django Version: 2.2.7
Exception Type: MultiValueDictKeyError
Exception Value:
'first_name'
Exception Location: C:\Users\Maansi\AppData\Roaming\Python\Python37\site-packages\django\utils\datastructures.py in getitem, line 80
views.py:
 def login(request):
    if request.method=='POST':
        username=request.POST['username']
        password=request.POST['password']
        user=auth.authenticate(username=username,password=password)
        if user is not None:
            auth.login(request,user)
            return redirect("/")
        else:
            messages.info(request,'invalid credentials')
            return redirect('login')
    else:
        return render(request,"login.html")

def register(request):
    if request.method=='POST':
        first_name=request.POST['first_name']
        last_name=request.POST['last_name']
        username=request.POST['username']
        password1=request.POST['password1']
        password2=request.POST['password2']
        email=request.POST['email']
        if password1==password2:
            if User.objects.filter(email=email).exists():
                messages.info(request,'Email Taken')
                return redirect('register')
            elif User.objects.filter(username=username).exists():
                messages.info(request,'Username Taken')
                return redirect('register')
            else:    
             user=User.objects.create_user(username=username,password=password1,email=email,first_name=first_name,last_name=last_name)
                user.save()
                print('user created')
                return redirect('login')
        else:
            messages.info(request,"Password don't match!")
            return redirect('register')
    else:
        return render(request,"register.html")

login.html
                        <div class="col-sm-6">
                            <div class="form-group">
                                {% csrf_token %}
                                <input class="form-control valid" name="username" id="name" type="text" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter your username'" placeholder="Enter your username">
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <div class="form-group">
                                {% csrf_token %}
                                <input class="form-control valid" name="password" id="password" type="password" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter Password'" placeholder="Enter Password">
                            </div>
                        </div>

register.html:
<div class="col-lg-8">
                        {% csrf_token %}
                        <form class="form-contact contact_form" action="register" method="post">
                            <div class="row">

                                <div class="col-sm-6">
                                    <div class="form-group">
                                        {% csrf_token %}
                                        <input class="form-control valid" name="first_name" id="name" type="text" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter your name'" placeholder="Enter your name">
                                    </div>
                                </div>
                                <div class="col-sm-6">
                                    <div class="form-group">
                                        {% csrf_token %}
                                        <input class="form-control valid" name="last_name" id="name" type="text" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter your last name'" placeholder="Enter your last name">
                                    </div>
                                </div>
                                <div class="col-sm-6">
                                    <div class="form-group">
                                        {% csrf_token %}
                                        <input class="form-control valid" name="username" id="name" type="text" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter your username'" placeholder="Enter your username">
                                    </div>
                                </div>
                                <div class="col-sm-6">
                                    <div class="form-group">
                                        {% csrf_token %}
                                        <input class="form-control valid" name="email" id="email" type="email" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Enter email address'" placeholder="Email">
                                    </div>
                                </div>
                                <div class="col-sm-6">
                                    <div class="form-group">
                                        {% csrf_token %}
                                        <input class="form-control valid" name="password1" id="password" type="password" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Create Password'" placeholder="Create Password">
                                    </div>
                                </div>
                                <div class="col-sm-6">
                                    <div class="form-group">
                                        {% csrf_token %}
                                        <input class="form-control valid" name="password2" id="password" type="password" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Confirm Password'" placeholder="Confirm Password">
                                    </div>
                                </div>
                            </div>

Traceback:
Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/account/register

Django Version: 2.2.7
Python Version: 3.7.3
Installed Applications:
['news.apps.NewsConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "C:\Users\Maansi\AppData\Roaming\Python\Python37\site-packages\django\utils\datastructures.py" in __getitem__
  78.             list_ = super().__getitem__(key)

During handling of the above exception ('first_name'), another exception occurred:

File "C:\Users\Maansi\AppData\Roaming\Python\Python37\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\Maansi\AppData\Roaming\Python\Python37\site-packages\django\core\handlers\base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\Maansi\AppData\Roaming\Python\Python37\site-packages\django\core\handlers\base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\Maansi\projects\Learn\account\views.py" in register
  34.         first_name=request.GET['first_name']

File "C:\Users\Maansi\AppData\Roaming\Python\Python37\site-packages\django\utils\datastructures.py" in __getitem__
  80.             raise MultiValueDictKeyError(key)

Exception Type: MultiValueDictKeyError at /account/register
Exception Value: 'first_name'

What is the problem with first_name. Let me know if more information is needed.

A: It is because it can not find the key first_name in request.POST.
In Python, dictionaries have a build-in static method .get(). When .get() can't find the key, it returns None by default or the value you specified.
My suggestion is to use .get(). Here is the example-
Change
first_name=request.POST["first_name"]

to 
first_name=request.POST.get("first_name", "default value")

Also, there is no need to write {% csrf_token %} before every input field. Only one csrf_token is required per form. So you can remove the other ones just keep one inside the form tag.

A: check the fistname field of your register.html and make sure firstname input field must have a name of first_name.


For example
<input type="text" name="first_name" class="form-control" required>
