我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.conf.settings.USE_I18N。
def i18n_javascript(self, request): """ Displays the i18n JavaScript that the Django admin requires. This takes into account the USE_I18N setting. If it's set to False, the generated JavaScript will be leaner and faster. """ if settings.USE_I18N: from django.views.i18n import javascript_catalog else: from django.views.i18n import null_javascript_catalog as javascript_catalog return javascript_catalog(request, packages=['django.conf', 'xadmin']) # This global object represents the default admin site, for the common case. # You can instantiate AdminSite in your own code to create a custom admin site.
def updatemessages(): from django.conf import settings if not settings.USE_I18N: return from django.core.management.commands.compilemessages import compile_messages if any([needs_update(path) for path in settings.LOCALE_PATHS]): compile_messages() LOCALE_PATHS = settings.LOCALE_PATHS settings.LOCALE_PATHS = () cwd = os.getcwdu() for app in settings.INSTALLED_APPS: path = os.path.dirname(__import__(app, {}, {}, ['']).__file__) locale = os.path.join(path, 'locale') if os.path.isdir(locale): # Copy Python translations into JavaScript translations update_js_translations(locale) if needs_update(locale): os.chdir(path) compile_messages() settings.LOCALE_PATHS = LOCALE_PATHS os.chdir(cwd)
def i18n_javascript(self, request): """ Displays the i18n JavaScript that the Django admin requires. This takes into account the USE_I18N setting. If it's set to False, the generated JavaScript will be leaner and faster. """ if settings.USE_I18N: from django.views.i18n import javascript_catalog else: from django.views.i18n import null_javascript_catalog as javascript_catalog return javascript_catalog(request, packages=['django.conf', 'django.contrib.admin'])
def __getattr__(self, real_name): from django.conf import settings if settings.USE_I18N: from django.utils.translation import trans_real as trans else: from django.utils.translation import trans_null as trans setattr(self, real_name, getattr(trans, real_name)) return getattr(trans, real_name)
def _i18n_cache_key_suffix(request, cache_key): """If necessary, adds 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: # The datetime module doesn't restrict the output of tzname(). # Windows is known to use non-standard, locale-dependent names. # User-defined tzinfo classes may return absolutely anything. # Hence this paranoid conversion to create a valid cache key. tz_name = force_text(get_current_timezone_name(), errors='ignore') cache_key += '.%s' % tz_name.encode('ascii', 'ignore').decode('ascii').replace(' ', '_') return cache_key
def learn_cache_key(request, response, cache_timeout=None, key_prefix=None, cache=None): """ Learns what headers to take into account for some request URL from the response object. It stores those headers in a global URL registry so that later access to that URL will know what headers to take into account without building the response object itself. The headers are named in the Vary header of the response, but we want to prevent response generation. The list of headers to use for cache key generation is stored in the same cache as the pages themselves. If the cache ages some data out of the cache, this just means that we have to build the response once to get at the Vary header and so at the list of headers to use for the cache key. """ if key_prefix is None: key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX if cache_timeout is None: cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS cache_key = _generate_cache_header_key(key_prefix, request) if cache is None: cache = caches[settings.CACHE_MIDDLEWARE_ALIAS] if response.has_header('Vary'): is_accept_language_redundant = settings.USE_I18N or settings.USE_L10N # If i18n or l10n are used, the generated cache key will be suffixed # with the current locale. Adding the raw value of Accept-Language is # redundant in that case and would result in storing the same content # under multiple keys in the cache. See #18191 for details. headerlist = [] for header in cc_delim_re.split(response['Vary']): header = header.upper().replace('-', '_') if header == 'ACCEPT_LANGUAGE' and is_accept_language_redundant: continue headerlist.append('HTTP_' + header) headerlist.sort() cache.set(cache_key, headerlist, cache_timeout) return _generate_cache_key(request, request.method, headerlist, key_prefix) else: # if there is no Vary header, we still need a cache key # for the request.build_absolute_uri() cache.set(cache_key, [], cache_timeout) return _generate_cache_key(request, request.method, [], key_prefix)
def __init__(self): if not settings.USE_I18N: raise django.core.exceptions.MiddlewareNotUsed()
def get_languages(): if django_settings.USE_I18N: return [ x[0] for x in getattr(django_settings, 'LANGUAGES', [[django_settings.LANGUAGE_CODE]]) ] else: return None
def i18n_javascript(self, request): if settings.USE_I18N: from django.views.i18n import javascript_catalog else: from django.views.i18n import null_javascript_catalog as javascript_catalog return javascript_catalog(request, packages=['django.conf', 'xadmin'])
def i18n_patterns(*urls, **kwargs): """ Adds the language code prefix to every URL pattern within this function. This may only be used in the root URLconf, not in an included URLconf. """ if not settings.USE_I18N: return list(urls) prefix_default_language = kwargs.pop('prefix_default_language', True) assert not kwargs, 'Unexpected kwargs for i18n_patterns(): %s' % kwargs return [LocaleRegexURLResolver(list(urls), prefix_default_language=prefix_default_language)]
def i18n_l10n_prefix(self): parts = [] lang = translation.get_language() if lang is None: lang = '' locale = '' else: locale = translation.to_locale(lang) if settings.USE_I18N: parts += [lang] if settings.USE_L10N: parts += [locale] return '.'.join(parts)
def init_toolbar(self, request): self.request = request self.is_staff = self.request.user.is_staff self.edit_mode = self.is_staff and self.request.session.get('cms_edit', False) self.build_mode = self.is_staff and self.request.session.get('cms_build', False) self.use_draft = self.is_staff and self.edit_mode or self.build_mode self.show_toolbar = self.is_staff or self.request.session.get('cms_edit', False) self.login_form = CMSToolbarLoginForm(request=request) if self.request.session.get('cms_toolbar_disabled', False): self.show_toolbar = False if settings.USE_I18N: self.language = get_language_from_request(request) else: self.language = settings.LANGUAGE_CODE # We need to store the current language in case the user's preferred language is different. self.toolbar_language = self.language user_settings = self.get_user_settings() if user_settings: if (settings.USE_I18N and user_settings.language in dict(settings.LANGUAGES)) or ( not settings.USE_I18N and user_settings.language == settings.LANGUAGE_CODE): self.toolbar_language = user_settings.language else: user_settings.language = self.language user_settings.save() self.clipboard = user_settings.clipboard if hasattr(self, 'toolbars'): for key, toolbar in self.toolbars.items(): self.toolbars[key].request = self.request
def add_language_menu(self): if settings.USE_I18N and not self._language_menu: self._language_menu = self.toolbar.get_or_create_menu(LANGUAGE_MENU_IDENTIFIER, _('Language')) language_changer = getattr(self.request, '_language_changer', DefaultLanguageChanger(self.request)) for code, name in get_language_tuple(self.current_site.pk): try: url = language_changer(code) except NoReverseMatch: url = DefaultLanguageChanger(self.request)(code) self._language_menu.add_link_item(name, url=url, active=self.current_lang == code)
def get_request(self, path=None, language=None, post_data=None, enforce_csrf_checks=False, page=None): factory = RequestFactory() if not path: path = self.get_pages_root() if not language: if settings.USE_I18N: language = settings.LANGUAGES[0][0] else: language = settings.LANGUAGE_CODE if post_data: request = factory.post(path, post_data) else: request = factory.get(path) request.session = self.client.session request.user = getattr(self, 'user', AnonymousUser()) request.LANGUAGE_CODE = language request._dont_enforce_csrf_checks = not enforce_csrf_checks if page: request.current_page = page else: request.current_page = None class MockStorage(object): def __len__(self): return 0 def __iter__(self): return iter([]) def add(self, level, message, extra_tags=''): pass def update(self, response): pass request._messages = MockStorage() return request
def get_language_list(site_id=None): """ :return: returns a list of iso2codes for this site """ return ([lang['code'] for lang in get_languages(site_id)] if settings.USE_I18N else [settings.LANGUAGE_CODE])
def preview_link(page, language): if settings.USE_I18N: # Which one of page.get_slug() and page.get_path() is the right # one to use in this block? They both seem to return the same thing. try: # attempt to retrieve the localized path/slug and return return page.get_absolute_url(language, fallback=False) except: # no localized path/slug. therefore nothing to preview. stay on the same page. # perhaps the user should be somehow notified for this. return '' return page.get_absolute_url(language)
def _clean_many(prefix): from django.core.cache import cache keys = [] if settings.USE_I18N: for lang in [language[0] for language in settings.LANGUAGES]: keys.append("%s-%s" %(prefix, lang)) else: keys = ["%s-%s" %(prefix, settings.LANGUAGE_CODE)] cache.delete_many(keys)