【发布时间】:2010-11-09 07:16:19
【问题描述】:
我有字符串
u"Played Mirror's Edge\u2122"
应该显示为
Played Mirror's Edge™
但这是另一个问题。我手头的问题是我将其放入模型中,然后尝试将其保存到数据库中。又名:
a = models.Achievement(name=u"Played Mirror's Edge\u2122")
a.save()
我得到了:
'ascii' codec can't encode character u'\u2122' in position 13: ordinal not in range(128)
完整的堆栈跟踪(根据要求):
Traceback:
File "/var/home/ptarjan/django/mysite/django/core/handlers/base.py" in get_response
86. response = callback(request, *callback_args, **callback_kwargs)
File "/var/home/ptarjan/django/mysite/yourock/views/alias.py" in import_all
161. types.import_all(type, alias)
File "/var/home/ptarjan/django/mysite/yourock/types/types.py" in import_all
52. return modules[type].import_all(siteAlias, alias)
File "/var/home/ptarjan/django/mysite/yourock/types/xbox.py" in import_all
117. achiever = self.add_achievement(dict, siteAlias, alias)
File "/var/home/ptarjan/django/mysite/yourock/types/base_profile.py" in add_achievement
130. owner = siteAlias,
File "/var/home/ptarjan/django/mysite/django/db/models/query.py" in get
304. num = len(clone)
File "/var/home/ptarjan/django/mysite/django/db/models/query.py" in __len__
160. self._result_cache = list(self.iterator())
File "/var/home/ptarjan/django/mysite/django/db/models/query.py" in iterator
275. for row in self.query.results_iter():
File "/var/home/ptarjan/django/mysite/django/db/models/sql/query.py" in results_iter
206. for rows in self.execute_sql(MULTI):
File "/var/home/ptarjan/django/mysite/django/db/models/sql/query.py" in execute_sql
1734. cursor.execute(sql, params)
File "/var/home/ptarjan/django/mysite/django/db/backends/util.py" in execute
19. return self.cursor.execute(sql, params)
File "/var/home/ptarjan/django/mysite/django/db/backends/mysql/base.py" in execute
83. return self.cursor.execute(query, args)
File "/usr/lib/pymodules/python2.5/MySQLdb/cursors.py" in execute
151. query = query % db.literal(args)
File "/usr/lib/pymodules/python2.5/MySQLdb/connections.py" in literal
247. return self.escape(o, self.encoders)
File "/usr/lib/pymodules/python2.5/MySQLdb/connections.py" in string_literal
180. return db.string_literal(obj)
Exception Type: UnicodeEncodeError at /import/xbox:bob
Exception Value: 'ascii' codec can't encode character u'\u2122' in position 13: ordinal not in range(128)
以及模型的相关部分:
class Achievement(MyBaseModel):
name = models.CharField(max_length=100, help_text="A human readable achievement name")
我在我的 settings.py 中使用 MySQL 后端
DEFAULT_CHARSET = 'utf-8'
所以基本上,我到底应该如何处理所有这些 unicode 的东西?如果我远离有趣的字符集并坚持使用 UTF8,我希望这一切都能“正常工作”。唉,这似乎没那么容易。
【问题讨论】:
-
听起来好像不喜欢单引号(')字符...
-
怎么回事?我认为它在 \u2122 上很无聊......
-
你能提供其余的堆栈跟踪吗?实际的数据库代码可能正确处理了您的 unicode 字符串,但是某处的某些日志记录代码搞砸了。
-
并尝试缩小问题:models.Achievement.objects.create(name=u"\u2122") models.Achievement.objects.create(name=u"Played Mirror's Edge")
-
你使用什么数据库排序规则?
标签: python mysql django unicode django-models