python - django.utils.encoding.DjangoUnicodeDecodeError

标签 python django utf-8

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

相关文章:

python - 使用 Python 计算 .txt 文件中数字的平均值

python - 下载 PDF 到子目录

python - 使用 HyperlinkedModelSerializer 强制 https?

Django:urls.py 中的美元符号

python - 导入错误 : Could not import settings

python - 在 Python 中读取文件时的编码问题

php - UTF-8贯穿始终

python - JWT 如何与 django-phonenumber-field 一起工作

python - 如何将从 YAML 文件中检索到的 utf-8 文件名用于 os.path.isdir()?

python - 文件将在 "open(file_name, ' w +').write(somestr)"之后关闭