django.utils.translation.get_language

Here are the examples of the python api django.utils.translation.get_language taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: pootle
Source File: forms.py
View license
    def format_output(self, rendered_widgets):
        from django.utils.safestring import mark_safe
        if len(rendered_widgets) == 1:
            return mark_safe(rendered_widgets[0])

        output = ''
        for i, widget in enumerate(rendered_widgets):
            output += '<div lang="%s" title="%s">' % \
                (get_language(), _('Plural Form %d', i))
            output += widget
            output += '</div>'

        return mark_safe(output)

Example 2

View license
def load_template_source(template_name, template_dirs=None):
    """Assuming the current language is German.
       If template_name is index.$LANG.html, try index.de.html then index.html
       Also replaces .. with . when attempting fallback.
    """
    if "$LANG" in template_name:
        lang = translation.get_language()
        try:
            t = template_name.replace("$LANG", lang)
            res = _load_template_source(t, template_dirs)
            return res
        except TemplateDoesNotExist: 
            t = template_name.replace("$LANG", "").replace("..",".")
            return _load_template_source(t, template_dirs)
    return _load_template_source(template_name, template_dirs)

Example 3

Project: tower
Source File: test_l10n.py
View license
def test_cached_activate():
    """
    Make sure the locale is always activated properly, even when we hit a
    cached version.
    """
    tower.deactivate_all()
    tower.activate('fr')
    eq_(translation.get_language(), 'fr')
    tower.activate('fa')
    eq_(translation.get_language(), 'fa')
    tower.activate('fr')
    eq_(translation.get_language(), 'fr')
    tower.activate('de')
    eq_(translation.get_language(), 'de')
    tower.activate('fr')
    eq_(translation.get_language(), 'fr')
    tower.activate('fa')
    eq_(translation.get_language(), 'fa')

Example 4

View license
    def _get_missing_containers(self, language_code=None):
        language_code = language_code or get_language()

        try:
            template_name = self.page_type.template_name
        except AttributeError:
            template_name = getattr(
                settings, 'FP_DEFAULT_TEMPLATE',
                defaults.FP_DEFAULT_TEMPLATE)

        cnames = self.containers.filter(
            language_code=language_code).values_list('name')
        existing_containers = [i[0] for i in cnames]

        for cname in get_container_names_from_template(template_name):
            if cname not in existing_containers:
                yield cname

Example 5

Project: django-countries
Source File: test_fields.py
View license
    def test_translated_choices(self):
        lang = translation.get_language()
        translation.activate('eo')
        form = forms.PersonForm()
        try:
            # This is just to prove that the language changed.
            self.assertEqual(list(countries)[0][1], 'Afganio')
            # If the choices aren't lazy, this wouldn't be translated. It's the
            # second choice because the first one is the initial blank option.
            self.assertEqual(
                form.fields['country'].choices[1][1], 'Afganio')
            self.assertEqual(
                form.fields['country'].widget.choices[1][1], 'Afganio')
        finally:
            translation.activate(lang)

Example 6

View license
@register.filter
def percentage(value):
    if value or value == 0:
        kwargs = {
            'locale': to_locale(get_language()),
            'format': "#,##0.00 %",
        }
        return format_percent(value, **kwargs)

Example 7

View license
    def search(self, query_string, **kwargs):
        """
        The main search method
        :param query_string: The string to pass to Elasticsearch. e.g. '*:*'
        :param kwargs: start_offset, end_offset, result_class
        :return: result_class instance
        """
        self.index_name = self._index_name_for_language(translation.get_language())
        # self.log.debug('search method called (%s): %s' %
        #                (translation.get_language(), query_string))
        return super(ElasticsearchMultilingualSearchBackend, self).search(query_string, **kwargs)

Example 8

Project: django-money
Source File: fields.py
View license
    def __get_current_locale(self):
        # get_language can return None starting on django 1.8
        language = translation.get_language() or settings.LANGUAGE_CODE
        locale = translation.to_locale(language)

        if _FORMATTER.get_formatting_definition(locale):
            return locale

        if _FORMATTER.get_formatting_definition('%s_%s' % (locale, locale)):
            return '%s_%s' % (locale, locale)

        return ''

Example 9

Project: zulip
Source File: i18n.py
View license
def with_language(string, language):
    # type: (text_type, text_type) -> text_type
    old_language = translation.get_language()
    translation.activate(language)
    result = _(string)
    translation.activate(old_language)
    return result

