From 8e350d036ce6e12b2c2e9229c6b00d4da7823ffb Mon Sep 17 00:00:00 2001 From: Karen Tracey Date: Sun, 16 Nov 2008 18:58:43 +0000 Subject: [PATCH] Fixed #9608: Ensured a Model's default repr() is printable even if its __unicode__ method raises a Unicode error. git-svn-id: http://code.djangoproject.com/svn/django/trunk@9475 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/db/models/base.py | 6 +++++- tests/regressiontests/model_regress/models.py | 12 ++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/django/db/models/base.py b/django/db/models/base.py index f94d25c9f50..bf6588d7fee 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -266,7 +266,11 @@ class Model(object): 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__'): diff --git a/tests/regressiontests/model_regress/models.py b/tests/regressiontests/model_regress/models.py index 19d38b216c0..3c87e1c1e90 100644 --- a/tests/regressiontests/model_regress/models.py +++ b/tests/regressiontests/model_regress/models.py @@ -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.) @@ -128,5 +134,11 @@ datetime.datetime(2000, 1, 1, 6, 1, 1) >>> w +# Models with broken unicode methods should still have a printable repr +>>> b = BrokenUnicodeMethod(name="Jerry") +>>> b.save() +>>> BrokenUnicodeMethod.objects.all() +[] + """ }