diff options
Diffstat (limited to 'parts/django/tests/modeltests/str')
-rw-r--r-- | parts/django/tests/modeltests/str/__init__.py | 0 | ||||
-rw-r--r-- | parts/django/tests/modeltests/str/models.py | 33 | ||||
-rw-r--r-- | parts/django/tests/modeltests/str/tests.py | 23 |
3 files changed, 56 insertions, 0 deletions
diff --git a/parts/django/tests/modeltests/str/__init__.py b/parts/django/tests/modeltests/str/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/parts/django/tests/modeltests/str/__init__.py diff --git a/parts/django/tests/modeltests/str/models.py b/parts/django/tests/modeltests/str/models.py new file mode 100644 index 0000000..84b8d67 --- /dev/null +++ b/parts/django/tests/modeltests/str/models.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +""" +2. Adding __str__() or __unicode__() to models + +Although it's not a strict requirement, each model should have a +``_str__()`` or ``__unicode__()`` 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. + +Normally, you should write ``__unicode__()`` method, since this will work for +all field types (and Django will automatically provide an appropriate +``__str__()`` method). However, you can write a ``__str__()`` method directly, +if you prefer. You must be careful to encode the results correctly, though. +""" + +from django.db import models + +class Article(models.Model): + headline = models.CharField(max_length=100) + pub_date = models.DateTimeField() + + def __str__(self): + # Caution: this is only safe if you are certain that headline will be + # in ASCII. + return self.headline + +class InternationalArticle(models.Model): + headline = models.CharField(max_length=100) + pub_date = models.DateTimeField() + + def __unicode__(self): + return self.headline
\ No newline at end of file diff --git a/parts/django/tests/modeltests/str/tests.py b/parts/django/tests/modeltests/str/tests.py new file mode 100644 index 0000000..4e4c765 --- /dev/null +++ b/parts/django/tests/modeltests/str/tests.py @@ -0,0 +1,23 @@ + # -*- coding: utf-8 -*- +import datetime + +from django.test import TestCase + +from models import Article, InternationalArticle + +class SimpleTests(TestCase): + def test_basic(self): + a = Article.objects.create( + headline='Area man programs in Python', + pub_date=datetime.datetime(2005, 7, 28) + ) + self.assertEqual(str(a), 'Area man programs in Python') + self.assertEqual(repr(a), '<Article: Area man programs in Python>') + + def test_international(self): + a = InternationalArticle.objects.create( + headline=u'Girl wins €12.500 in lottery', + pub_date=datetime.datetime(2005, 7, 28) + ) + # The default str() output will be the UTF-8 encoded output of __unicode__(). + self.assertEqual(str(a), 'Girl wins \xe2\x82\xac12.500 in lottery')
\ No newline at end of file |