Example 10

Project: django-dockit
Source File: options.py
View license
    def verbose_name_raw(self):
        """
        There are a few places where the untranslated verbose name is needed
        (so that we get the same value regardless of currently active
        locale).
        """
        lang = get_language()
        deactivate_all()
        raw = force_unicode(self.verbose_name)
        activate(lang)
        return raw

Example 11

Project: Misago
Source File: views.py
View license
@cache_page(86400, key_prefix='momentjsi18n')
@last_modified(lambda req, **kw: timezone.now())
def momentjs_catalog(request):
    locale_path = momentjs.get_locale_path(get_language())

    if locale_path:
        with open (locale_path, "r") as locale_file:
            locale = locale_file.read()
    else:
        locale = "";
    return HttpResponse(
        locale, content_type='application/javascript; charset=utf-8')

Example 12

Project: django-konfera
Source File: custom_filters.py
View license
def set_default_locale():
    default_language = get_language()
    default_loc = to_locale(default_language)
    system_enc = get_system_encoding()
    try:
        user_locale = locale.setlocale(locale.LC_ALL, (default_loc, system_enc))
    except locale.Error:
        user_locale = locale.setlocale(locale.LC_ALL, ('en_US', 'UTF-8'))
    return user_locale

Example 13

Project: aldryn-newsblog
Source File: views.py
View license
    def get_queryset(self):
        qs = super(PreviewModeMixin, self).get_queryset()
        # check if user can see unpublished items. this will allow to switch
        # to edit mode instead of 404 on article detail page. CMS handles the
        # permissions.
        user = self.request.user
        user_can_edit = user.is_staff or user.is_superuser
        if not (self.edit_mode or user_can_edit):
            qs = qs.published()
        language = translation.get_language()
        qs = qs.active_translations(language).namespace(self.namespace)
        return qs

Example 14

View license
@register.filter(name='currency')
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 15

Project: aldryn-blog
Source File: forms.py
View license
    def get_slug_conflict(self, slug):
        translations_model = self.instance._meta.translations_model

        try:
            language_code = self.instance.language_code
        except translations_model.DoesNotExist:
            language_code = get_language()

        conflicts = translations_model.objects.filter(slug=slug, language_code=language_code)
        if self.is_edit_action():
            conflicts = conflicts.exclude(master=self.instance)

        try:
            return conflicts.get()
        except translations_model.DoesNotExist:
            return None

Example 16

Project: couchdbkit
Source File: schema.py
View license
    def verbose_name_raw(self):
        """
        There are a few places where the untranslated verbose name is needed
        (so that we get the same value regardless of currently active
        locale).
        """
        lang = get_language()
        deactivate_all()
        raw = force_unicode(self.verbose_name)
        activate(lang)
        return raw

Example 17

Project: django-oscar
Source File: currency_filters.py
View license
@register.filter(name='currency')
def currency(value, currency=None):
    """
    Format decimal value as currency
    """
    try:
        value = D(value)
    except (TypeError, InvalidOperation):
        return u""
    # Using Babel's currency formatting
    # http://babel.pocoo.org/en/latest/api/numbers.html#babel.numbers.format_currency
    kwargs = {
        'currency': currency if currency else settings.OSCAR_DEFAULT_CURRENCY,
        'format': getattr(settings, 'OSCAR_CURRENCY_FORMAT', None),
        'locale': to_locale(get_language() or settings.LANGUAGE_CODE),
    }
    return format_currency(value, **kwargs)

Example 18

Project: SchoolIdolAPI
Source File: serializers.py
View license
    def get_japanese_center_skill(self, obj):
        if not obj.center_skill:
            return None
        old_lang = translation.get_language()
        translation.activate("ja")
        sentence = string_concat(_(obj.center_skill.split(' ')[0]), ' ', _(obj.center_skill.split(' ')[1]))
        sentence = unicode(sentence)
        translation.activate(old_lang)
        return sentence

Example 19

Project: django-recurrence
Source File: forms.py
View license
    def render(self, name, value, attrs=None):
        if value is None:
            value = ''
        elif isinstance(value, recurrence.Recurrence):
            value = recurrence.serialize(value)

        widget_init_js = (
            '<script type="text/javascript">'
            'recurrence.language_code =\'%s\';'
            'new recurrence.widget.Widget(\'%s\', %s);'
            '</script>'
        ) % (get_language(), attrs['id'], json.dumps(self.js_widget_options))

        return safestring.mark_safe(u'%s\n%s' % (
            super(RecurrenceWidget, self).render(name, value, attrs),
            widget_init_js))

