~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to ivle/webapp/base/forms.py

  • Committer: Matt Giuca
  • Date: 2010-02-25 06:10:18 UTC
  • Revision ID: matt.giuca@gmail.com-20100225061018-18w07kvsh2bf6386
forms: Added DateTimeValidator, which validates datestamps in our preferred format.

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17
17
 
18
18
import re
 
19
import datetime
19
20
 
20
21
import formencode
21
22
import formencode.validators
117
118
                'Must consist of a lowercase alphanumeric character followed '
118
119
                'by any number of lowercase alphanumerics, ., +, - or _.',
119
120
                value, state)
 
121
 
 
122
class DateTimeValidator(formencode.validators.FancyValidator):
 
123
    """Accepts a date/time in YYYY-MM-DD HH:MM:SS format. Converts to a
 
124
    datetime.datetime object."""
 
125
    def _to_python(self, value, state):
 
126
        """Validate and convert."""
 
127
        try:
 
128
            return datetime.datetime.strptime(value, "%Y-%m-%d %H:%M:%S")
 
129
        except ValueError, e:
 
130
            raise formencode.Invalid(str(e) + " -> " + repr(value), value, state)
 
131
            raise formencode.Invalid("Must be a timestamp in "
 
132
                "YYYY-MM-DD HH:MM:SS format", value, state)
 
133
    def _from_python(self, value, state):
 
134
        try:
 
135
            return value.strftime("%Y-%m-%d %H:%M:%S")
 
136
        except AttributeError:
 
137
            raise formencode.Invalid("Must be a datetime.datetime object")