Python / Django UnicodeDecodeError' ascii'编解码器无法解码

时间:2014-12-02 15:39:02

标签: python django encoding utf-8

我得到了views.py:

# -*- coding: UTF-8 -*-
def myview(request):
    object = MyObject.objects.get(id = 1)
    testvar = u"test %s" % object.myfield

我得到了错误:

UnicodeDecodeError at /myurl
'ascii' codec can't decode byte 0xc4 in position 1: ordinal not in range(128)

Unicode error hint
The string that could not be encoded/decoded was: J������

J - myfield值 在数据库中,此字段为utf8_bin。 在模型中,此字段为CharField

sys.getfilesystemencoding() #-  UTF-8
sys.getdefaultencoding() #- ascii
sys.getdefaultencoding() #- ascii
locale.getdefaultlocale() #- ('en_US', 'UTF-8')
locale.getlocale() #- (None, None)

Python 2.7.6 Django 1.5.8

我也试过了:

object.myfield.decode("utf8")

得到错误:

UnicodeEncodeError at /myurl
'ascii' codec can't encode characters in position 6-10: ordinal not in range(128)

我有这个对象的管理方面 - 即使使用utf-8符号,一切都很完美。

如果我打印出object.myfield的类型,那么我得到:

<type 'str'>

1 个答案:

答案 0 :(得分:0)

试试这个

def myview(request):
    object = MyObject.objects.get(id = 1)
    testvar = u"test %s" % object.myfield.**decode('utf-8')**