Python django.utils.translation.to_locale() Examples

The following are 19 code examples of django.utils.translation.to_locale(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.utils.translation , or try the search function .
Example #1
Source File: currency_filters.py    From django-accounting with MIT License 6 votes vote down vote up
def currency_formatter(value, currency=None):
    """
    Format decimal value as currency
    """
    try:
        value = D(value)
    except (TypeError, InvalidOperation):
        return ""
    # Using Babel's currency formatting
    # http://babel.pocoo.org/docs/api/numbers/#babel.numbers.format_currency
    currency = currency or settings.ACCOUNTING_DEFAULT_CURRENCY
    kwargs = {
        'currency': currency,
        'format': getattr(settings, 'CURRENCY_FORMAT', None),
        'locale': to_locale(get_language()),
    }
    return format_currency(value, **kwargs) 
Example #2
Source File: react_locales_utils.py    From marsha with MIT License 6 votes vote down vote up
def react_locale(value):
    """
    Convert a language (simple ISO639-1 or full language with regions) to an ISO15897 locale.

    This locale is supported by the react frontend.
    """
    value_locale = to_locale(value)
    # pylint: disable=unsupported-membership-test
    if value_locale in settings.REACT_LOCALES:
        return value_locale
    # pylint: disable=not-an-iterable
    for locale in settings.REACT_LOCALES:
        if locale[:2] == value_locale:
            return locale
    raise ImproperlyConfigured(
        f"{value:s} does not correspond to any locale supported by the React frontend."
    ) 
Example #3
Source File: formats.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def iter_format_modules(lang):
    """
    Does the heavy lifting of finding format modules.
    """
    if check_for_language(lang):
        format_locations = ['django.conf.locale.%s']
        if settings.FORMAT_MODULE_PATH:
            format_locations.append(settings.FORMAT_MODULE_PATH + '.%s')
            format_locations.reverse()
        locale = to_locale(lang)
        locales = [locale]
        if '_' in locale:
            locales.append(locale.split('_')[0])
        for location in format_locations:
            for loc in locales:
                try:
                    yield import_module('.formats', location % loc)
                except ImportError:
                    pass 
Example #4
Source File: classified.py    From django-classified with MIT License 6 votes vote down vote up
def currency(value, currency=None):
    """
    Format decimal value as currency
    """
    try:
        value = D(value)
    except (TypeError, InvalidOperation):
        return ""

    # Using Babel's currency formatting
    # http://babel.pocoo.org/en/latest/api/numbers.html#babel.numbers.format_currency

    kwargs = {
        'currency': currency or CURRENCY,
        'locale': to_locale(get_language() or settings.LANGUAGE_CODE)
    }

    return format_currency(value, **kwargs) 
Example #5
Source File: views.py    From zing with GNU General Public License v3.0 5 votes vote down vote up
def get_alt_src_langs(request, user, translation_project):
    language = translation_project.language
    project = translation_project.project
    source_language = project.source_language

    langs = user.alt_src_langs.exclude(id__in=(language.id, source_language.id)).filter(
        translationproject__project=project
    )

    if not user.alt_src_langs.count():
        from pootle_language.models import Language

        accept = request.META.get("HTTP_ACCEPT_LANGUAGE", "")

        for accept_lang, __ in parse_accept_lang_header(accept):
            if accept_lang == "*":
                continue

            simplified = data.simplify_to_common(accept_lang)
            normalized = to_locale(data.normalize_code(simplified))
            code = to_locale(accept_lang)
            if normalized in (
                "en",
                "en_US",
                source_language.code,
                language.code,
            ) or code in ("en", "en_US", source_language.code, language.code):
                continue

            langs = Language.objects.filter(
                code__in=(normalized, code), translationproject__project=project,
            )
            if langs.count():
                break

    return langs


#
# Views used with XMLHttpRequest requests.
# 
Example #6
Source File: util_tags.py    From donate-wagtail with Mozilla Public License 2.0 5 votes vote down vote up
def to_known_locale(code):
    code = LOCALE_MAP.get(code, code)
    return to_locale(code)


# Generates a sorted list of currently supported locales. For each locale, the list
# contains the locale code and the local name of the locale.
# To sort the list by local names, we use:
# - Case folding, in order to do case-insensitive comparison, and more.
# - String normalization using the Normalization Form Canonical Decomposition, to compare
#   canonical equivalence (e.g. without diacritics) 
Example #7
Source File: manythings.py    From ls.joyous with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def toDaysOffsetStr(offset):
    retval = ""
    if offset <= -2:
        n = num2words(-offset, lang=to_locale(get_language()), to="cardinal")
        retval = _("{N} days before").format(N=n.capitalize())
    elif offset == -1:
        retval = _("The day before")
    elif offset == 1:
        retval = _("The day after")
    elif offset >= 2:
        n = num2words(offset, lang=to_locale(get_language()), to="cardinal")
        retval = _("{N} days after").format(N=n.capitalize())
    return retval

# ------------------------------------------------------------------------------ 
Example #8
Source File: manythings.py    From ls.joyous with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _n2w(n, to):
    try:
        return num2words(n, lang=to_locale(get_language()), to=to)
    except NotImplementedError:
        # fall back to gettext for these words
        gettext_noop("first")
        gettext_noop("second")
        gettext_noop("third")
        gettext_noop("fourth")
        gettext_noop("fifth")
        return _(num2words(n, lang="en", to=to))

# ------------------------------------------------------------------------------ 
Example #9
Source File: user_language.py    From iguana with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def get_user_locale():
    lang = get_user_language()
    return to_locale(lang) 
Example #10
Source File: utils.py    From ecommerce with GNU Affero General Public License v3.0 5 votes vote down vote up
def format_currency(currency, amount, format=None, locale=None):  # pylint: disable=redefined-builtin
    locale = locale or to_locale(get_language())
    format = format or getattr(settings, 'OSCAR_CURRENCY_FORMAT', None)

    return default_format_currency(
        amount,
        currency,
        format=format,
        locale=locale
    ) 
Example #11
Source File: context_processors.py    From yournextrepresentative with GNU Affero General Public License v3.0 5 votes vote down vote up
def locale(request):
    """Convert the language string to a locale"""
    """Copied from: http://stackoverflow.com/a/6362929 """
    return {'LOCALE': to_locale(get_language())} 
Example #12
Source File: gettext.py    From zing with GNU General Public License v3.0 5 votes vote down vote up
def tr_lang(language_name):
    """Translates language names."""
    language_code = translation.get_language()
    if language_code is None:
        language_code = settings.LANGUAGE_CODE
    language_code = translation.to_locale(language_code)

    return langdata.tr_lang(language_code)(language_name) 
Example #13
Source File: core_tags.py    From rdmo with Apache License 2.0 5 votes vote down vote up
def render_lang_template(template_name):
    loc = to_locale(get_language())
    lst = [
        template_name + '_' + loc + '.html',
        template_name + '_' + settings.LANGUAGES[0][0] + '.html',
        template_name + '_en.html',
        template_name + '.html'
    ]
    for el in lst:
        try:
            t = get_template(el)
            return t.render()
        except TemplateDoesNotExist:
            pass
    return '' 
Example #14
Source File: emails.py    From karrot-backend with GNU Affero General Public License v3.0 5 votes vote down vote up
def prepare_activity_conversation_message_notification(user, messages):
    activity = target_from_messages(messages)
    language = language_for_user(user)
    with translation.override(language):
        with timezone.override(activity.place.group.timezone):
            weekday = format_date(
                activity.date.start.astimezone(timezone.get_current_timezone()),
                'EEEE',
                locale=translation.to_locale(language),
            )
            time = format_time(
                activity.date.start,
                format='short',
                locale=translation.to_locale(language),
                tzinfo=timezone.get_current_timezone(),
            )
            date = format_date(
                activity.date.start.astimezone(timezone.get_current_timezone()),
                format='long',
                locale=translation.to_locale(language),
            )

            long_date = '{} {}, {}'.format(weekday, time, date)
            short_date = '{} {}'.format(weekday, time)

            reply_to_name = _('Pickup %(date)s') % {
                'date': short_date,
            }
            conversation_name = _('Pickup %(date)s') % {
                'date': long_date,
            }

        return prepare_message_notification(
            user,
            messages,
            group=activity.place.group,
            reply_to_name=reply_to_name,
            conversation_name=conversation_name,
            conversation_url=activity_detail_url(activity),
            stats_category='activity_conversation_message'
        ) 
Example #15
Source File: email_utils.py    From karrot-backend with GNU Affero General Public License v3.0 5 votes vote down vote up
def time_filter(value):
    return format_time(
        value,
        format='short',
        locale=to_locale(get_language()),
        tzinfo=get_current_timezone(),
    ) 
Example #16
Source File: email_utils.py    From karrot-backend with GNU Affero General Public License v3.0 5 votes vote down vote up
def date_filter(value):
    return format_date(
        value.astimezone(get_current_timezone()),
        format='full',
        locale=to_locale(get_language()),
    ) 
Example #17
Source File: translation.py    From open-synthesis with GNU General Public License v3.0 5 votes vote down vote up
def get_current_locale():
    """Return the locale for the current language."""
    return to_locale(get_language()) 
Example #18
Source File: format_filters.py    From django-accounting with MIT License 5 votes vote down vote up
def percentage_formatter(value):
    if value or value == 0:
        kwargs = {
            'locale': to_locale(get_language()),
            'format': "#,##0.00 %",
        }
        return format_percent(value, **kwargs) 
Example #19
Source File: forms.py    From avos with Apache License 2.0 4 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(UserSettingsForm, self).__init__(*args, **kwargs)

        # Languages
        def get_language_display_name(code, desc):
            try:
                desc = translation.get_language_info(code)['name_local']
                desc = string.capwords(desc)
            except KeyError:
                # If a language is not defined in django.conf.locale.LANG_INFO
                # get_language_info raises KeyError
                pass
            return "%s (%s)" % (desc, code)
        languages = [(k, get_language_display_name(k, v))
                     for k, v in settings.LANGUAGES]
        self.fields['language'].choices = languages

        # Timezones
        timezones = []
        language = translation.get_language()
        current_locale = translation.to_locale(language)
        babel_locale = babel.Locale.parse(current_locale)
        for tz, offset in self._sorted_zones():
            try:
                utc_offset = _("UTC %(hour)s:%(min)s") % {"hour": offset[:3],
                                                          "min": offset[3:]}
            except Exception:
                utc_offset = ""

            if tz == "UTC":
                tz_name = _("UTC")
            elif tz == "GMT":
                tz_name = _("GMT")
            else:
                tz_label = babel.dates.get_timezone_location(
                    tz, locale=babel_locale)
                # Translators:  UTC offset and timezone label
                tz_name = _("%(offset)s: %(label)s") % {"offset": utc_offset,
                                                        "label": tz_label}
            timezones.append((tz, tz_name))

        self.fields['timezone'].choices = timezones