python - 在模板中打印所有 Django 表单错误的官方建议不工作......或不理解

标签 python django forms django-templates

我不知道如何在 Django (1.7) 模板中打印所有表单错误消息,尽管遵循了官方文档和其他地方的建议。

我有一个帐户 user/pass admin/admin。我故意将 LoginForm 中允许的最小用户名长度更改为 6,以努力获得“错误长度”错误,而不是“错误用户/密码组合”错误(底部的完整表格/查看代码)。

根据 the official docs , 以下应打印所有错误消息:

{% if form.errors %}
   {% for error in form.errors %}
      <li><strong>{{ error|escape }}</strong></li>
   {% endfor %}
{% endif %}

但它只打印“用户名”这个词。

改成这样

{% for error, msg in form.errors %}
   <li><strong>{{ error|escape }}: {{ msg|escape }}</strong></li>
{% endfor %}

打印

Username
u: s

嗯?

我也试过这个,但它什么也没打印出来:

{% for error, msg in form.non_field_errors %}
   <li><strong>{{ error|escape }}: {{ msg|escape }}</strong></li>
{% endfor %}

与此相同:

{% for error in form.non_field_errors %}
   {{error}} 
{% endfor %}

还有这个:

{% for error in form.non_field_errors %}
   {{error.msg}} 
{% endfor %}

this question 中接受的答案建议:

{% for key,value in form.errors.items %}
   {% for error in value %}
   <li>{{ error|escape }}</li>
   {% endfor %}
{% endfor %}

但是,无论 escape 过滤器是否存在,它都会导致

TypeError at/auth/login/-- %=: 'NoneType' 和 'dict' 不支持的操作数类型

(根据 another section in the official docs ,错误对象只是一个字典。)

我也试过this ,如 this question 中所述,但它给出了同样的错误:

{% for field in form %}
   <li>{{ field.errors|escape }}</li>
{% endfor %}

请问我错过了什么?


网址入口:

url(r"^login/$",
    "auth_lifecycle.registration.view_login.login_maybe_remember",
    { "authentication_form": AuthenticationFormEnforceLength },
    name="login"),

view_login.py

from auth_lifecycle.models     import PASSWORD_MIN_LEN, PASSWORD_MAX_LEN
from auth_lifecycle.models     import USERNAME_MIN_LEN, USERNAME_MAX_LEN
from django                    import forms    #NOT django.contrib.auth.forms
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.views import login
from django.utils.translation  import ugettext, ugettext_lazy as _

def login_maybe_remember(request, *args, **kwargs):
    """
    Login with remember-me functionality and length checking. If the
    remember-me checkbox is checked, the session is remembered for
    SESSION_COOKIE_AGE seconds. If unchecked, the session expires at
    browser close.

    - https://docs.djangoproject.com/en/1.7/ref/settings/#std:setting-SESSION_COOKIE_AGE
    - https://docs.djangoproject.com/en/1.7/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.set_expiry
    - https://docs.djangoproject.com/en/1.7/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.get_expire_at_browser_close
    """
    if request.method == 'POST' and not request.POST.get('remember', None):
        #This is a login attempt and the checkbox is not checked.
        request.session.set_expiry(0)

    context = {}
    context["USERNAME_MIN_LEN"] = USERNAME_MIN_LEN
    context["USERNAME_MAX_LEN"] = USERNAME_MAX_LEN
    context["PASSWORD_MIN_LEN"] = PASSWORD_MIN_LEN
    context["PASSWORD_MAX_LEN"] = PASSWORD_MAX_LEN
    kwargs["extra_context"] = context

    return login(request, *args, **kwargs)

def get_min_max_incl_err_msg(min_int, max_int):
    """A basic error message for inclusive string length."""
    "Must be between " + str(min_int) + " and " + str(max_int) + " characters, inclusive."

view_login.py 继续:

username_min_max_len_err_msg = get_min_max_incl_err_msg(USERNAME_MIN_LEN, USERNAME_MAX_LEN)
pwd_min_max_len_err_msg = get_min_max_incl_err_msg(PASSWORD_MIN_LEN, PASSWORD_MAX_LEN)

