2015-02-23 51 views
1

我无法弄清楚如何在Django(1.7)模板中打印所有表单错误消息,尽管遵循官方建议文档和其他地方。官方建议打印模板中的所有Django表单错误无法正常工作......或不明白

我有一个帐户用户/传递管理员/管理员。我有意将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/ -- unsupported operand type(s) for %=: 'NoneType' and 'dict'

(据another section in the official docs,错误对象仅仅是一本字典。)

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

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

W请问我错过了什么帽子?


网址条目:

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> 
+0

我希望是一个更清晰的随访:http://stackoverflow.com/questions/28681563/ django-form-is-properly-catching-bad-user-pass-length-but-is-crashing-with-type – aliteralmind 2015-02-23 19:14:24

回答

2

form.errors是一本字典。您可以通过使用.items访问密钥(字段名,或__all__)和值(错误信息):

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

这给了我一个'TypeError at/auth/login/...不受支持的操作数类型(s)对于%=:'NoneType'和'dict''。 – aliteralmind 2015-02-23 17:38:02

+0

是的,因为在这种情况下'form.errors'是None。所以你需要使用一个警卫:'{%if form.errors%} ...' – 2015-02-23 17:54:38

+0

@DanielRoseman即使[this](http://dpaste.com/2Z07S1Z)导致该错误。我怀疑我的整体问题是没有打印错误。我试图产生一个虚假的错误来测试的东西,但我有点迷路。 – aliteralmind 2015-02-23 18:01:38