In Django, how can I get an exception's message?

15,309

ValidationError actually holds multiple error messages.

The output of print err is [u'Empty URL'] because that is the string returned by repr(err.messages) (see ValidationError.__str__ source code).

If you want to print a single readable message out of a ValidationError, you can concatenate the list of error messages, for example:

    # Python 2 
    print '; '.join(err.messages)
    # Python 3
    print('; '.join(err.messages))
Share:
15,309
Nikki Erwin Ramirez
Author by

Nikki Erwin Ramirez

I'm a software developer currently working on various projects using PHP/Zend, Python/Django, JavaScript/jQuery/Dojo.

Updated on June 16, 2022

Comments

  • Nikki Erwin Ramirez
    Nikki Erwin Ramirez about 2 years

    In a view function, I have something like:

    try:
        url = request.POST.get('u', '')
        if len(url) == 0:
            raise ValidationError('Empty URL')
    except ValidationError, err:
        print err
    

    The output is a string: [u'Empty URL']

    When I try to pass the error message to my template (stuffed in a dict, something like { 'error_message': err.value }), the template successfully gets the message (using {{ error_message }}).

    The problem is that I get the exact same string as above, [u'Empty URL'], with the [u'...']!

    How do I get rid of that?

    (Python 2.6.5, Django 1.2.4, Xubuntu 10.04)

  • Fred
    Fred over 11 years
    That is actually bad practise I'd say. BaseException catches everything, whereas you should only handle ValidationError. If another exception pops it's because there's an error in your code, which should be fixed.
  • Nikki Erwin Ramirez
    Nikki Erwin Ramirez over 11 years
    Well, I did raise the error/exception myself. The code in the try block was very minimal, that I thought the chances of a different kind of error popping up was slim. I just wanted to reuse ValidationError for semantic purposes. I guess the more proper approach would be to subclass BaseException with my own kind of validation error? In any case, the code has changed a lot since I first posted this and my workaround is no longer applicable, so I accepted the answer above instead.
  • Tomasz Gandor
    Tomasz Gandor over 9 years
    I figured that, as validators for a field is also an array. Good to know about the messages member of ValidationError. They never mention it here: docs.djangoproject.com/en/dev/ref/forms/validation as they primarily should!