Skip to content

Commit

Permalink
Fixed #9608: Ensured a Model's default repr() is printable even if it…
Browse files Browse the repository at this point in the history
…s __unicode__ method raises a Unicode error.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@9475 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information
kmtracey committed Nov 16, 2008
1 parent bcb4693 commit 8e350d0
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
6 changes: 5 additions & 1 deletion django/db/models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,11 @@ def __init__(self, *args, **kwargs):
signals.post_init.send(sender=self.__class__, instance=self)

def __repr__(self):
return smart_str(u'<%s: %s>' % (self.__class__.__name__, unicode(self)))
try:
u = unicode(self)
except (UnicodeEncodeError, UnicodeDecodeError):
u = '[Bad Unicode data]'
return smart_str(u'<%s: %s>' % (self.__class__.__name__, u))

def __str__(self):
if hasattr(self, '__unicode__'):
Expand Down
12 changes: 12 additions & 0 deletions tests/regressiontests/model_regress/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@ class Worker(models.Model):
def __unicode__(self):
return self.name

class BrokenUnicodeMethod(models.Model):
name = models.CharField(max_length=7)
def __unicode__(self):
return 'Názov: %s' % self.name


__test__ = {'API_TESTS': """
(NOTE: Part of the regression test here is merely parsing the model
declaration. The verbose_name, in particular, did not always work.)
Expand Down Expand Up @@ -128,5 +134,11 @@ def __unicode__(self):
>>> w
<Worker: Full-time>
# Models with broken unicode methods should still have a printable repr
>>> b = BrokenUnicodeMethod(name="Jerry")
>>> b.save()
>>> BrokenUnicodeMethod.objects.all()
[<BrokenUnicodeMethod: [Bad Unicode data]>]
"""
}

0 comments on commit 8e350d0

Please sign in to comment.