当我尝试从表单中打印出错误时输出非常奇怪。这是模板中的代码(如果您对CSS感到好奇,可以使用Bootstrap 3),
{% if not form.is_valid and form.is_bound %}
<div class="row">
<div class="col col-lg-10 col-offset-1 text-center">
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert">×</button>
{% for field in form %}
{% for error in field.errors %}
<strong>{{ field.label }}</strong>: {{ error }} <br>
{% endfor %}
{% endfor %}
</div>
</div>
</div>
{% endif %}
所有其他错误都很好,除非我输入错误的密码。然后,我得到这样的输出,
Password: I
Password: n
Password: c
Password: o
Password: r
Password: r
Password: e
Password: c
Password: t
Password:
Password: p
Password: a
Password: s
Password: s
Password: w
Password: o
Password: r
Password: d
Password: ,
Password:
Password: p
Password: l
Password: e
Password: a
Password: s
Password: e
Password:
Password: t
Password: r
Password: y
Password:
Password: a
Password: g
Password: a
Password: i
Password: n
Password: .
如果你仔细观察,这是一句话,“密码不正确,请再试一次。”除了每一个角色都有自己的路线。
这里发生了什么?
为了进一步参考,我在这里是如何在视图中分配错误消息
form.errors['email'] = 'Email not found, please try again.'
form.errors['password'] = 'Incorrect password, please try again.'
非常感谢!!
答案 0 :(得分:1)
对我来说,问题是错误循环正在迭代字符串,这是有道理的,因为你将它定义为string
。
form.errors['password'] = 'Incorrect password, please try again.'
尝试将其包装在列表中:
form.errors['password'] = ['Incorrect password, please try again.']
电子邮件也可能发生这种情况。
希望这有帮助!