在django admin中访问db时出现UnicodeEncodeError

时间:2016-01-06 10:36:33

标签: python django unicode encoding python-unicode

尝试通过管理员访问数据库时出现此错误

  

/ admin / nota_app / demographic /

中的UnicodeEncodeError
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

1 个答案:

答案 0 :(得分:1)

如果您使用@python_2_unicode_compatible,那么您的__str__方法应该返回一个unicode字符串。

你有str(self.region+", "+self.country),它试图将unicode字符串转换为Python 2中的字节字符串。要解决此问题,请将方法更改为:

def __str__(self):
    return self.region + u"," + self.country