diff --git a/django/db/models/base.py b/django/db/models/base.py index c6233f36dc..ebc4461359 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -86,6 +86,8 @@ class Model(object): return '<%s: %s>' % (self.__class__.__name__, self) def __str__(self): + if hasattr(self, '__unicode__'): + return unicode(self).encode('utf-8') return '%s object' % self.__class__.__name__ def __eq__(self, other): diff --git a/tests/modeltests/str/models.py b/tests/modeltests/str/models.py index 81230d538c..a700daddcc 100644 --- a/tests/modeltests/str/models.py +++ b/tests/modeltests/str/models.py @@ -1,11 +1,15 @@ +# -*- coding: utf-8 -*- """ -2. Adding __str__() to models +2. Adding __str__() or __unicode__() to models Although it's not a strict requirement, each model should have a ``__str__()`` method to return a "human-readable" representation of the object. Do this not only for your own sanity when dealing with the interactive prompt, but also because objects' representations are used throughout Django's automatically-generated admin. + +For international applications, you should write ``__unicode__``() method +instead. """ from django.db import models @@ -17,7 +21,14 @@ class Article(models.Model): def __str__(self): return self.headline -__test__ = {'API_TESTS':""" +class InternationalArticle(models.Model): + headline = models.CharField(maxlength=100) + pub_date = models.DateTimeField() + + def __unicode__(self): + return self.headline + +__test__ = {'API_TESTS':ur""" # Create an Article. >>> from datetime import datetime >>> a = Article(headline='Area man programs in Python', pub_date=datetime(2005, 7, 28)) @@ -28,4 +39,10 @@ __test__ = {'API_TESTS':""" >>> a + +>>> a1 = InternationalArticle(headline=u'Girl wins €12.500 in lottery', pub_date=datetime(2005, 7, 28)) + +# The default str() output will be the UTF-8 encoded output of __unicode__(). +>>> str(a1) +'Girl wins \xe2\x82\xac12.500 in lottery' """}