In Django, how can I get an exception's message?
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))
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, 2022Comments
-
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 over 11 yearsThat 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 over 11 yearsWell, 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 reuseValidationError
for semantic purposes. I guess the more proper approach would be to subclassBaseException
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 over 9 yearsI figured that, as validators for a field is also an array. Good to know about the
messages
member ofValidationError
. They never mention it here: docs.djangoproject.com/en/dev/ref/forms/validation as they primarily should!