Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 819
Nikki Erwin Ramirez Avatar asked Jan 13 '11 09:01

Nikki Erwin Ramirez


People also ask

How do I get an exception message in Python?

To catch and print an exception that occurred in a code snippet, wrap it in an indented try block, followed by the command "except Exception as e" that catches the exception and saves its error message in string variable e . You can now print the error message with "print(e)" or use it for further processing.

How do I return an error response in Django?

I want to return a HTTP 400 response from my django view function if the request GET data is invalid and cannot be parsed. Return a HttpResponseBadRequest : docs.djangoproject.com/en/dev/ref/request-response/… You can create an Exception subclass like Http404 to have your own Http400 exception.

How does Django handle connection error?

You stated that you are running the server on Ubuntu while you are trying to connect it from another PC running Windows. In that case, you should replace the 127.0. 0.1 with the actual IP address of Ubuntu server (the one you use for PuTTY). Show activity on this post.


1 Answers

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))
like image 111
scoffey Avatar answered Sep 20 '22 16:09

scoffey