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

blu*_*inc 3 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.
Run Code Online (Sandbox Code Playgroud)

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

dot*_*mly 12

我相信你正在寻找as_data()

对于整个表格:

print(form.errors.as_data())

{'foo': [ValidationError([u'This is an error.'])], 'bar': [ValidationError([u'This is another error.'])]}
Run Code Online (Sandbox Code Playgroud)

对于一个字段:

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

[u'This field is required.']
Run Code Online (Sandbox Code Playgroud)