当我尝试通过通用关系向 Django 模型添加条目时,出现以下错误。
django.utils.encoding.DjangoUnicodeDecodeError: 'utf8' codec can't decode byte 0xb8 in position 24: unexpected code byte. You passed in 'ASL/60Styles_Timeless-3_\xb8 CaLe.asl' (<type 'str'>)
模型是这样的:
class MD5(models.Model):
value = models.CharField(max_length=32, db_index=True)
filename = models.CharField(max_length=100)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey()
表的字符集是 utf8,排序规则是 utf8_general_ci。
这是否意味着文件名不是有效的 utf8 字符串?如何修复此错误或者我们可以将无效字符串转换为有效格式吗?
最佳答案
您的文件系统显然没有使用 UTF-8 编码:
>>> a = 'ASL/60Styles_Timeless-3_\xb8 CaLe.asl'
>>> print a.decode('utf-8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.5/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xb8 in position 24: unexpected code byte
>>> a.decode('iso8859-2')
u'ASL/60Styles_Timeless-3_\xb8 CaLe.asl'
>>> print a.decode('iso8859-2')
ASL/60Styles_Timeless-3_¸ CaLe.asl
直到现在我才意识到你得到的字符串实际上已经是unicode了。尝试使用它来获取 unicode:
>>> a.decode('raw_unicode_escape')
u'ASL/60Styles_Timeless-3_\xb8 CaLe.asl'
关于python - django.utils.encoding.DjangoUnicodeDecodeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1767848/