Example 20

Project: django-slim
Source File: translations.py
View license
def is_primary_language(language=None):
    """
    Returns true if current or passed language is the primary language for this site.
    (The primary language is defined as the first language in settings.LANGUAGES.)

    :param str language:
    :return bool:
    """
    if not language:
        language = translation.get_language()

    return language == default_language

Example 21

Project: cadasta-platform
Source File: widgets.py
View license
    def render(self, name, value, attrs=None):
        date_format = formats.get_format("DATETIME_FORMAT",
                                         lang=get_language())
        checkbox = super().render(name, value, attrs=attrs)
        num_entities = self.resource.num_entities
        return self.html.format(
            name=name,
            resource=self.resource,
            checkbox=checkbox,
            date_updated=date(self.resource.last_updated, date_format),
            attachment_text=self.get_attachment_text(num_entities),
        )

Example 22

Project: SmartElect
Source File: models.py
View license
    @staticmethod
    def get_name_field_name():
        """
        Returns the name of the name field that has the name for the
        current language.
        """
        return 'name_arabic' if get_language() == 'ar' else 'name_english'

Example 23

Project: plan
Source File: title.py
View license
@register.inclusion_tag('title.html')
def title(semester, slug, week=None):
    # TODO(adamcik): feels wrong hardcoding this here.
    if translation.get_language() in ['no', 'nb', 'nn']:
        ending = norwegian(slug)
    else:
        ending = english(slug)

    return {
        'slug': slug,
        'ending': ending,
        'type': semester.get_type_display(),
        'year': semester.year,
        'week': week,
    }

Example 24

Project: django-transadmin
Source File: helpers.py
View license
@register.function
def _(text, context=None):
    try:
        trans = Translation.objects.translate(text, get_language(), context)
        return trans.text if trans else text
    except (Translation.DoesNotExist, TypeError, DatabaseError,
            AppRegistryNotReady):
        return text

Example 25

Project: timebank
Source File: utils.py
View license
    def to_unicode(self, language_code=None):
        from django.utils import translation
        cur_language = translation.get_language()
        renderized_string = None
        try:
            if language_code:
                translation.activate(language_code)
            if self.render:
                renderized_string = render_to_string(self.message, self.args)
            else:
                renderized_string = self.message % self.args
        finally:
            if language_code:
                translation.activate(settings.LANGUAGE_CODE)
        return renderized_string

Example 26

Project: django-phonenumber-field
Source File: widgets.py
View license
    def __init__(self, initial=None):
        choices = [('', '---------')]
        language = translation.get_language() or settings.LANGUAGE_CODE
        if language:
            locale = Locale(translation.to_locale(language))
            for prefix, values in _COUNTRY_CODE_TO_REGION_CODE.items():
                prefix = '+%d' % prefix
                if initial and initial in values:
                    self.initial = prefix
                for country_code in values:
                    country_name = locale.territories.get(country_code)
                    if country_name:
                        choices.append((prefix, u'%s %s' % (country_name, prefix)))
        super(PhonePrefixSelect, self).__init__(
            choices=sorted(choices, key=lambda item: item[1]))

Example 27

View license
def i18n():
    from django.utils import translation

    return {
        'LANGUAGES': settings.LANGUAGES,
        'LANGUAGE_CODE': translation.get_language(),
        'LANGUAGE_BIDI': translation.get_language_bidi(),
    }

Example 28

Project: aldryn-search
Source File: router.py
View license
    def for_write(self, **hints):
        language = get_language()
        alias = alias_from_language(language)

        if alias not in settings.HAYSTACK_CONNECTIONS:
            return DEFAULT_ALIAS
        return alias

Example 29

Project: reviewboard
Source File: chunk_generator.py
View license
    def make_cache_key(self):
        """Create a cache key for any generated chunks."""
        key = 'diff-sidebyside-'

        if self.enable_syntax_highlighting:
            key += 'hl-'

        if not self.force_interdiff:
            key += six.text_type(self.filediff.pk)
        elif self.interfilediff:
            key += 'interdiff-%s-%s' % (self.filediff.pk,
                                        self.interfilediff.pk)
        else:
            key += 'interdiff-%s-none' % self.filediff.pk

        key += '-%s' % get_language()

        return key

