Forums

How I can fix this error.

A user un muy system use special caracters and show this error.'

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

How I can fix this error? The string is "José Iván" this show in error page.

# -*- coding: UTF-8 -*-

character encoding and unicode stuff is always a headache. the thing to remember is the difference between bytes (zeroes and ones) and strings (magical python entities that don't exist in the real world). To change bytes into strings you need to know how they're encoded. To change strings into bytes you need to choose how to encode them. To send and receive information across the web, you need to use bytes. but usually, when you want to work on them in python, you want to use strings.

All this to say: when you receive information from the web, you probably want to do something like:

input_string = user_input_bytes.decode('utf8')

And when you want to send it back out over the web, you probably want to do something like:

response_data = answer.encode('utf8')

UTF-8 is usually the best encoding to work with. Some web frameworks will try and do this work for you. Python 3 also tries to enforce a more rigid distinction between bytes and strings, which forces you to think about it, and helps a bit. The problem with Python 2 is that it mixes up the concept of bytes and strings too much...

Thanks! I try it!

Don't works! Django say:

The string that could not be encoded/decoded was: José Iván

and

Error during template rendering

What can I do?

What's your setting for DEFAULT_CHARSET in settings.py? https://docs.djangoproject.com/en/1.7/ref/settings/#std:setting-DEFAULT_CHARSET

There's more info about unicode and encoding in the django docs here: https://docs.djangoproject.com/en/1.7/ref/unicode/

The "DEFAULT_SETCHAR=UTF-8". I will read the documentation.

I change this file: /usr/lib/python2.7/site.py

493: encoding = ascii”# Default value set by _PyUnicode_Init()

to:

493: encoding = utf-8″# Default value set by _PyUnicode_Init()

now it's work!

Glad you got it working! I assume that you're not running this on PythonAnywhere, though...? You shouldn't be able to change /usr/lib/python2.7/site.py here. I'm sure it could help on your own machine, however.