Filed Under (Python) by Marcin Kuźmiński on February-8-2010
Tagged Under : , , , , , , ,

I’d created another simple application in pylons, final step was to translate it from English to Polish.

I used the babel extractor recommended by pylons and that went really smooth.

My application have a language selector available anytime from menu.
I saw that even this switch worked very well for mako templates and string inside controllers,
it did not work when displaying my custom messages that i over rid in validators
and also did not work in my own custom validators that inherit from FancyValidator.
So i started to investigate this.

The first problem of not translating custom error messages in the regular formencode validators was easily being fixed by using lazy_ugettex method.

def _(s):
    #fix for translation error messages
    return lazy_ugettext(s)

This method allowed me to use lazy_ugettext to translate.
So now when in the validators your translating a string using _(‘this string is for translate’) method it’s actually wrapper for lazy_ugettext function.
Lazy translation is when you translate a string when it is accessed, not when the _() or other functions are called.

The second problem of translating custom error messages in your own validator was a bigger problem

I was looking for a solution for some time, and found a nice trick. You have to use your own
state_obj with static _() function. As example below for custom validation function.

class ValidLoginNames(formencode.validators.FancyValidator):

    messages = {'invalid_name':_('you cannot use %(username)s as login')}

    def validate_python(self, value, state):
        banned_names = ['admin', 'administrator', 'root']
        if value in banned_names:
            raise formencode.Invalid(self.message('invalid_name', state = State_obj, username = value), value, state)

#this is needed to translate the messages using _()
class State_obj(object):
    _ = staticmethod(_)

Those two trick now let’s you translate custom validators without a problem.



Post a comment
Name:  * required
Email:  * required
URL: 
Comments: