[英]UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9'
i work on ajax's script in views.py of django 1.5. 我在django 1.5的views.py中处理ajax的脚本。 after build my json file, i must put username into cookies.
在构建我的json文件之后,我必须将用户名放入cookie中。 The name have french accent name like 'hervé'.
该名称的法语口音名称如'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. 解决这个问题我使用unicode(),decode()......但没有任何改变。 Is the error came from set_cookie() fonction?
错误来自set_cookie()函数吗? or json file?
还是json文件? what can i do to solve it?
我能做些什么来解决它?
this is set_cookies function 这是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)
OK now I fixed it. 好了,我现在修好了。 In the head of your views.py, put this interpreter
在views.py的头部,放置这个解释器
# -*- 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.