django.utils.encoding.DjangoUnicodeDecodeError [英] django.utils.encoding.DjangoUnicodeDecodeError

查看:246
本文介绍了django.utils.encoding.DjangoUnicodeDecodeError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当尝试通过通用关系向Django模型添加条目时,出现以下错误.

I got the following error when tried to add an entry to a Django model via generic relations.

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.

Table's charset is utf8 and collation is utf8_general_ci.

这是否意味着文件名不是有效的utf8字符串?如何解决此错误,或者我们可以将无效字符串转换为有效格式?

Does it mean that the filename is not a valid utf8 string? How to fix this error or can we convert the invalid string to a valid format?

推荐答案

您的文件系统显然未使用UTF-8编码:

Your file system is apparently not using UTF-8 encoding:

>>> 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:

Only now I've realized that the string you got is actually already unicode. Try using this to get unicode:

>>> a.decode('raw_unicode_escape')
u'ASL/60Styles_Timeless-3_\xb8 CaLe.asl'

这篇关于django.utils.encoding.DjangoUnicodeDecodeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