Thursday, February 11, 2016

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

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

Le jeudi 11 février 2016 19:55:10 UTC-5, JHeasly a écrit :
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

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/631ded45-5e87-4fff-89bd-d9d9306a880f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment