1
0
mirror of https://github.com/django/django.git synced 2025-07-04 09:49:12 +00:00

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
This commit is contained in:
Malcolm Tredinnick 2007-04-22 03:13:00 +00:00
parent b30e5b5434
commit 9470a6c5bb
2 changed files with 21 additions and 2 deletions

View File

@ -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):

View File

@ -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'
"""}