奇怪的验证错误消息

时间:2010-07-13 16:50:01

标签: django django-forms validation

我正在使用标准身份验证表单。这个干净的方法看起来像这样:

def clean(self):
    username = self.cleaned_data.get('username')
    password = self.cleaned_data.get('password')

    if username and password:
        self.user_cache = authenticate(username=username, password=password)
        if self.user_cache is None:
            raise forms.ValidationError(_("Please enter a correct username and password. Note that both fields are case-sensitive."))
        elif not self.user_cache.is_active:
            raise forms.ValidationError(_("This account is inactive."))

    # TODO: determine whether this should move to its own method.
    if self.request:
        if not self.request.session.test_cookie_worked():
            raise forms.ValidationError(_("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in."))

    return self.cleaned_data

我的登录表单:

<form method="post" action="{% url django.contrib.auth.views.login %}">
    <table>
        {% if form.errors %}
            <tr class="form-errors">
                <td>
                    <ol>
                        {% for error in form.errors %}
                            <li>{{ error }}</li>
                        {% endfor %}
                    </ol>
                </td>
            </tr>
        {% endif %}

但不是我得到的验证信息:

如果用户名和密码不正确或帐户处于无效状态:“1. __all__
如果没有给出密码:“1. password
如果没有给出用户名:“1. username
如果两者都没有给出:“1. username 2. password
没有错误用户名的消息

修改 如果我改变

                <td>
                    <ol>
                        {% for error in form.errors %}
                            <li>{{ error }}</li>
                        {% endfor %}
                    </ol>
                </td>

到:

{{form.errors}}

我收到了__all__ and beneath it "Account inactive"。如何获得消息? 有任何想法吗 ?

1 个答案:

答案 0 :(得分:2)

试试这个。 form.errors是一个字典,所以像每个字典一样,你可以读取键和值。键是字段或__all__',值是您要查找的错误消息。

{% if form.errors %}
<tr>
    {% for k, v in form.errors.items %}
    <td>{{k}}</td>
    <td>{{v}}</td>
    {% endfor %}
</tr>
{% endif %}

修改

如果您不想选择特定的字段错误类型:

{% if form.errors %}
    {% for k, v in form.errors.items %} 
        <tr>
            {% ifequal k 'password' %}
                <td>Password</td>
                {% else %}
                    {% ifequal k 'username' %}
                        <td>Username</td>
                        {% else %}
                            <td>Other</td>
            {% endifequal %}{% endifequal %}                
            <td>{{v}}</td>
        </tr>
    {% endfor %}
{% endif %}

或在ifequal中选择'__all__'