Example 30

Project: djangodoo
Source File: fields.py
View license
def field_translate(field, key):
    lang = translation.get_language() or "en-us"
    details = _get_details_in_lang(field, lang)
    res = details.get(key, "")
    if isinstance(res, six.binary_type):
        res = six.text_type(res)
    return res

Example 31

Project: ecommerce
Source File: utils.py
View license
def add_currency(amount):
    """ Adds currency to the price amount.

    Args:
        amount (Decimal): Price amount

    Returns:
        str: Formatted price with currency.
    """
    return format_currency(
        amount,
        settings.OSCAR_DEFAULT_CURRENCY,
        format=u'#,##0.00',
        locale=to_locale(get_language())
    )

Example 32

View license
def load_template_source(template_name, template_dirs=None):
    """Assuming the current language is German.
       If template_name is index.$LANG.html, try index.de.html then index.html
       Also replaces .. with . when attempting fallback.
    """
    if "$LANG" in template_name:
        lang = translation.get_language()
        try:
            t = template_name.replace("$LANG", lang)
            res = _load_template_source(t, template_dirs)
            return res
        except TemplateDoesNotExist: 
            t = template_name.replace("$LANG", "").replace("..",".")
            return _load_template_source(t, template_dirs)
    return _load_template_source(template_name, template_dirs)

Example 33

Project: pretix
Source File: i18n.py
View license
def get_moment_locale(locale=None):
    cur_lang = locale or translation.get_language()
    if cur_lang in moment_locales:
        return cur_lang
    if '-' in cur_lang or '_' in cur_lang:
        main = cur_lang.replace("_", "-").split("-")[0]
        if main in moment_locales:
            return main
    return settings.LANGUAGE_CODE

Example 34

Project: feincms-elephantblog
Source File: feeds.py
View license
    def items(self):
        if hasattr(Entry, 'translation_of'):
            return Entry.objects.active().filter(
                language=get_language()).order_by('-published_on')[:20]
        else:
            return Entry.objects.active().order_by('-published_on')[:20]

Example 35

Project: transurlvania
Source File: urlresolvers.py
View license
    def get_reverse_dict(self, lang=None):
        if lang is None:
            lang = get_language()
        if lang not in self._lang_reverse_dicts:
            self._lang_reverse_dicts[lang] = self._build_reverse_dict_for_lang(lang)
        return self._lang_reverse_dicts[lang]

Example 36

Project: django-arctic
Source File: generics.py
View license
    def get_datetime_formats(self):
        dtformats = {}

        dtformats['SHORT_DATE'] = get_format('DATE_INPUT_FORMATS',
                                             get_language())[0]
        dtformats['TIME'] = get_format('TIME_INPUT_FORMATS',
                                       get_language())[0]
        dtformats['SHORT_DATETIME'] = get_format('DATETIME_INPUT_FORMATS',
                                                 get_language())[0]

        return dtformats

Example 37

Project: dj-webmachine
Source File: resource.py
View license
    def verbose_name_raw(self):
        """
        There are a few places where the untranslated verbose name is needed
        (so that we get the same value regardless of currently active
        locale).
        """
        lang = get_language()
        deactivate_all()
        raw = force_unicode(self.verbose_name)
        activate(lang)
        return raw

Example 38

Project: django-parler
Source File: admin.py
View license
    def get_queryset_language(self, request):
        """
        Return the language to use in the queryset.
        """
        if not is_multilingual_project():
            # Make sure the current translations remain visible, not the dynamically set get_language() value.
            return appsettings.PARLER_LANGUAGES.get_default_language()
        else:
            # Allow to adjust to current language
            # This is overwritten for the inlines, which follow the primary object.
            return get_language()

Example 39

Project: datal
Source File: local_tags.py
View license
@register.simple_tag
def microsite_footer(preferences, context_path=None):
    footer_uri = preferences['account_footer_uri']
    footer_height = preferences['account_footer_height']
    if footer_uri and footer_height:
        footer_uri += "?locale=%s" % get_language()
        if context_path:
            footer_uri += "&page_type=%s" % context_path
        return '<iframe src="'+footer_uri+'" style="width:100%;height:'+footer_height+'px;border:0;overflow:hidden;" frameborder="0" scrolling="no"></iframe>'
    else:
        return preferences['branding_footer']

Example 40

