Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Django Form Error Message in View

In my view I can access form['item'].errors and it gives me something like:

> 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.

However, how do I access the There already exists... error message without either the HTML tags or the *name\n * showing up?

like image 263
blue_zinc Avatar asked Dec 11 '22 20:12

blue_zinc


1 Answers

I believe you are looking for as_data().

For the whole form:

print(form.errors.as_data())

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

For just a field:

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

[u'This field is required.']
like image 193
dotcomly Avatar answered Dec 30 '22 16:12

dotcomly