[Answered ]-How to get the exact message of form.errors?

2👍

You are creating a list with the list comprehension expression [v[0].__str__() for k,v in form.errors.items()], that’s where you are getting the [ ].

Here is a better way to do what you are trying:

errors = '<br />'.join('<br />'.join(i for i in form.errors.values()))
messages.error(request, errors)

Your form may raise multiple errors, which is why you need to loop and fetch each error item. The standard practice is to pass the form back to the view, and then display the errors from the form object itself:

if form.is_valid():
     # do stuff
else:
   return render(request,{'form': form})

Then in your view:

{% if form.errors %}
   <strong>Please fix the errors</strong><br />
{% endif %}
<form>
   {% for field in form %}
      {{ field.errors }}
      {{ field.label_tag }}: {{ field }}
   {% endfor %}
   <input type="submit" />
</form>

Leave a comment