View license
def make_key(k, with_locale=True):
    """Generate the full key for ``k``, with a prefix."""
    key = encoding.smart_bytes('%s:%s' % (config.CACHE_PREFIX, k))
    if with_locale:
        key += encoding.smart_bytes(translation.get_language())
    # memcached keys must be < 250 bytes and w/o whitespace, but it's nice
    # to see the keys when using locmem.
    return hashlib.md5(key).hexdigest()

Example 41

Project: python-useful
Source File: i18n.py
View license
def get_safe_langcode():
    """
    Returns two-letter code of the active language.
    Is always one of the supported languages. 'en' is expected to exist!
    """
    lang = get_language()[:2].lower()
    return lang if lang in dict(settings.LANGUAGES) else 'en'

Example 42

Project: wolnelektury
Source File: emitters.py
View license
    def get_ssis(self, emitter_format):
        """Yields SSI include statements for the queryset."""
        url_pattern = reverse(
            'api_include',
            kwargs={
                'model': self.queryset.model.__name__.lower(),
                'pk': '0000',
                'emitter_format': emitter_format,
                'lang': get_language(),
            })
        for instance in self.queryset:
            yield "<!--#include file='%s'-->" % url_pattern.replace('0000', str(instance.pk))

Example 43

Project: django-linguist
Source File: utils.py
View license
def build_localized_field_name(field_name, language=None):
    """
    Build localized field name from ``field_name`` and ``language``.
    """
    if language is None:
        language = get_language()

    return '%s_%s' % (field_name, language.replace('-', '_'))

Example 44

Project: django-libs
Source File: format_utils.py
View license
def get_format_modules(lang=None, reverse=False):
    """
    Returns a list of the format modules found

    """
    if lang is None:
        lang = get_language()
    modules = _format_modules_cache.setdefault(lang, list(
        iter_format_modules(lang)))
    if reverse:
        return list(reversed(modules))
    return modules

Example 45

Project: django-jet
Source File: utils.py
View license
def get_possible_language_codes():
    language_code = translation.get_language()

    language_code = language_code.replace('_', '-').lower()
    language_codes = []

    # making dialect part uppercase
    split = language_code.split('-', 2)
    if len(split) == 2:
        language_code = '%s-%s' % (split[0].lower(), split[1].upper()) if split[0] != split[1] else split[0]

    language_codes.append(language_code)

    # adding language code without dialect part
    if len(split) == 2:
        language_codes.append(split[0].lower())

    return language_codes

Example 46

Project: django-widgy
Source File: models.py
View license
    def get_map_options(self):
        from django.utils.translation import get_language
        return {
            'q': self.address,
            'hl': get_language(),
            'ie': 'UTF8',
            'iwloc': 'addr',
            't': self.get_maptype_short(),
            'vector': 1,
            'z': self.zoom,
        }

Example 47

Project: django-localeurl
Source File: models.py
View license
def resolve(*args, **kwargs):
    locale = utils.supported_language(translation.get_language())
    path = args[0]
    if path.startswith("/%s/" % locale):
        path = path[len("/%s" % locale):]
    return django_resolve(path, *args[1:], **kwargs)

Example 48

Project: yawd-translations
Source File: models.py
View license
    def get_name(self, language_id=None):
        """
        Get the related :class:`translations.models.Translation`
        object's display name for a given ``language``.
        """
        #use the current language if not explicitly set
        translation = self.translation(language_id)
        if translation:
            return unicode(translation)

        #attempt to show default translation
        translation = self.translation(utils.get_default_language())  
        if translation:
            return u'%s (%s %s)' % (translation, _('not translated in'), language_id if language_id else get_language())
        else:
            return u'%s #%s (%s %s)' % (self._meta.verbose_name, self.pk, _('not translated in'), language_id if language_id else get_language())

Example 49

Project: django-cooki18n
Source File: middleware.py
View license
    def process_response(self, request, response):
        if settings.LANGUAGE_COOKIE_NAME not in response.cookies:
            response.set_cookie(settings.LANGUAGE_COOKIE_NAME,
                translation.get_language())
        patch_vary_headers(response, ('Accept-Language',))
        if 'Content-Language' not in response:
            response['Content-Language'] = translation.get_language()
        translation.deactivate()
        return response

Example 50

Project: pythondigest
Source File: common.py
View license
@register.simple_tag()
def locale():
    if settings.LANGUAGE_CODE == 'ru-ru':
        return 'ru'
    else:
        return to_locale(get_language())