我正在尝试首次实现对Django的身份验证。
我正在按照Django 2的官方指南创建登录部分。但是,我遇到了这个问题:
Exception Type: MultiValueDictKeyError Exception Value: 'username'
我创建了一个名为“帐户”的应用。在里面,我有以下内容:
在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")
在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 %}
在urls.py中(我的应用程序的“帐户”不是项目的):
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"),
]
答案 0 :(得分:1)
def login(request):
username = request.POST['username']
...
出现错误是因为视图始终试图从POST数据中获取username
。但是,对于最初的GET请求,request.POST
将为空。
您不应尝试这样编写自己的登录视图。 Django随附authentication views。您应该使用它们。
答案 1 :(得分:1)
只需像下面那样进行身份验证,请检查请求方法
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
def login(request):
if request.method == 'POST':
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")
else:
return render(request, "accounts/login.html")