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

advertisements

Hi, I ran into an encoding error with Python Django. In my views.py, I have the following:

from django.shortcuts import render
from django.http import HttpResponse
from django.template.loader import get_template
from django.template import Context
# Create your views here.

def hello(request):
    name = 'Mike'
    html = '<html><body>Hi %s, this seems to have !!!!worked!</body></html>' % name
    return HttpResponse(html)

def hello2(request):
    name = 'Andrew'
    html = '<html><body>Hi %s, this seems to have !!!!worked!</body></html>' % name
    return HttpResponse(html)

# -*- coding: utf-8 -*-
def hello3_template(request):
    name = u'哈哈'
    t = get_template('hello3.html')
    html = t.render(Context({'name' : name}))
    return HttpResponse(html)

I got the following error:

SyntaxError at /hello3_template/

Non-ASCII character '\xe5' in file D:\WinPython-32bit-2.7.5.3\django_test\article\views.py on line 19, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details (views.py, line 19)

I look up that link, but I am still puzzled on how to resolve it.

Could you help? Thanks, smallbee

As lalo points out, the following line has to be on the top

# -*- coding: utf-8 -*-

Thank you, all.


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 must
be placed into the source files either as first or second
line in the file, such as:

So, you code must begin:

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

Hope helps