Hello,

I'm trying to write a custom validator that will use localized error messages.

As I found, attempt to use lazystring in a validator's message class variable 
leads to the following error:

File "controllers.py", line 88, in ?
   class EmailValidator(validators.Email):
 File 
"C:\Python24\Lib\site-packages\FormEncode-0.4-py2.4.egg\formencode\declarative.py",
 line 84, in __new__
   cls.__classinit__(cls, new_attrs)
 File 
"C:\Python24\Lib\site-packages\FormEncode-0.4-py2.4.egg\formencode\api.py", 
line 115, in __classinit__
   cls._initialize_docstring()
 File 
"C:\Python24\Lib\site-packages\FormEncode-0.4-py2.4.egg\formencode\api.py", 
line 188, in _initialize_docstring
   default = re.sub(r'(%\(.*?\)[rsifcx])', r'``\1``', default)
 File "C:\Python24\lib\sre.py", line 142, in sub
   return _compile(pattern, 0).sub(repl, string, count)
 TypeError: Error when calling the metaclass bases expected string or buffer

OTOH, the following kind of work:

def localize_formencode_messages(f):
    from turbogears.i18n import gettext
    def wrapper(self, msgName, state, **kw):
        if self._messages.has_key(msgName):
            message = self._messages.get(msgName)
            message = gettext(message)
            return message % kw
        return f(self, msgName, state, **kw)
    return wrapper

validators.Validator.message = \
        localize_formencode_messages(validators.Validator.message)

It works unless there is compound error. In this case UnicodeEncodeError pops 
up when formencode tries to reformat the exception:

File "d:\projects\3rd-party\turbogears\turbogears\controllers.py", line 125, in 
validate
    kw = validators.to_python(kw)
  File 
"C:\Python24\Lib\site-packages\FormEncode-0.4-py2.4.egg\formencode\api.py", 
line 304, in to_python
    value = tp(value, state)
  File 
"C:\Python24\Lib\site-packages\FormEncode-0.4-py2.4.egg\formencode\schema.py", 
line 172, in _to_python
    raise Invalid(
  File 
"C:\Python24\Lib\site-packages\FormEncode-0.4-py2.4.egg\formencode\schema.py", 
line 296, in format_compound_error
    return ('%s\n' % (' '*indent)).join(
  File 
"C:\Python24\Lib\site-packages\FormEncode-0.4-py2.4.egg\formencode\schema.py", 
line 292, in format_compound_error
    return str(v)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-6: 
ordinal not in range(128)

Is there a solution, preferably one that doesn't involve patching formencode?


Reply via email to