Accessing Django Form Error Message in View
Question:
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()
* namen * 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 *namen *
showing up?
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.']
in your view.py file
error = form.errors
a =list(error.as_data()["error_filed_name"][0])
print(a[0])
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()
* namen * 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 *namen *
showing up?
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.']
in your view.py file
error = form.errors
a =list(error.as_data()["error_filed_name"][0])
print(a[0])