Saisiva A
Saisiva A

Reputation: 615

exception __str__ returned non-string (type bytes) in django

Trying to execute following methods where i get exception like exception __str__ returned non-string (type bytes).

def __unicode__(self):
    return u"{}{:02d}:{:02d}:{:05.2f}".format(
        '-' if self.sign == -1 else '', self._deghour, self.minute, self.second)

def __str__(self):
    return unicode(self).encode('utf-8')

def __repr__(self):
    return u"RADecBase('{0}')".format(self)

Upvotes: 1

Views: 1029

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 600059

You are confused about unicode vs bytes, and encoding vs decoding.

Encoding converts a (unicode) string into bytes. But the __str__ method must return a string, not bytes. There is no need to encode there.

def __str__(self):
    return unicode(self)

However I don't know how this is even working, as Python 3 doesn't define a unicode builtin and doesn't recognise the __unicode__ method. You should just do this directly in __str__:

def __str__(self):
    return "{}{:02d}:{:02d}:{:05.2f}".format(
        '-' if self.sign == -1 else '', self._deghour, self.minute, self.second)

Upvotes: 1

Related Questions