Using __str__ with DateField

1,743 views
Skip to first unread message

Andrew Diederich

unread,
Feb 10, 2007, 1:04:03 PM2/10/07
to django...@googlegroups.com
I'm setting up a simple timecard app as a django proof-of-concept.
One of my models is "Period" that specifies the end-date of the time
period (usually a Friday).

I'm not getting __repr__ right.

Trying to add a period in the admin side:

TypeError at /admin/timekeeper/period/add/
__str__ returned non-string (type datetime.date)Request Method: POST
Request URL: http://localhost:8000/admin/timekeeper/period/add/
Exception Type: TypeError
Exception Value: __str__ returned non-string (type datetime.date)
Exception Location: c:\python25\lib\site-packages\django\contrib\admin\views\main.py
in add_stage, line 256

The model:
class Period(models.Model):
end_date = models.DateField('end date')
insert_date = models.DateTimeField('date inserted', auto_now_add=True)

def __str__(self):
return self.end_date

class Admin:
pass

Is there an easy way to munge the return self.end_date into a string?

Thanks for the help.

--
Andrew Diederich

Adrian Holovaty

unread,
Feb 10, 2007, 1:17:14 PM2/10/07
to django...@googlegroups.com
On 2/10/07, Andrew Diederich <andre...@gmail.com> wrote:
> Is there an easy way to munge the return self.end_date into a string?

This is a Python requirement -- __str__() methods must return a
string. To fix the problem, wrap self.end_date in str(), like so:

return str(self.end_date)

Adrian

--
Adrian Holovaty
holovaty.com | djangoproject.com

Andrew Diederich

unread,
Feb 10, 2007, 1:23:06 PM2/10/07
to django...@googlegroups.com
On 2/10/07, Adrian Holovaty <holo...@gmail.com> wrote:
>
> On 2/10/07, Andrew Diederich <andre...@gmail.com> wrote:
> > Is there an easy way to munge the return self.end_date into a string?
>
> This is a Python requirement -- __str__() methods must return a
> string. To fix the problem, wrap self.end_date in str(), like so:
>
> return str(self.end_date)

Perfect. I thought it would be intensely easy. Thanks for the help.

--
Andrew Diederich

Reply all
Reply to author
Forward
0 new messages