diff options
| author | Simon Charette <charette.s@gmail.com> | 2015-11-11 01:30:19 -0500 |
|---|---|---|
| committer | Simon Charette <charette.s@gmail.com> | 2015-11-11 12:18:52 -0500 |
| commit | 4cd5d846d4a0a62bba6edf435a8ae9c6dcfacb43 (patch) | |
| tree | 77a9de62788e0686cf369cfed0c326f32bac59fe | |
| parent | 74365585e28174834184e659b788c917303cd98a (diff) | |
Fixed #25730 -- Made Model.__str__() always return str instances.
Thanks to Kevin Turner for the report and Tim for the review.
| -rw-r--r-- | django/db/models/base.py | 2 | ||||
| -rw-r--r-- | tests/str/tests.py | 21 |
2 files changed, 22 insertions, 1 deletions
diff --git a/django/db/models/base.py b/django/db/models/base.py index e58e50e818..1dbf0e52e2 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -463,7 +463,7 @@ class Model(six.with_metaclass(ModelBase)): def __str__(self): if six.PY2 and hasattr(self, '__unicode__'): return force_text(self).encode('utf-8') - return '%s object' % self.__class__.__name__ + return str('%s object' % self.__class__.__name__) def __eq__(self, other): if not isinstance(other, Model): diff --git a/tests/str/tests.py b/tests/str/tests.py index 03ff2b849c..6467875a5c 100644 --- a/tests/str/tests.py +++ b/tests/str/tests.py @@ -4,6 +4,8 @@ from __future__ import unicode_literals import datetime from unittest import skipIf +from django.apps.registry import Apps +from django.db import models from django.test import TestCase from django.utils import six @@ -33,3 +35,22 @@ class SimpleTests(TestCase): # output of __unicode__() -- or __str__() when the # python_2_unicode_compatible decorator is used. self.assertEqual(str(a), b'Girl wins \xe2\x82\xac12.500 in lottery') + + def test_defaults(self): + """ + The default implementation of __str__ and __repr__ should return + instances of str. + """ + test_apps = Apps(['str']) + + class Default(models.Model): + class Meta: + apps = test_apps + + obj = Default() + # Explicit call to __str__/__repr__ to make sure str()/repr() don't + # coerce the returned value. + self.assertIsInstance(obj.__str__(), str) + self.assertIsInstance(obj.__repr__(), str) + self.assertEqual(str(obj), str('Default object')) + self.assertEqual(repr(obj), str('<Default: Default object>')) |