class AuthenticationFormEnforceLength(AuthenticationForm):
    """
    An `AuthenticationForm` that enforces min/max lengths.
    - https://docs.djangoproject.com/en/1.7/_modules/django/contrib/auth/forms/#AuthenticationForm

    Pass this into the login form via the `authentication_form` parameter.
    - https://docs.djangoproject.com/en/1.7/topics/auth/default/#django.contrib.auth.views.login
    Which is done in `registration/urls.py`.
    """
    username = forms.CharField(min_length=USERNAME_MIN_LEN,
                               max_length=USERNAME_MAX_LEN,
                               error_messages={
                                   'min_length': username_min_max_len_err_msg,
                                   'max_length': username_min_max_len_err_msg })
    password = forms.CharField(label=_("Password"), widget=forms.PasswordInput,
                                    min_length=PASSWORD_MIN_LEN,
                                    max_length=PASSWORD_MAX_LEN,
                                    error_messages={
                                        'min_length': pwd_min_max_len_err_msg,
                                        'max_length': pwd_min_max_len_err_msg })

整个模板:

{% load i18n %}       {# For the "trans" tag #}
{% load staticfiles %}{# References the static directory.             #}
<!DOCTYPE html>       {# Use with "{% static 'color_ajax_like.js' %}" #}
<html lang="en">
<HTML><HEAD>
     <TITLE>Login</TITLE>
     <!-- The following line makes this page pleasant to view on any device. -->
     <meta name="viewport" content="width=device-width" />
</HEAD>

<BODY>

<H1>Login</H1>

{% if form.errors %}
    {% for error in form.non_field_errors %}
        {{error.msg}}
    {% endfor %}
{% endif %}
<form method="post" id="loginForm" action="{% url 'login' %}">
{% csrf_token %}
    <table>
        <tr>
             <td>{{ form.username.label_tag }}</td>
             <td>{{ form.username }}</td>
        </tr>
        <tr>
             <td>{{ form.password.label_tag }}</td>
             <td>{{ form.password }}</td>
        </tr>
    </table>

    <label><input name="remember" type="checkbox">{% trans "Remember me" %}</label>

    <input type="submit" value="login" />
    <input type="hidden" name="next" value="{% url 'main_page' %}" />
</form>

<P>{% trans "...I forgot my password..., ...Create a new account..." %}</P>

<p><i><a href="{% url 'main_page' %}">View the main page without logging in.</a></i></p>

<script language="JavaScript">
    /*
        Before our JavaScript can be imported, the following variables need
        to be set from some Django variables. While these values could be
        hard-coded here, into the JavaScript, this allows the configuration
        to be centrally located.

        These four values come from auth_lifecycle.models and are required
        by validate_login_user_pass.js.
     */
    var minUserLen = {{ USERNAME_MIN_LEN }}; //USERNAME_MIN_LEN
    var maxUserLen = {{ USERNAME_MAX_LEN }}; //USERNAME_MAX_LEN
    var minPassLen = {{ PASSWORD_MIN_LEN }}; //PASSWORD_MIN_LEN
    var maxPassLen = {{ PASSWORD_MAX_LEN }}; //PASSWORD_MAX_LEN

    document.getElementById("id_username").focus();
</script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script>
<script type='text/javascript' src="{% static 'js/validate_login_user_pass.js' %}"></script>

</BODY></HTML>

最佳答案

form.errors 是一个字典。您可以使用 .items 访问键(字段名称或 __all__)和值(错误消息):

{% for error_field, error_message in form.errors.items %}
    {{ error_field|striptags }}: {{ error_message|striptags }}
{% endfor %}

关于python - 在模板中打印所有 Django 表单错误的官方建议不工作......或不理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28679257/

相关文章:

python - Elif 语句被忽略

python - 将 python 小数舍入到最接近的 0.05

python - 无法使用 Selenium 在搜索字段中输入文本

vb.net - 任务栏中显示二级窗体的模态对话框

php - 提交表单之前清除 URL 中的 GET 变量

python - 断言未按预期工作

python - 如何在 Django 中为模型创建索引?

django - 有什么办法可以更改登录的Django-rest-auth的 View 吗?

javascript - JQuery - 表单验证 - Onblur

python - 如何在 django 中获取时区感知日期?