def i18n(request):
    from server.utils import translation
    return {
        'LANGUAGES': settings.LANGUAGES,
        'LANGUAGE_CODE': translation.get_language(),
        'LANGUAGE_BIDI': translation.get_language_bidi(),
    }
Exemplo n.º 2
0
    def get_urls(self, page=1, site=None, protocol=None):
        # Determine protocol
        if self.protocol is not None:
            protocol = self.protocol
        if protocol is None:
            protocol = 'http'

        # Determine domain
        if site is None:
            if server_apps.is_installed('server.contrib.sites'):
                Site = server_apps.get_model('sites.Site')
                try:
                    site = Site.objects.get_current()
                except Site.DoesNotExist:
                    pass
            if site is None:
                raise ImproperlyConfigured(
                    "To use sitemaps, either enable the sites framework or pass "
                    "a Site/RequestSite object in your view.")
        domain = site.domain

        if getattr(self, 'i18n', False):
            urls = []
            current_lang_code = translation.get_language()
            for lang_code, lang_name in settings.LANGUAGES:
                translation.activate(lang_code)
                urls += self._urls(page, protocol, domain)
            translation.activate(current_lang_code)
        else:
            urls = self._urls(page, protocol, domain)

        return urls
Exemplo n.º 3
0
 def wrapped(*args, **kwargs):
     from server.utils import translation
     saved_locale = translation.get_language()
     translation.deactivate_all()
     try:
         res = handle_func(*args, **kwargs)
     finally:
         if saved_locale is not None:
             translation.activate(saved_locale)
     return res
Exemplo n.º 4
0
def get_format_modules(lang=None, reverse=False):
    """Return a list of the format modules found."""
    if lang is None:
        lang = get_language()
    if lang not in _format_modules_cache:
        _format_modules_cache[lang] = list(iter_format_modules(lang, settings.FORMAT_MODULE_PATH))
    modules = _format_modules_cache[lang]
    if reverse:
        return list(reversed(modules))
    return modules
Exemplo n.º 5
0
def _i18n_cache_key_suffix(request, cache_key):
    """If necessary, add the current locale or time zone to the cache key."""
    if settings.USE_I18N or settings.USE_L10N:
        # first check if LocaleMiddleware or another middleware added
        # LANGUAGE_CODE to request, then fall back to the active language
        # which in turn can also fall back to settings.LANGUAGE_CODE
        cache_key += '.%s' % getattr(request, 'LANGUAGE_CODE', get_language())
    if settings.USE_TZ:
        cache_key += '.%s' % get_current_timezone_name()
    return cache_key
Exemplo n.º 6
0
 def get(self, request, *args, **kwargs):
     locale = get_language()
     domain = kwargs.get('domain', self.domain)
     # If packages are not provided, default to all installed packages, as
     # ServerTranslation without localedirs harvests them all.
     packages = kwargs.get('packages', '')
     packages = packages.split('+') if packages else self.packages
     paths = self.get_paths(packages) if packages else None
     self.translation = ServerTranslation(locale,
                                          domain=domain,
                                          localedirs=paths)
     context = self.get_context_data(**kwargs)
     return self.render_to_response(context)
Exemplo n.º 7
0
 def __get__(self, instance, cls=None):
     """
     Return a compiled regular expression based on the active language.
     """
     if instance is None:
         return self
     # As a performance optimization, if the given regex string is a regular
     # string (not a lazily-translated string proxy), compile it once and
     # avoid per-language compilation.
     pattern = getattr(instance, self.attr)
     if isinstance(pattern, str):
         instance.__dict__['regex'] = instance._compile(pattern)
         return instance.__dict__['regex']
     language_code = get_language()
     if language_code not in instance._regex_dict:
         instance._regex_dict[language_code] = instance._compile(
             str(pattern))
     return instance._regex_dict[language_code]
Exemplo n.º 8
0
 def media(self):
     extra = '' if settings.DEBUG else '.min'
     i18n_name = SELECT2_TRANSLATIONS.get(get_language())
     i18n_file = ('admin/js/vendor/select2/i18n/%s.js' %
                  i18n_name, ) if i18n_name else ()
     return forms.Media(
         js=(
             'admin/js/vendor/jquery/jquery%s.js' % extra,
             'admin/js/vendor/select2/select2.full%s.js' % extra,
         ) + i18n_file + (
             'admin/js/jquery.init.js',
             'admin/js/autocomplete.js',
         ),
         css={
             'screen': (
                 'admin/css/vendor/select2/select2%s.css' % extra,
                 'admin/css/autocomplete.css',
             ),
         },
     )
Exemplo n.º 9
0
def number_format(value, decimal_pos=None, use_l10n=None, force_grouping=False):
    """
    Format a numeric value using localization settings.

    If use_l10n is provided and is not None, it forces the value to
    be localized (or not), overriding the value of settings.USE_L10N.
    """
    if use_l10n or (use_l10n is None and settings.USE_L10N):
        lang = get_language()
    else:
        lang = None
    return numberformat.format(
        value,
        get_format('DECIMAL_SEPARATOR', lang, use_l10n=use_l10n),
        decimal_pos,
        get_format('NUMBER_GROUPING', lang, use_l10n=use_l10n),
        get_format('THOUSAND_SEPARATOR', lang, use_l10n=use_l10n),
        force_grouping=force_grouping,
        use_l10n=use_l10n,
    )
