Attention

This document was written for an old version of Plone, Plone 2.5.x, and was last updated 1204 days ago.

To learn how to upgrade to the current version of Plone, read the upgrade manual.

Set the default of a DateTime Field to the current date/time

by Rob Lineberger last modified Feb 04, 2009 03:03 AM
It seems like a simple task to set the default date/time when the user creates a new instance of your archetype Object. And it is -- but it took me awhile to find the answer. Maybe this will save some else some search time.

The default behavior for my ATs was that a DateTimeField using the CalendarWidget would only have the year filled in.  I wanted the value to be set to the current date and time.  I had no special requirements for accuracy, time zones, etc. 

 

The three step process is:

1)  Add this line to the area where you declare imported modules.  Note that I am lazy and used the asterisk.  You might be more conscientious and actually import the specific module necessary:

from DateTime.DateTime import *

 

2) In the Schema, make a DateTimeField and specify a default_method to populate the field:

    DateTimeField('dateAdded',
        searchable = 1,
        required = 0,
        default_method = 'getDefaultTime',
        widget = CalendarWidget(
            label = 'Date Added'
        ),
    ),

 

3) In the class definition code, skip to near the bottom and add a new method called getDefaultTime:

    def getDefaultTime(self):
        return DateTime()

 

That's it.  Your new instances should now be populated with something that approximates the current date and time.


Contribute

Something wrong or out of date? Anybody can edit or create a new article in the knowledge base. Simply create an account on this site, log in, and click the Edit button to contribute.