source: main/waeup.sirp/trunk/src/waeup/sirp/widgets/datewidget.py @ 6051

Last change on this file since 6051 was 6050, checked in by uli, 14 years ago

Add date widgets that can cope with different date formats.

File size: 2.3 KB
RevLine 
[6050]1##
2## datewidget.py
3## Login : <uli@pu.smp.net>
4## Started on  Wed May 11 15:53:35 2011 Uli Fouquet
5## $Id$
6##
7## Copyright (C) 2011 Uli Fouquet
8## This program is free software; you can redistribute it and/or modify
9## it under the terms of the GNU General Public License as published by
10## the Free Software Foundation; either version 2 of the License, or
11## (at your option) any later version.
12##
13## This program is distributed in the hope that it will be useful,
14## but WITHOUT ANY WARRANTY; without even the implied warranty of
15## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16## GNU General Public License for more details.
17##
18## You should have received a copy of the GNU General Public License
19## along with this program; if not, write to the Free Software
20## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21##
22"""
23A datewidget with customizable date format.
24"""
25from datetime import datetime
26from zope.formlib.i18n import _
27from zope.formlib.interfaces import ConversionError
28from zope.formlib.textwidgets import DateWidget, DateDisplayWidget
29
30class FormattedDateWidget(DateWidget):
31    """A date widget that supports different (and _explicit_) date formats.
32
33    This is an input widget.
34    """
35    date_format = '%Y-%m-%d'
36
37    def _toFieldValue(self, input):
38        if input == self._missing:
39            return self.context.missing_value
40        else:
41            try:
42                value = datetime.strptime(input, self.date_format)
43            except (ValueError, IndexError), v:
44                raise ConversionError(_("Invalid datetime data"), v)
45        return value.date()
46
47    def _toFormValue(self, value):
48        if value:
49            value = value.strftime(self.date_format)
50        return value
51
52class FormattedDateDisplayWidget(DateDisplayWidget):
53    """A date widget that supports different (and _explicit_) date formats.
54
55    This is a display widget.
56    """
57    date_format = '%Y-%m-%d'
58
59    def __call__(self):
60        if self._renderedValueSet():
61            content = self._data
62        else:
63            content = self.context.default
64        if content == self.context.missing_value:
65            return ""
66        content = content.strftime(self.date_format)
67        return renderElement("span", contents=escape(content),
68                             cssClass=self.cssClass)
Note: See TracBrowser for help on using the repository browser.