djangopostdjango-viewsdjango-errorsdjango-request

Django: MultiValueDictKeyError


I created this sign up form which is working perfectly fine. On the same template I created a login form. The sign up form has 3 parameters email, username and password while the login form has only username and password inputs. When I try to sign up everything works fine but when I try to login, it gives me MultiValueDictKeyError

Here's my views.py

from django.shortcuts import render
from django.contrib.auth.models import User
from django.contrib.auth import login, logout, authenticate
from django.db import IntegrityError

# Create your views here.

def usersignup(request):
    if request.method == 'GET':
        return render(request, 'social_media/user.html')
    else:
        try:
            user = User.objects.create_user(username=request.POST.get['username'], password=request.POST.get['password'], email=request.POST['email'])
            user.save()
            login(request, user)
            return render(request, 'social_media/base.html')
        except IntegrityError:
            return render(request, 'social_media/user.html', {'error':'User already exists'})

def loginuser(request):
    if request.method == 'GET':
        return render(request, 'social_media/user.html')
    else:
        user = authenticate(request, username=request.POST.get['username'], password=request.POST.get['password'])
        if user is none:
            return render(request, 'social_media/user.html', {'errorsignin':'Invalid User man'})
        else:
            login(request, user)
            return render(request, 'social_media/base.html')

Here's my HTML form:

{% load static %}

<form action="" method="POST">
    {% csrf_token %}
    <input type="text" name="username" placeholder="Username">
    <input type="email" name="email" placeholder="Email">
    <input type="password" name="password" placeholder="Password">
    <button type="submit">Sign In</button>
</form>
                
<form action="" method="POST">
    {% csrf_token %}
    <input type="text" name="username" placeholder="Username">
    <input type="email" name="email" placeholder="Email">
    <input type="password" name="password" placeholder="Password">
    <button type="submit">Sign Up</button>
</form>

   

Is there any way I can just take username and password for signing up the user and not email or do I have to add an email input field for signing in the user!

Regards

Vansh


Solution

  • replace

    request.POST['']
    

    with

    request.POST.get('')
    

    everywhere

    example

    request.POST['username']
    

    to

    request.POST.get('username')