![](/img/trans.png)
[英]UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9'
[英]UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9'
我在django 1.5的views.py中处理ajax的脚本。 在构建我的json文件之后,我必须将用户名放入cookie中。 该名称的法语口音名称如'hervé'。 这是我的代码的一部分
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)
出现的错误是
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 4: ordinal not in range(128)
解决这个问题我使用unicode(),decode()......但没有任何改变。 错误来自set_cookie()函数吗? 还是json文件? 我能做些什么来解决它?
这是set_cookies函数
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)
好了,我现在修好了。 在views.py的头部,放置这个解释器
# -*- coding: latin-1 -*-
然后在你的功能,
name = 'Hervé'
name.decode('latin-1').encode('ascii','xmlcharrefreplace') //add this line
jsondict['success'] = True
jsondict['text']['welcome'] = 'Bienvenue, %s!' % name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.