我正在尝试使用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>


它几乎可以工作。但是我的问题是,当用户名和/或密码不正确时,表单不会返回任何错误。

当我在外壳中尝试它时

>>> 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>'


有任何想法吗?

最佳答案

AuthenticationForm的行为与常规形式有些不同,它需要一个data参数。您在外壳程序代码中有data参数,但在视图中没有。它应该是:

connection_form = AuthenticationForm(data=request.POST)

07-24 17:02