Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`__unicode__()` addition not working in basic poll application in Django tutorial

Tags:

django

I'm working through the Django tutorial after having installed the development source of Django along with PostgreSQL from source and everything else needed from source. I'm trying to do everything with python3 instead of python on Ubuntu 12.10.

Everything seemed to be going well until I got to the part in the tutorial where we're supposed to redefine __unicode__() in order to return a sensible result when we ask for objects.all() from a table. It's not working at all. I decided to try __str__(), and it worked!

But, the tutorial explains we're not supposed to redefine __str__(). So, what's wrong with my install that __unicode__() doesn't work while __str__() does? Other methods from the tutorial work fine.

like image 535
Colin Keenan Avatar asked Nov 13 '12 08:11

Colin Keenan


1 Answers

Strings are handled differently in Python 3 vs 2.

In 2, __str__() returned bytes, while __unicode__() returned characters. In 3, __str__() now returns characters, as strings are now natively unicode, and __unicode__() doesn't exist. If you really need the old 2 behavior for __str__(), I believe it is now __bytes__().

Short answer, stick with __str__() if you are using Python 3, and realize that the Django tutorials explicitly state they are written for 2.x, so there will be differences.

like image 163
Chris Avatar answered Oct 21 '22 19:10

Chris