I am trying to implement for the first time the authentication for Django.
I am creating the login part following the official guide of Django 2. However I am having this problem:
Exception Type: MultiValueDictKeyError Exception Value: 'username'
I created an app called "accounts". Inside of it, I have the following:
In accounts/views.py:
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
def login(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
return redirect('home')
else:
return render(request, "accounts/login.html")
In templates/accounts.html:
{% extends 'mysite/base.html' %}
{% block content %}
<h1>Login</h1>
<form method="POST" action="{% url 'login' %}">
{% csrf_token %}
Username:
<br>
<input type="text" name="username" />
<br>
Password:
<br />
<input type="password" name="password" />
<br>
<br>
<input class="btn btn-primary" type="submit" value="Sign Up!" />
</form>
{% endblock %}
In urls.py (of my app "accounts" not of the project):
from django.urls import path, include
from . import views
urlpatterns = [
path("signup/", views.signup, name="signup"),
path("login/", views.login, name="login"),
path("logout/", views.logout, name="logout"),
]
def login(request):
username = request.POST['username']
...
You get the error because your view always tries to get username
from the POST data. However, for the initial GET request, request.POST
will be empty.
You shouldn't try to write your own login view like this. Django comes with authentication views. You should use them.