Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 1: ordinal not in range(128)

Tags:

django

I know there is existing title about this, but there question is different from mine. So here's my problem. I use context processor to display user name. It's working but my sentry detect an error yesterday.

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 1: ordinal not in range(128)

Here is my code:

def display_name(request):
    try:
        name = "{0} {1}".format(request.user.first_name, request.user.last_name)
        name = name.strip()
        if not name:
            name = request.user.username
    except AttributeError:
        name = None

    return {'display_name': name,}

What's the cause of this? Or the user input character for their name?

like image 470
catherine Avatar asked Feb 26 '13 08:02

catherine


1 Answers

It's basically a user input problem.

Text encodings are a whole "thing" and hard to get into, but in a nut shell, a user entered a Unicode character that can't easily be mapped to an ASCII character.

You can fix this by changing this:

name = "{0} {1}".format(request.user.first_name, request.user.last_name)

To this:

name = u"{0} {1}".format(request.user.first_name, request.user.last_name)

This tells Python to treat the string as a unicode string (which has all the normal functions as an ascii string).

like image 107
Jack Shedd Avatar answered Sep 27 '22 19:09

Jack Shedd