Howto: Default value for datetime field in plone5 without using plone.directives

Hi Plone addon developers!

Cleaning our code from Grok relicts I stumbled over the following problem:
HowTo set a default value to a plone.supermodel.model schema using schema hints in Plone5?

The current documentation uses plone.directives which is GROK infested:

from plone.directives import form
...
@form.default_value(field=IMySchema['start'])
def startDefaultValue(data):
     return datetime.datetime.today()

Is there a plone5 solution not using GROK?

Best regards

Volker

1 Like

Not sure about the best or canonical solution but at least in DX behaviors I frequently use the following pattern:

It allows me to assign DX fields as property with custom getter/setter methods and in my case with fixed default values. I assume that you can extend the getter implementation easily with support for default methods.
There is likely something in the plone.supermodel - I remember having used a default method once but on the XML level of a model.

-aj

1 Like
import datetime
from zope.component import provideAdapter
from z3c.form import widget

DefaultStartDate = widget.ComputedWidgetAttribute(
    lambda adapter: datetime.datetime.today()',
    field=IMySchema['start'])

provideAdapter(DefaultStartDate, name='default')

Off-topic but
...best example why the complete ZCA pattern for average Python programmers sucks.

-aj

1 Like

IMO the best way to do this is to use defaultFactory in your schema:

start = schema.Date(
    title='Start',
    defaultFactory=datetime.datetime.today,
)

This has the advantage of not being tied to a particular form library, as well as being the most readable solution proposed. Dexterity's __getattr__ is aware of defaultFactory and will calculate the default if you try to fetch an attribute that doesn't have a value stored. (So beware; if you don't set a value then you'll get a new date if you access the default again tomorrow.)

You can also write context-dependent default factories; see https://pypi.python.org/pypi/zope.schema#id16

1 Like

You can also use <defaultFactory>dotted.path.to.factory</defaultFactory> in an XML supermodel, as long as the factory provides the plone.supermodel.interfaces.IDefaultFactory marker interface (for security to make sure that TTW schema editors can't reference arbitrary Python functions).

1 Like

Oh hey, look, we even have this covered in the documentation: http://docs.plone.org/external/plone.app.dexterity/docs/advanced/defaults.html

2 Likes

Oh! Sorry, to dumb to find this. Sorry for the stealing your time.