__unicode__ rather than __str__ in Part 2 of 'Writing you first Django app"?

67 views
Skip to first unread message

JHeasly

unread,
Feb 11, 2016, 7:55:10 PM2/11/16
to Django users
In "Writing your first Django app, part 2" (https://docs.djangoproject.com/en/1.9/intro/tutorial02/), it's outlines adding a __str__() method  to your models.

But if you've got a unicode string that's called in the admin, you're going to get a big, unfriendly UnicodeEncodeError error when you load that admin change_form.html.

Wouldn't it be safer/better newbie user experience to go with a __unicode__ method instead?

— John

Simon Charette

unread,
Feb 11, 2016, 8:11:38 PM2/11/16
to Django users
Hi John,

The tutorial is oriented towards Python 3 users where the `str` type is the
equivalent of the Python 2 `unicode` hence why defining `__str__` is suggested.

You'll notice that all models example suggest decorating model classes with
the `python_2_unicode_compatible` decorator if you need to support Python 2.

This decorator makes sure the correct types are returned under the Python
version used by simply defining an `__str__` method that returns `unicode` on
Python 2 and `str` on Python 3.

This allows Django and third-party applications to support both versions in the
same code base without shipping the boilerplate required to handle the
conversion correctly.

If you can't use Python 3 now I suggest you do as documented and use the
`python_2_unicode_compatible` decorator as it will make your future transition
to Python 3 easier.

Cheers,
Simon

JHeasly

unread,
Feb 12, 2016, 3:02:25 PM2/12/16
to Django users
Hi Simon —

I was pretty sure I was missing something obvious. Thanks for pointing it out.

— John
Reply all
Reply to author
Forward
0 new messages