在View中访问Django Form报错信息

Accessing Django Form Error Message in View

在我看来,我可以访问 form['item'].errors,它给了我类似的东西:

> form.is_valid()
 False
> 
> e = form['name'].errors
>
> print e
 <ul class="errorlist"><li>There already exists an item with this name. Try a different one.</li></ul>
>
> e.as_text()
* name\n  * There already exists an item with this name. Try a different one.

但是,如何在不显示 HTML 标记或 *name\n * 的情况下访问 There already exists... 错误消息?

我相信您正在寻找 as_data()

整个表格:

print(form.errors.as_data())

{'foo': [ValidationError([u'This is an error.'])], 'bar': [ValidationError([u'This is another error.'])]}

对于一个字段:

for e in form.errors['foo'].as_data():
    print e

[u'This field is required.']