Skip to content

i18n support is frozen to default language instead of being request specific #163

Closed
@codingjoe

Description

@codingjoe

Discussed in #162

Originally posted by arneatec November 2, 2022
Issue
django-select2 does not use the current active translation of Django.

Select2Mixin is only initialized on (development) server start this way:

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.i18n_name = SELECT2_TRANSLATIONS.get(get_language())

get_language() will make the best effort and return a language (for example, from the default settings.LANGUAGE_CODE = "en").

But the current language might change on a request basis, for example due to django.middleware.locale.LocaleMiddleware with a browser with Accept-Language: bg,en-US;q=0.9,en;q=0.8 header.

LocaleMiddleware will activate the 'bg' language on receiving the request and Django will translate the form to Bulgarian, but the self.i18n_name will remain 'en' for django-select2.

The Select2Mixin.media() method will thus return the 'en' language for the JS translation file.

@property
def media(self):
    ... code removed for brevity ...
    i18n_file = []
    
    if self.i18n_name in settings.SELECT2_I18N_AVAILABLE_LANGUAGES:
        i18n_file = [f"{settings.SELECT2_I18N_PATH}/{self.i18n_name}.js"]

This will prevent the select2-based controls from translating correctly. No amount of effort (e.g. setting data-language or lang in the attrs for a control) can fix this, as you would also be required to resolve the JS file name externally and swap it with the incorrect one being supplied by the media method.

Expected behavior
The django-select2 forms should be translated transparently as the rest of the form is translated.

django-select2 should check the current active translation before building the media information and also before build_attrs

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions