我正在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)
blah = '一些包含Unicode的文本!'
这样的例子,基本上可以让我们运行。 - Joran Beasley