简体   繁体   中英

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9'

i work on ajax's script in views.py of django 1.5. after build my json file, i must put username into cookies. The name have french accent name like 'hervé'. This is a part of my code

if user.is_active:
            login(request, user)
            name = 'Hervé'
            jsondict['success'] = True
            jsondict['text']['welcome'] = 'Bienvenue, %s!' % name

            if name:
                fn = name
    response = HttpResponse(json.dumps(jsondict, cls=DjangoJSONEncoder, ensure_ascii=False),mimetype='application/json')
    if fn:
        set_cookie(response,"full_name",fn)

error which appear is

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

to solve this i use unicode(), decode()... but nothing change. Is the error came from set_cookie() fonction? or json file? what can i do to solve it?

this is set_cookies function

def set_cookie(response, key, value, days_expire = 7):
import datetime
from django.conf import settings
if days_expire is None:
    max_age = 365 * 24 * 60 * 60  #one year
else:
    max_age = days_expire * 24 * 60 * 60 
expires = datetime.datetime.strftime(datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age), "%a, %d-%b-%Y %H:%M:%S GMT")
response.set_cookie(key, value, max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN, secure=settings.SESSION_COOKIE_SECURE or None)

OK now I fixed it. In the head of your views.py, put this interpreter

# -*- coding: latin-1 -*-

Then in your function,

name = 'Hervé'
name.decode('latin-1').encode('ascii','xmlcharrefreplace') //add this line
jsondict['success'] = True
jsondict['text']['welcome'] = 'Bienvenue, %s!' % name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM