Opened 10 years ago
Closed 10 years ago
#23036 closed Uncategorized (invalid)
In the tutorial: Why __unicode__() and not __str__()?
Reported by: | anonymous | Owned by: | nobody |
---|---|---|---|
Component: | Documentation | Version: | 1.6 |
Severity: | Normal | Keywords: | python3 |
Cc: | Triage Stage: | Unreviewed | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | yes | UI/UX: | no |
Description
https://docs.djangoproject.com/en/1.4/intro/tutorial01/
Currently says:
"""
Why unicode() and not str()?
If you’re familiar with Python, you might be in the habit of adding str() methods to your classes, not unicode() methods. We use unicode() here because Django models deal with Unicode by default. All data stored in your database is converted to Unicode when it’s returned.
Django models have a default str() method that calls unicode() and converts the result to a UTF-8 bytestring. This means that unicode(p) will return a Unicode string, and str(p) will return a normal string, with characters encoded as UTF-8.
If all of this is gibberish to you, just remember to add unicode() methods to your models. With any luck, things should Just Work for you.
"""
models.Model.str??
Type: function
String form: <function Model.str at 0x7fd0a8cefbf8>
File: /home/jlo/code/init/django/init/djangoInit/lib/python3.4/site-packages/django/db/models/base.py
Definition: models.Model.str(self)
Source:
def str(self):
if six.PY2 and hasattr(self, 'unicode'):
return force_text(self).encode('utf-8')
return '%s object' % self.class.name
If the tutorial is followed to the letter in Python 3, the user will likely be confused as to why their unicode() method doesn't seem to be making any difference. Wording in this box could stand to be updated to mention something from the documentation from https://docs.djangoproject.com/en/dev/topics/python3/#str-and-unicode-methods or at least mention that the tutorial was written with Python 2 in mind
You are reading the tutorial for Django 1.4 (pre-Python3-support), but the str/unicode documentation for the development version of Django, so it's not surprising they seem inconsistent. You'll find that the tutorial for more recent Django versions no longer recommends writing a
__unicode__
method.