Exemplo n.º 10
0
def get_format(format_type, lang=None, use_l10n=None):
    """
    For a specific format type, return the format for the current
    language (locale). Default to the format in the settings.
    format_type is the name of the format, e.g. 'DATE_FORMAT'.

    If use_l10n is provided and is not None, it forces the value to
    be localized (or not), overriding the value of settings.USE_L10N.
    """
    use_l10n = use_l10n or (use_l10n is None and settings.USE_L10N)
    if use_l10n and lang is None:
        lang = get_language()
    cache_key = (format_type, lang)
    try:
        return _format_cache[cache_key]
    except KeyError:
        pass

    # The requested format_type has not been cached yet. Try to find it in any
    # of the format_modules for the given lang if l10n is enabled. If it's not
    # there or if l10n is disabled, fall back to the project settings.
    val = None
    if use_l10n:
        for module in get_format_modules(lang):
            val = getattr(module, format_type, None)
            if val is not None:
                break
    if val is None:
        if format_type not in FORMAT_SETTINGS:
            return format_type
        val = getattr(settings, format_type)
    elif format_type in ISO_INPUT_FORMATS:
        # If a list of input formats from one of the format_modules was
        # retrieved, make sure the ISO_INPUT_FORMATS are in this list.
        val = list(val)
        for iso_input in ISO_INPUT_FORMATS.get(format_type, ()):
            if iso_input not in val:
                val.append(iso_input)
    _format_cache[cache_key] = val
    return val
Exemplo n.º 11
0
 def render(self, context):
     context[self.variable] = translation.get_language()
     return ''
Exemplo n.º 12
0
 def app_dict(self):
     language_code = get_language()
     if language_code not in self._app_dict:
         self._populate()
     return self._app_dict[language_code]
Exemplo n.º 13
0
 def namespace_dict(self):
     language_code = get_language()
     if language_code not in self._namespace_dict:
         self._populate()
     return self._namespace_dict[language_code]
Exemplo n.º 14
0
 def reverse_dict(self):
     language_code = get_language()
     if language_code not in self._reverse_dict:
         self._populate()
     return self._reverse_dict[language_code]
Exemplo n.º 15
0
 def _populate(self):
     # Short-circuit if called recursively in this thread to prevent
     # infinite recursion. Concurrent threads may call this at the same
     # time and will need to continue, so set 'populating' on a
     # thread-local variable.
     if getattr(self._local, 'populating', False):
         return
     try:
         self._local.populating = True
         lookups = MultiValueDict()
         namespaces = {}
         apps = {}
         language_code = get_language()
         for url_pattern in reversed(self.url_patterns):
             p_pattern = url_pattern.pattern.regex.pattern
             if p_pattern.startswith('^'):
                 p_pattern = p_pattern[1:]
             if isinstance(url_pattern, URLPattern):
                 self._callback_strs.add(url_pattern.lookup_str)
                 bits = normalize(url_pattern.pattern.regex.pattern)
                 lookups.appendlist(
                     url_pattern.callback,
                     (bits, p_pattern, url_pattern.default_args,
                      url_pattern.pattern.converters))
                 if url_pattern.name is not None:
                     lookups.appendlist(
                         url_pattern.name,
                         (bits, p_pattern, url_pattern.default_args,
                          url_pattern.pattern.converters))
             else:  # url_pattern is a URLResolver.
                 url_pattern._populate()
                 if url_pattern.app_name:
                     apps.setdefault(url_pattern.app_name,
                                     []).append(url_pattern.namespace)
                     namespaces[url_pattern.namespace] = (p_pattern,
                                                          url_pattern)
                 else:
                     for name in url_pattern.reverse_dict:
                         for matches, pat, defaults, converters in url_pattern.reverse_dict.getlist(
                                 name):
                             new_matches = normalize(p_pattern + pat)
                             lookups.appendlist(
                                 name, (new_matches, p_pattern + pat, {
                                     **defaults,
                                     **url_pattern.default_kwargs
                                 }, {
                                     **self.pattern.converters,
                                     **url_pattern.pattern.converters,
                                     **converters
                                 }))
                     for namespace, (
                             prefix, sub_pattern
                     ) in url_pattern.namespace_dict.items():
                         namespaces[namespace] = (p_pattern + prefix,
                                                  sub_pattern)
                     for app_name, namespace_list in url_pattern.app_dict.items(
                     ):
                         apps.setdefault(app_name,
                                         []).extend(namespace_list)
                 self._callback_strs.update(url_pattern._callback_strs)
         self._namespace_dict[language_code] = namespaces
         self._app_dict[language_code] = apps
         self._reverse_dict[language_code] = lookups
         self._populated = True
     finally:
         self._local.populating = False
Exemplo n.º 16
0
 def language_prefix(self):
     language_code = get_language() or settings.LANGUAGE_CODE
     if language_code == settings.LANGUAGE_CODE and not self.prefix_default_language:
         return ''
     else:
         return '%s/' % language_code