Skip to content

Commit

Permalink
Fallback i18n js files for zh-hans/zh-hant. (#468)
Browse files Browse the repository at this point in the history
* Fallback i18n js files for zh-hans/zh-hant.

* Use Django admin's built-in SELECT2_TRANSLATIONS to determine the lang of i18n js files.
  • Loading branch information
dzhuang authored and codingjoe committed Jun 14, 2018
1 parent 17af750 commit 496cc7c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
21 changes: 16 additions & 5 deletions django_select2/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,12 +98,23 @@ def _get_media(self):
.. Note:: For more information visit
https://docs.djangoproject.com/en/stable/topics/forms/media/#media-as-a-dynamic-property
"""
lang = get_language()
i18n_name = None
try:
# get_language() will always return a lower case language code, where some files are named upper case.
i = [x.lower() for x in settings.SELECT2_I18N_AVAILABLE_LANGUAGES].index(get_language())
i18n_file = ('%s/%s.js' % (settings.SELECT2_I18N_PATH, settings.SELECT2_I18N_AVAILABLE_LANGUAGES[i]), )
except ValueError:
i18n_file = ()
from django.contrib.admin.widgets import SELECT2_TRANSLATIONS
i18n_name = SELECT2_TRANSLATIONS.get(lang)
if i18n_name not in settings.SELECT2_I18N_AVAILABLE_LANGUAGES:
i18n_name = None
except ImportError:
# TODO: select2 widget feature needs to be backported into Django 1.11
try:
i = [x.lower() for x in settings.SELECT2_I18N_AVAILABLE_LANGUAGES].index(lang)
i18n_name = settings.SELECT2_I18N_AVAILABLE_LANGUAGES[i]
except ValueError:
pass

i18n_file = ('%s/%s.js' % (settings.SELECT2_I18N_PATH, i18n_name),) if i18n_name else ()

return forms.Media(
js=(settings.SELECT2_JS,) + i18n_file + ('django_select2/django_select2.js',),
css={'screen': (settings.SELECT2_CSS,)}
Expand Down
11 changes: 10 additions & 1 deletion tests/test_forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,13 +129,22 @@ def test_i18n(self):
'django_select2/django_select2.js'
)

translation.activate('zh-cn')
pytest.importorskip("django", minversion="2.0.4")

translation.activate('zh-hans')
assert tuple(Select2Widget().media._js) == (
'//cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js',
'//cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/i18n/zh-CN.js',
'django_select2/django_select2.js'
)

translation.activate('zh-hant')
assert tuple(Select2Widget().media._js) == (
'//cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js',
'//cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/i18n/zh-TW.js',
'django_select2/django_select2.js'
)


class TestSelect2MixinSettings(object):
def test_default_media(self):
Expand Down

0 comments on commit 496cc7c

Please sign in to comment.