Python Django Encoding Error, Non-ASCII character '\xe5' Python Django Encoding Error, Non-ASCII character '\xe5' django django

Python Django Encoding Error, Non-ASCII character '\xe5'


Well, here you are:

Put # -*- coding: utf-8 -*- at top of file, it define de encoding.

The docs says:

Python will default to ASCII as standard encoding if no other encoding hints are given.

To define a source code encoding, a magic comment mustbe placed into the source files either as first or secondline in the file, such as:

So, you code must begin:

# -*- coding: utf-8 -*-from django.shortcuts import renderfrom django.http import HttpResponsefrom django.template.loader import get_template...

Hope helps


If you read PEP 263, it clearly says:

To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file…

(The original proposal said that it had to be the first line after the #!, if any, but presumably it turned out to be easier to implement with the "first or second line" rule.)

The actual reference docs describe the same thing, in a less friendly but more rigorous way, for 3.3 and 2.7.

A "magic comment" that appears later in the file is not magic, it's just a comment to mislead your readers without affecting the Python compiler.

UTF-8 for u'哈哈' is '\xe5\x93\x88\xe5\x93\x88', so those are the bytes in the file. In recent Python versions (including 2.7 and all 3.x), the default encoding is always ASCII unless the file starts with a UTF BOM (as some Microsoft editors like to do); even in 2.3-2.6 it's usually ASCII; in earlier versions it's Latin-1. Trying to interpret '\xe5\x93\x88\xe5\x93\x88' will fail with the exact exception you saw.