diff options
| author | Malcolm Tredinnick <malcolm.tredinnick@gmail.com> | 2007-04-22 03:13:00 +0000 |
|---|---|---|
| committer | Malcolm Tredinnick <malcolm.tredinnick@gmail.com> | 2007-04-22 03:13:00 +0000 |
| commit | 9470a6c5bb52ac1c55d438bb8a86b92760e4ed26 (patch) | |
| tree | 693d15fca725bdfbc456333a78f19ab4e9f84cf1 | |
| parent | b30e5b54346abacdd91b8ef7ec439c00f34a5ad6 (diff) | |
unicode: Fixed #3996. Added check for model-specific __unicode__ method to
default Model.__str__ method. Thanks, Ivan Sagalaev.
git-svn-id: http://code.djangoproject.com/svn/django/branches/unicode@5057 bcc190cf-cafb-0310-a4f2-bffc1f526a37
| -rw-r--r-- | django/db/models/base.py | 2 | ||||
| -rw-r--r-- | tests/modeltests/str/models.py | 21 |
2 files changed, 21 insertions, 2 deletions
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 <Article: Area man programs in Python> + +>>> 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' """} |
