James Crasta committed 189fb15

Add LANGUAGES option to i18n Form to allow customizing language at runtime. Fixes #161.

Comments (0)

Files changed (3)

 - Allow blank string and the string 'false' to be considered false values
   for BooleanField (configurable). This is technically a breaking change,
   but it is not likey to affect the majority of users adversely.
+- ext.i18n form allows passing LANGUAGES to the constructor.
 Version 1.0.4


 from __future__ import unicode_literals
 from unittest import TestCase
+from wtforms import TextField, validators
 from wtforms.ext.i18n.utils import get_translations
+from wtforms.ext.i18n import form as i18n_form
 class I18NTest(TestCase):
     def test_failure(self):
         self.assertEqual(translations.gettext('Invalid Mac address.'), 'Invalid MAC address.')
+class FormTest(TestCase):
+    class F(i18n_form.Form):
+        LANGUAGES = ['en_US', 'en']
+        a = TextField(validators=[validators.Required()])
+    def test_form(self):
+        tcache = i18n_form.translations_cache
+        tcache.clear()
+        form = self.F()
+        assert ('en_US', 'en') in tcache
+        self.assertIs(form._get_translations(), tcache[('en_US', 'en')])
+        assert not form.validate()
+        self.assertEqual(form.a.errors[0], 'This field is required.')
+        form = self.F(LANGUAGES=['es'])
+        print form.LANGUAGES
+        assert len(tcache) == 2
+        assert ('es', ) in tcache
+        assert not form.validate()
+        self.assertEqual(form.a.errors[0], 'Este campo es obligatorio.')
 if __name__ == '__main__':
     from unittest import main


 translations_cache = {}
 class Form(form.Form):
     Base form for a simple localized WTForms form.
         LANGUAGES = ['en_GB', 'en']
+    One can also provide the languages by passing `LANGUAGES=` to the
+    constructor of the form.
     Translations objects are cached to prevent having to get a new one for the
-    same languages every instantiation. 
+    same languages every instantiation.
     LANGUAGES = None
+    def __init__(self, *args, **kwargs):
+        if 'LANGUAGES' in kwargs:
+            self.LANGUAGES = kwargs.pop('LANGUAGES')
+        super(Form, self).__init__(*args, **kwargs)
     def _get_translations(self):
         languages = tuple(self.LANGUAGES) if self.LANGUAGES else None
         if languages not in translations_cache: