Search code examples
djangopython-2.7localizationinternationalizationdjango-i18n

Django load LANGUAGES parameter from the database


I would like to set my LANGUAGES variable dynamically by loading the values from the database.

Let's say i have a table like this

COLUMN_NAME
-----------
id
name
identifier
active

and i would like to define these languages:

LANGUAGES = (
    ('en', _('English')),
    ('de', _('German')),
    ('fr', _('French')),
)

i would need to load all languages from the table and define them in the settings file. now i don't think that running a query in the settings file is a good idea.

This way also allows me to activate and disable languages on the fly (if for example a language file contains grammar mistakes).

I really wouldn't know on how to start on this. I have searched a lot on google but i can't find anyone who has needed this system (it could be that this is also unnecessary)

any recommendations on this?


Solution

  • To this point:

    This way also allows me to activate and disable languages on the fly (if for example a language file contains grammar mistakes).

    I would recommend to not do it because you should not alter settings at runtime: https://docs.djangoproject.com/en/1.7/topics/settings/#altering-settings-at-runtime.

    One strategy you may want to consider is overriding process_request in django.middleware.locale.LocaleMiddleware to set the LANGUAGE_CODE to a default such as EN if it is not an active language in your table.

    class CustomLocaleMiddleware(LocaleMiddleware):
        def process_request(self, request):
            ...
            lang = languages.objects.get(identifier=translation.get_language())
            if lang:
                if not lang.active:
                    request.LANGUAGE_CODE = 'en'
                else:
                    request.LANGUAGE_CODE = translation.get_language()
            else:
                request.LANGUAGE_CODE = translation.get_language()
    

    You would want to compensate for prefered language codes like en-us, de-at