django authenticationform不显示所有错误

时间:2013-12-08 16:50:46

标签: django forms authentication

我的登录工作正常,但没有显示所有错误。当我输入无效的用户名或密码时,这些错误不会显示,页面只会刷新而不会导致任何错误。

但是当我将一个字段留空时,它会显示正确的错误:

所以缺少的错误是(来自源):

error_messages = {
    'invalid_login': _("Please enter a correct %(username)s and password. "
                       "Note that both fields may be case-sensitive."),
    'inactive': _("This account is inactive."),
}

我的代码:

def login_user(request):
    """Logs a user into the application."""
    auth_form = AuthenticationForm(None, request.POST or None)

    # The form itself handles authentication and checking to make sure password and such are supplied.
    if auth_form.is_valid():
       (request, auth_form.get_user())
       return HttpResponseRedirect(reverse('index'))

    return render(request, 'login.html', {'auth_form': auth_form})

我的模板:

<form action="{% url 'login_user' %}" method="post" class="login">{% csrf_token %}
    <div>
        <input name="username" placeholder="Username:" type="text" name="username"     value="" id="username" class="login">
        {{ auth_form.username.errors }}
    </div>
    <div>
        <input name="password" placeholder="Password:" type="password" name="password" value="" id="password" class="login">
        {{ auth_form.password.errors }}
    </div>
    <div>
        <center>
            <a href="{% url 'register_user' %}">
                register
            </a>
            &nbsp;&nbsp;&nbsp;&nbsp;
            <button type="submit" class="link">
                login
            </button>
        </center>
    </div>
</form>

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您未在模板中加入form.non_field_errors。有关示例,请参阅customizing the form template上的文档。

另外,AuthenticationForm将请求作为其第一个参数。您传递的是None而不是request,这看起来有些奇怪。