我尝试使用AuthenticationForm模型对我的用户进行身份验证。
以下是我的观点:
from django.contrib.auth.forms import AuthenticationForm
def connection(request):
if request.user.is_authenticated():
return redirect('user:profile')
if request.method == "POST":
connection_form = AuthenticationForm(request.POST)
if connection_form.is_valid():
username = connection_form.cleaned_data["username"]
password = connection_form.cleaned_data["password"]
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
if next is not None:
return redirect(next)
else:
return redirect('home')
else :
connection_form = AuthenticationForm()
return render(request, 'user/connection.html', { 'connection_form': connection_form })
这是我的模板代码:
<form action="{% url 'user:connection' %}{% if request.GET.next %}?next={{request.GET.next}}{% endif %}" method="post">
{% csrf_token %}
{{ connection_form }}
<input type="submit" value="Se connecter" />
</form>
它几乎可以工作。但我的问题是,当用户名和/或密码不正确时,表单不会返回任何错误。
当我在shell中尝试这个时,它可以工作
>>> POST = {'username' : 'test', 'password' : 'me', }
>>> form = AuthenticationForm(data=POST)
>>> form.is_valid()
False
>>> form.as_p()
'<ul class="errorlist nonfield"><li>Please enter a correct username and password. Note that both fields may be case-sensitive.</li></ul>\n<p><label for="id_username">Username:</label> <input autofocus="" id="id_username" maxlength="254" name="username" type="text" value="test" required /></p>\n<p><label for="id_password">Password:</label> <input id="id_password" name="password" type="password" required /></p>'
有什么想法吗?
答案 0 :(得分:2)
AuthenticationForm
与常规表单略有不同,需要data
个参数。您的shell代码中有data
参数,但在视图中没有。{1}}参数。它应该是:
connection_form = AuthenticationForm(data=request.POST)