virusdefender
virusdefender

Reputation: 543

Questions about django form.errors, to get the raw error messages

The django document says https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.errors

Access the errors attribute to get a dictionary of error messages:

f.errors {'sender': ['Enter a valid email address.'], 'subject': ['This field is required.']}

However, when I try to print forms.errors, I got html code.

def login(request):
    if request.method == "GET":
        return render(request, r"login.html")
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            return HttpResponse("valid")
        else:
            print form.errors
            return HttpResponse("Invalid")

Django version 1.6.4, using settings 'test_proj.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

<ul class="errorlist"><li>username<ul class="errorlist"><li>Ensure this value ha
s at most 3 characters (it has 6).</li></ul></li></ul>

I need to get the raw errors to show an ajax messager, for exemple

response_json = {"status": "error", "content": "Username is too short"}

If there is any other way to get the raw error messages, You can also tell me.Thanks!

Upvotes: 2

Views: 731

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599450

That's simply an artefact of calling print: that implictly converts to a string, and the ErrorList class's __str__ method calls its as_ul method to output as HTML - this is so you can output the errorlist in a template simply by doing {{ form.errors }}.

The contents of the object itself are not in HTML, and you can see it by doing print repr(form.errors).

Upvotes: 4

Related Questions