Skip to content

Instantly share code, notes, and snippets.

@Xowap
Created September 10, 2015 11:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xowap/40da8e9f388647e219d2 to your computer and use it in GitHub Desktop.
Save Xowap/40da8e9f388647e219d2 to your computer and use it in GitHub Desktop.
Helpers for translating hstore fields in Django
# vim: fileencoding=utf-8 tw=100 expandtab ts=4 sw=4 :
#
# gmc_api
# (c) 2015 ActivKonnect
from django.core.exceptions import ValidationError
from django.utils.six import string_types
from django.utils.translation import get_language
from django.conf import settings
def get_short_language():
"""
Guess the language (without the country code) based on what Django says.
"""
l = get_language()
if not l:
l = settings.LANGUAGE_CODE
return normalize_language(l)
def normalize_language(lang):
"""
Returns a normalized version of a language, and drop the country code if needed
"""
try:
lang, _ = lang.split('-', 1)
except ValueError:
pass
return lang.lower()
def choose_language(choices):
"""
Choose a language from the choices. Preferably one that the user speaks.
If no language is provided as choice, None will be returned.
"""
l = get_short_language()
raw = None
for choice, raw in ((normalize_language(x), x) for x in choices):
if choice == l:
return raw
return raw
def localize(translations):
"""
From a {lang: translation} dict, return the most fitting translation string for the user.
"""
l = choose_language(translations.keys())
if not l:
return None
return translations[l]
def validate_translation_dict(translations):
"""
Validates that a translation dict has valid keys/values
"""
for k, v in translations.items():
if normalize_language(k) != k:
raise ValidationError('"{}" is not a valid language name'.format(k))
if not isinstance(v, string_types):
raise ValidationError('"{}" is not a string'.format(v))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment