Django: from user's language to the locale string - how to?
In our Django/Python/Linux stack we want to determine the correct locale from the user's language. The language might be 'de' and the locale could be something like de_DE or de_AT or even de_CH.UTF-8 - depending on what locale -a
returns. In case of ambiguity we would just use the first valid entry for the respective language.
This locale string shall than be used to determine the correct number format for instance like so:
locale.setlocale(locale.LC_ALL, user.language)
formattedValue = locale.format_string(f'%.{decimals}f', val=gram, grouping=True)
We don't want to create a relation between language code and locale string in our application - so defining a dictionary containing languages and locale strings is not something we have in mind. The information should be retrieved generically.
Any ideas how to do it in a proper way?
I ended up solving it like this - although initially not my preferred solution ...
import subprocess
def get_active_locales():
# Get all active locales on the system using the `locale -a` command
try:
result = subprocess.run(["locale", "-a"], capture_output=True, text=True, check=True)
active_locales = result.stdout.splitlines() # Split by line to get the list of locales
return active_locales
except subprocess.CalledProcessError as e:
return []