Wednesday, September 23, 2015

different behaviour of datetime.datetime object before vs after save

I'm baffled by the fact that the __str__ method of an instance fails
before the instance is saved but works fine afterwards.

The relevant snippet from my file:
class Journal(models.Model):
date = models.DateTimeField(
user = models.CharField(max_length=24)
description = models.CharField(max_length=256)
def __str__(self):
ret = [" #{:0>3} on {:<12} by {}."
.format(,'%Y-%m-%d %H:%M'),
for line in self.description.split('\n'):
ret.append(" {}".format(line))
return '\n'.join(ret)

Here's the result of some experimentation using the shell:
(venv)alex@x301:~/Py/debk$ ./ shell
Python 3.4.0 (default, Jun 19 2015, 14:18:46)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from journal.models import Journal
>>> j = Journal(user='Alex', description='Test entry')
>>> j
Traceback (most recent call last):
File "<console>", line 1, in <module>
line 496, in __repr__
u = six.text_type(self)
File "/home/alex/Py/debk/journal/", line 22, in __str__
TypeError: non-empty format string passed to object.__format__
>>> j
<Journal: #005 on 2015-09-24 06:11 by Alex.
Test entry>

I don't understand why saving would change the behavior of an instance.
I'd like my code to be able to display such an instance before a
decision is made whether or not to save it.
I'd be grateful if anyone could explain what's happening and perhaps
suggest a way to use the __str__ method before saving.

Thanks in advance for any help.

Alex K

You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to
To post to this group, send email to
Visit this group at
To view this discussion on the web visit
For more options, visit

No comments:

Post a Comment