Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract Django Form errors message without the HTML tags

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.

Explored Questions and Documentations

  • displaying django form error messages instead of just the field name
  • Getting a list of errors in a Django form
  • django form errors. get the error without any html tags
  • How do I display the Django '__all__' form errors in the template?
  • https://docs.djangoproject.com/en/1.10/ref/forms/api/
  • https://docs.djangoproject.com/en/1.10/topics/forms/

Thanks, please tell if something is amiss or something needs clarification so i could fix it.

like image 357
android-guy Avatar asked Jan 18 '17 03:01

android-guy


1 Answers

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 the non_field_errors() method if you need to. If you want to attach errors to a specific field in the form, you need to call add_error().

like image 107
Burhan Khalid Avatar answered Oct 10 '22 19:10

Burhan Khalid