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 models.py file:
class Journal(models.Model):
date = models.DateTimeField(default=timezone.now)
user = models.CharField(max_length=24)
description = models.CharField(max_length=256)
def __str__(self):
ret = [" #{:0>3} on {:<12} by {}."
.format(self.id,
self.date.strftime('%Y-%m-%d %H:%M'),
self.user)]
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$ ./manage.py 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.
(InteractiveConsole)
>>> from journal.models import Journal
>>> j = Journal(user='Alex', description='Test entry')
>>> j
Traceback (most recent call last):
File "<console>", line 1, in <module>
File
"/home/alex/Py/venv/lib/python3.4/site-packages/django/db/models/base.py",
line 496, in __repr__
u = six.text_type(self)
File "/home/alex/Py/debk/journal/models.py", line 22, in __str__
self.user)]
TypeError: non-empty format string passed to object.__format__
>>> j.save()
>>> 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 django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/be4d9342d8d31cc5236a38845b8a5103%40sonic.net.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment