## ## datewidget.py ## Login : ## Started on Wed May 11 15:53:35 2011 Uli Fouquet ## $Id$ ## ## Copyright (C) 2011 Uli Fouquet ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ## """ A datewidget with customizable date format. """ from datetime import datetime from zope.formlib.i18n import _ from zope.formlib.interfaces import ConversionError from zope.formlib.textwidgets import DateWidget, DateDisplayWidget, escape from zope.formlib.widget import renderElement class FormattedDateWidget(DateWidget): """A date widget that supports different (and _explicit_) date formats. This is an input widget. """ date_format = '%Y-%m-%d' def _toFieldValue(self, input): if input == self._missing: return self.context.missing_value else: try: value = datetime.strptime(input, self.date_format) except (ValueError, IndexError), v: raise ConversionError(_("Invalid datetime data"), v) return value.date() def _toFormValue(self, value): if value: value = value.strftime(self.date_format) return value class FormattedDateDisplayWidget(DateDisplayWidget): """A date widget that supports different (and _explicit_) date formats. This is a display widget. """ date_format = '%Y-%m-%d' def __call__(self): if self._renderedValueSet(): content = self._data else: content = self.context.default if content == self.context.missing_value: return "" content = content.strftime(self.date_format) return renderElement("span", contents=escape(content), cssClass=self.cssClass)