Opened 4 years ago

Closed 4 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

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.

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/
Definition: models.Model.str(self)

def str(self):

if six.PY2 and hasattr(self, 'unicode'):

return force_text(self).encode('utf-8')

return '%s object' %

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 or at least mention that the tutorial was written with Python 2 in mind

Change History (1)

comment:1 Changed 4 years ago by Carl Meyer

Resolution: invalid
Status: newclosed

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.

Note: See TracTickets for help on using tickets.
Back to Top