在视图中访问Django表单错误消息

时间:2015-10-22 00:36:42

标签: python django django-forms django-views

在我看来,我可以访问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标记或There already exists...显示,如何访问*name\n *错误消息?

1 个答案:

答案 0 :(得分:3)

我相信您正在寻找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.']