[Mpuls-commits] r1902 - wasko/branches/2.0/mpulsweb/lib

scm-commit@wald.intevation.org scm-commit at wald.intevation.org
Mon Mar 8 10:38:41 CET 2010


Author: torsten
Date: 2010-03-08 10:38:40 +0100 (Mon, 08 Mar 2010)
New Revision: 1902

Modified:
   wasko/branches/2.0/mpulsweb/lib/validators.py
Log:
* mpulsweb/lib/validators.py (DateOrder): New Validator to check to
correct order of two datefields. (MyDateConverter): New DateConverter
which allows dd.mm.jjjj dates. (CreateAppointmentForm): User new
Validators


Modified: wasko/branches/2.0/mpulsweb/lib/validators.py
===================================================================
--- wasko/branches/2.0/mpulsweb/lib/validators.py	2010-03-05 14:24:47 UTC (rev 1901)
+++ wasko/branches/2.0/mpulsweb/lib/validators.py	2010-03-08 09:38:40 UTC (rev 1902)
@@ -1,17 +1,22 @@
 # -*- coding: utf-8 -*-
 
 import re
+import logging
 import datetime
 
 import formencode
 from formencode import ForEach, All
-from formencode.validators import Bool, Int, String, FieldsMatch, StringBoolean
+from formencode.validators import Bool, Int, String, FieldsMatch, StringBoolean, \
+     DateConverter, DateValidator, TimeConverter, FormValidator
 
 from pylons import session
+from pylons.i18n import _
 
 from mpulsweb.lib.db import db
 
+log = logging.getLogger(__name__)
 
+
 class ValidatorStateObject:
 
     def __setattr__(self, key, value):
@@ -49,7 +54,67 @@
                                                   max=self.maxlength),
                                      value, state)
 
+class DateOrder(FormValidator):
 
+    """
+    Tests that the given datetimes are in the corrent order. First given date must
+    be smaller the second datePass the list of field names in as `field_names`.
+    """
+
+    field_names = None
+    validate_partial_form = True
+    __unpackargs__ = ('*', 'field_names')
+
+    messages = {
+        'notbefore': _("Startdatum muss vor oder gleich dem Enddatum liegen"),
+        'notDict': _("Fields should be a dictionary"),
+        }
+
+    def __init__(self, *args, **kw):
+        super(FormValidator, self).__init__(*args, **kw)
+        if len(self.field_names) < 2:
+            raise TypeError("FieldsMatch() requires at least two field names")
+
+    def validate_partial(self, field_dict, state):
+        for name in self.field_names:
+            if not field_dict.has_key(name):
+                return
+        self.validate_python(field_dict, state)
+
+    def validate_python(self, field_dict, state):
+        try:
+            ref = field_dict[self.field_names[0]]
+        except TypeError:
+            # Generally because field_dict isn't a dict
+            raise Invalid(self.message('notDict', state), field_dict, state)
+        except KeyError:
+            ref = ''
+        errors = {}
+        for name in self.field_names[1:]:
+            log.debug(ref)
+            log.debug(field_dict.get(name, ''))
+            mydate = field_dict.get(name)
+            if mydate and mydate < ref:
+                errors[name] = self.message('notbefore', state)
+        if errors:
+            error_list = errors.items()
+            error_list.sort()
+            error_message = '<br>\n'.join(
+                ['%s: %s' % (name, value) for name, value in error_list])
+            raise formencode.Invalid(error_message,
+                          field_dict, state,
+                          error_dict=errors)
+
+
+class MyDateConverter(DateConverter):
+    '''Own DateConverter which also allows Dates in dd.mm.jjjj style.'''
+
+    def __init__(self, *args, **kw):
+        super(DateConverter, self).__init__(*args, **kw)
+        if not self.month_style in ('dd/mm/yyyy', 'mm/dd/yyyy', 'dd.mm.jjjj'):
+            raise TypeError("Bad month_style: %r" % self.month_style)
+
+
 class DateCheck(formencode.validators.FancyValidator):
 
     valid_date = re.compile(r'^[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{4}$')
@@ -327,12 +392,13 @@
 
 class CreateAppointmentForm(BaseFormValidator):
 
-    start_date = All(String(not_empty=True),
-                                DateCheck())
-    start_time = All(String(not_empty=True),
-                                TimeCheck())
-    end_date = DateCheck()
-    end_time = TimeCheck()
+    start_date = MyDateConverter(not_empty=True, month_style='dd.mm.jjjj')
+    start_time = TimeConverter(not_empty=True, use_datetime=True)
+
+    end_date =  MyDateConverter(month_style='dd.mm.jjjj')
+    end_time = TimeConverter(use_datetime=True)
+
+    chained_validators = [DateOrder('start_date', 'end_date')]
     title = All(String(not_empty=True), StringTooLong(128))
 
 



More information about the Mpuls-commits mailing list