【发布时间】:2016-04-10 10:00:11
【问题描述】:
尝试通过管理员访问数据库时出现此错误
UnicodeEncodeError at /admin/nota_app/demographic/
Exception Type: UnicodeEncodeError
Exception Value: 'ascii' codec can't encode character u'\x8e' in position 0: ordinal not in range(128)
这就是我的模型:
@python_2_unicode_compatible
class Demographic(models.Model):
status = models.CharField(max_length = 100)
region = models.CharField(max_length = 50)
...
我正在以这种方式保存对象:
new_demographic = Demographic(
status = smart_unicode(my_dict[i]['status']),
region = smart_unicode(my_dict[i]['network']),
...
)
new_demographic.save()
我也尝试过使用unicode() 和encode('utf-8') 方法,但遗憾的是,它们也没有效果。谁能帮我解决这个问题?
这是完整的回溯:
UnicodeEncodeError at /admin/nota_app/demographic/
'ascii' codec can't encode character u'\x8e' in position 0: ordinal not in range(128)
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/nota_app/demographic/
Django Version: 1.7.9
Exception Type: UnicodeEncodeError
Exception Value:
'ascii' codec can't encode character u'\x8e' in position 0: ordinal not in range(128)
Exception Location: C:\Users\KESHAV\Desktop\StackQueue\nota\nota_app\models.py in __str__, line 87
Python Executable: C:\Users\KESHAV\Desktop\StackQueue\Scripts\python.exe
Python Version: 2.7.10
Python Path:
['C:\\Users\\KESHAV\\Desktop\\StackQueue\\nota',
'C:\\Windows\\system32\\python27.zip',
'C:\\Users\\KESHAV\\Desktop\\StackQueue\\DLLs',
'C:\\Users\\KESHAV\\Desktop\\StackQueue\\lib',
'C:\\Users\\KESHAV\\Desktop\\StackQueue\\lib\\plat-win',
'C:\\Users\\KESHAV\\Desktop\\StackQueue\\lib\\lib-tk',
'C:\\Users\\KESHAV\\Desktop\\StackQueue\\Scripts',
'C:\\Python27\\Lib',
'C:\\Python27\\DLLs',
'C:\\Python27\\Lib\\lib-tk',
'C:\\Users\\KESHAV\\Desktop\\StackQueue',
'C:\\Users\\KESHAV\\Desktop\\StackQueue\\lib\\site-packages']
Server time: Wed, 6 Jan 2016 16:28:48 +0000
【问题讨论】:
-
请显示完整的回溯。
-
已编辑,请查看。
-
回溯告诉您错误发生在第 87 行,在您的
__str__方法中。这是Demographic模型的__str__方法吗?它看起来像什么? -
它只是简单地从对象返回信息,这是
return str(self.region+", "+self.country)这一行 -
我现在将代码更改为
return str(self.region.encode("utf-8")+", "+self.country.encode("utf-8")),现在回溯在C:\Users\KESHAV\Desktop\StackQueue\lib\site-packages\django\utils\encoding.py in <lambda>, line 38处显示错误
标签: python django unicode encoding python-unicode