Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

unicode: Fixed #3996. Added check for model-specific __unicode__ meth…

…od 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
  • Loading branch information...
commit 9470a6c5bb52ac1c55d438bb8a86b92760e4ed26 1 parent b30e5b5
@malcolmt malcolmt authored
Showing with 21 additions and 2 deletions.
  1. +2 −0  django/db/models/base.py
  2. +19 −2 tests/modeltests/str/models.py
View
2  django/db/models/base.py
@@ -86,6 +86,8 @@ def __repr__(self):
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):
View
21 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 @@ def __str__(self):
>>> 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'
"""}
Please sign in to comment.
Something went wrong with that request. Please try again.