Skip to main content
 首页 » 编程设计

python之django.utils.encoding.DjangoUnicodeDecodeError

2024年08月12日47linjiqin

尝试通过通用关系向 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'