官方建议在模板中打印所有Django表单错误不能正常工作或不明白 [英] Official advice for printing all Django form errors in a template not working...or not understood

查看:275
本文介绍了官方建议在模板中打印所有Django表单错误不能正常工作或不明白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can't figure out how to print all form error messages in a Django (1.7) template, despite following the advice in the official docs and elsewhere.

我有一个帐户用户/通行证管理员/管理员。我有意将LoginForm中的最小允许用户名长度更改为6,以便获得错误长度错误,而不是坏用户/传递组合错误(底部的完整表单/视图代码)。

I have an account user/pass admin/admin. I've intentionally changed the minimum allowable username length in the LoginForm to 6, in an effort to get a "bad length" error, instead of a "bad user/pass combo" error (full form/view code at the bottom).

根据官方文档,以下内容应打印所有错误信息:

According to the official docs, the following should print all error messages:

{% 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

我也尝试过这个,但它没有打印出来:

I also tried this, but it prints out nothing:

{% 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 %}

此问题中接受的答案建议这是:

The accepted answer in this question suggests this:

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

但是, $ / code>过滤器是否存在,它会导致

But, whether the escape filter is there or not, it results in

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

(根据官方文档中的另一部分,错误对象是只是一个字典。)

(According to another section in the official docs, the error object is just a dictionary.)

我也尝试过这个,如此问题所述,但它给出了相同的错误:

I also tried this, as mentioned in this question, but it gives the same error:

{% 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 从auth_lifecycle.models导入PASSWORD_MIN_LEN,PASSWORD_MAX_LEN
从auth_lifecycle.models导入USERNAME_MIN_LEN,USERNAME_MAX_LEN
从django


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 续: / p>

view_login.py continued:

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 })






整个模板:


Entire template:

{% 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__)和值(错误消息):

form.errors is a dictionary. You can access to the key (field name, or __all__) and the value (error message) by using .items:

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

这篇关于官方建议在模板中打印所有Django表单错误不能正常工作或不明白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