Search code examples
pythondjangointernationalizationcross-browserdjango-i18n

How to save `LANGUAGE_CODE` to database with i18n switcher so that the language is not changed in different browsers in Django?


Is there any way to change the value of LANGUAGE_CODE variable in settings.py dynamically on clicking a button (sending a request)?

I want the user to have their own "default language" set for their account.

Right now the user can select their preferred language using a drop-down list, and the website gets translated perfectly, and because Django picks up the browser's language, the user need not to re-select their language after they reopen the website from the same browser.

But when they open the website from a different browser, the default language is again "English" because of the LANGUAGE_CODE variable set to en-us in settings.py.

So what I want to do is make each user have an option to select their desired language as default for them. I want to do this by making an another(similar) drop-down and ask user to select a language they want as "default" and hit the save button, and on saving, I want to change LANGUAGE_CODE's value to the one selected by the user (i.e change it dynamically). But I don't know how to change the value of LANGUAGE_CODE dynamically.

Also, there is one more problem with this approach. Say even if I was able to change this LANGUAGE_CODE variable dynamically, it would make the website have the selected language as default for ALL THE USERS and not only for that one specific user who changed it, according to Django's documentation:

LANGUAGE_CODE:

  • If the locale middleware isn’t in use, it decides which translation is served to all users.

I researched a lot, but couldn't find a solution for me. I am very new to Internationalization. Please help.


Solution

  • Of course there is, that is the whole point of translations. You've confused yourself by thinking of the "default" language; something that they've chosen is not the default, by definition.

    The Django docs explain how to set the active language for a user explicitly. You can set this on save exactly as you describe.

    You probably also want to re-set this value on login, again by passing the value from the user's profile.