3

I got views.py:

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

And I got error:

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 value In database this field is utf8_bin. In model this field is 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

I tried also:

object.myfield.decode("utf8")

And got error:

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

I have administration side of this object - and everything works perfect, even with utf-8 symbols.

And if I print out type of object.myfield, then i get:

<type 'str'>
4
  • I don't know about the first bit of your question, but the last bit where you get a "can't encode" while attempting to decode a value happens in Python 2.x when you try to decode a unicode string: Python will encode it first (with the ascii codec) so that it can attempt to decode it. That says to me your field is already unicode so the main problem probably isn't in the lines you showed us but elsewhere when something tries to encode the unicode value to ascii. Commented Dec 2, 2014 at 16:01
  • Is myfield a foreign key? If it is, can you post __str__() and __unicode__() of related model? Commented Dec 2, 2014 at 17:25
  • Duncan, my code throws first error till decode() part - in this part "u"test %s" % object.myfield" Commented Dec 2, 2014 at 20:58
  • danhip, no it is not ForeignKey, just CharField Commented Dec 2, 2014 at 20:58

1 Answer 1

1

Try this

def myview(request):
    object = MyObject.objects.get(id = 1)
    testvar = u"test %s" % object.myfield.**decode('utf-8')**
Sign up to request clarification or add additional context in comments.

1 Comment

To make this a great answer, please explain what this does

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.