I need to extract the messages and field.
For Example, I have this django form error result
<ul class="errorlist">
<li>__all__
<ul class="errorlist nonfield">
<li>Pointofsale with this Official receipt and Company already exists.</li>
</ul>
</li>
</ul>
from the output of this code
def post_sale(request):
sale_form = request["data"]
if sale_form.is_valid():
save_form.save()
else:
print save_form.errors
But what i need to achieve is to get the message without the tags, so i could just return those message in plain string/text.
def post_sale(request):
sale_form = request["data"]
if sale_form.is_valid():
save_form.save()
else:
# This is just pseudo code
for field in save_form.errors:
field = str(field["field"})
message = str(field["error_message"])
print "Sale Error Detail"
print field
print message
error_message = { 'field':field,'message':message }
error_messages.append(error_message )
The output would be:
Sale Error Detail
(the field where form error exists)
Pointofsale with this Official receipt and Company already exists.
Thanks, please tell if something is amiss or something needs clarification so i could fix it.
The errors
property of a bound form will contain all errors raised by that form, as a dictionary. The key is a field or other special values (such as __all__
), and the value is a list of one or more errors.
Here is a simple example on how this works:
>>> from django import forms
>>> class MyForm(forms.Form):
... name = forms.CharField()
... email = forms.EmailField()
...
>>> f = MyForm() # Note, this is an unbound form
>>> f.is_valid()
False
>>> f.errors # No errors
{}
>>> f = MyForm({}) # Now, the form is bound (to an empty dictionary)
>>> f.is_valid()
False
>>> f.errors # dictionary of errors
{'name': [u'This field is required.'], 'email': [u'This field is required.']}
In your view, depending on what you want you can just return the value of form.errors
, or parse it to whatever structure your need.
for field, errors in form.errors.items():
print('Field: {} Errors: {}'.format(field, ','.join(errors))
For the specific error you have mentioned, it is a custom error raised as a result of overriding the clean()
method - which is why it is listed under the special identifier __all__
and not under a specific field.
This is mentioned in the forms reference, under validation:
Note that any errors raised by your
Form.clean()
override will not be associated with any field in particular. They go into a special “field” (called__all__
), which you can access via thenon_field_errors()
method if you need to. If you want to attach errors to a specific field in the form, you need to calladd_error()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With