我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.conf.settings.LANGUAGE_CODE。
def __init__(self, language): """Create a GNUTranslations() using many locale directories""" gettext_module.GNUTranslations.__init__(self) self.set_output_charset('utf-8') # For Python 2 gettext() (#25720) self.__language = language self.__to_language = to_language(language) self.__locale = to_locale(language) self._catalog = None self._init_translation_catalog() self._add_installed_apps_translations() self._add_local_translations() if self.__language == settings.LANGUAGE_CODE and self._catalog is None: # default lang should have at least one translation file available. raise IOError("No translation files found for default language %s." % settings.LANGUAGE_CODE) self._add_fallback() if self._catalog is None: # No catalogs found for this language, set an empty catalog. self._catalog = {}
def get_available_languages_setting(): ''' list of available languages for modeltrans translations. defaults to the list of language codes extracted from django setting LANGUAGES ''' languages = tuple(set(getattr( settings, 'MODELTRANS_AVAILABLE_LANGUAGES', (code for code, _ in getattr(settings, 'LANGUAGES')) ))) if not all(isinstance(x, six.string_types) for x in languages): raise ImproperlyConfigured('MODELTRANS_AVAILABLE_LANGUAGES should be an iterable of strings') # make sure LANGUAGE_CODE is not in available languages return (lang for lang in languages if lang != get_default_language())
def get_fallback_chain(lang): ''' Returns the list of fallback languages for language `lang`. For example, this function will return `('nl', 'en')` when called with `lang='fy'` and configured like this:: LANGUAGE_CODE = 'en' MODELTRANS_FALLBACK = { 'default': (LANGUAGE_CODE, ), 'fy': ('nl', 'en') } ''' MODELTRANS_FALLBACK = get_fallback_setting() if lang not in MODELTRANS_FALLBACK.keys(): lang = 'default' return MODELTRANS_FALLBACK[lang]
def set_pootle_locale_from_settings(): """Try to set Pootle locale based on the language specified in settings.""" # See above for the reasoning why we need to skip setting locale under # Windows if os.name == 'nt': return lang = translation.to_locale(settings.LANGUAGE_CODE) try: if lang == 'tr' or lang.startswith('tr_'): raise ValueError("Turkish locale broken due to changed meaning of " "lower()") locale.setlocale(locale.LC_ALL, (lang, 'UTF-8')) except: logging.debug('Failed to set locale to Pootle default (%s); loading ' 'system default', lang) locale.setlocale(locale.LC_ALL, '')
def get_request_language_preference(request): """ Collect language preferences from request.LANGUAGE_CODE, the HTTP Accept-Language header, and settings.LANGUAGE_CODE, and return a list of languages in preference order. """ all_langs = [] if hasattr(request, 'LANGUAGE_CODE'): all_langs.append(request.LANGUAGE_CODE) all_langs.extend(parse_accept_header(request.META.get('HTTP_ACCEPT_LANGUAGE', ''))) all_langs.append(settings.LANGUAGE_CODE) # Remove duplicates while preserving order. The list of languages should be # quite short, so the inefficiency of this method should not matter. # Famous last words. langs = [] for lang in all_langs: if lang not in langs: langs.append(lang) return langs
def lang_data(LANGUAGE_CODE, **kwargs): # These are needed for i18n from django.http import HttpRequest from django.views.i18n import javascript_catalog LANGUAGE_BIDI = LANGUAGE_CODE.split('-')[0] in \ settings.LANGUAGES_BIDI request = HttpRequest() request.GET['language'] = LANGUAGE_CODE # Add some JavaScript data content = 'var LANGUAGE_CODE = "%s";\n' % LANGUAGE_CODE content += 'var LANGUAGE_BIDI = ' + \ (LANGUAGE_BIDI and 'true' or 'false') + ';\n' content += javascript_catalog(request, packages=settings.INSTALLED_APPS).content # The hgettext() function just calls gettext() internally, but # it won't get indexed by makemessages. content += '\nwindow.hgettext = function(text) { return gettext(text); };\n' # Add a similar hngettext() function content += 'window.hngettext = function(singular, plural, count) { return ngettext(singular, plural, count); };\n' return content
def get_context_data(self, **kwargs): context = super(SubmissionRedirectView,self).get_context_data(**kwargs) try: redirect_url = unquote(self.request.GET.get('redirect_url','')) if not redirect_url: redirect_url = Page.objects.get(pk=getConstant('general__defaultAdminSuccessPage')).get_absolute_url(settings.LANGUAGE_CODE) except ObjectDoesNotExist: redirect_url = '/' context.update({ 'redirect_url': redirect_url, 'seconds': self.request.GET.get('seconds',5), }) return context ################################################ # For Viewing Invoices and sending notifications
def test_fileplugin_icon_uppercase(self): page = api.create_page('testpage', 'nav_playground.html', 'en') body = page.placeholders.get(slot="body") plugin = File( plugin_type='FilePlugin', placeholder=body, position=1, language=settings.LANGUAGE_CODE, ) # This try/except block allows older and newer versions of the # djangocms-file plugin to work here. try: plugin.file.save("UPPERCASE.JPG", SimpleUploadedFile( "UPPERCASE.jpg", b"content"), False) except ObjectDoesNotExist: # catches 'RelatedObjectDoesNotExist' plugin.source.save("UPPERCASE.JPG", SimpleUploadedFile( "UPPERCASE.jpg", b"content"), False) plugin.add_root(instance=plugin) self.assertNotEquals(plugin.get_icon_url().find('jpg'), -1)
def get_default_language(language_code=None, site_id=None): """ Returns default language depending on settings.LANGUAGE_CODE merged with best match from get_cms_setting('LANGUAGES') Returns: language_code """ if not language_code: language_code = get_language_code(settings.LANGUAGE_CODE) languages = get_language_list(site_id) # first try if there is an exact language if language_code in languages: return language_code # otherwise split the language code if possible, so iso3 language_code = language_code.split("-")[0] if not language_code in languages: return settings.LANGUAGE_CODE return language_code
def get_languages(): if settings.SITE_ID != hash(settings.SITE_ID): raise ImproperlyConfigured( "SITE_ID must be an integer" ) if not settings.USE_I18N: return _ensure_languages_settings( {settings.SITE_ID: [{'code': settings.LANGUAGE_CODE, 'name': settings.LANGUAGE_CODE}]}) if settings.LANGUAGE_CODE not in dict(settings.LANGUAGES): raise ImproperlyConfigured( 'LANGUAGE_CODE "%s" must have a matching entry in LANGUAGES' % settings.LANGUAGE_CODE ) languages = getattr(settings, 'CMS_LANGUAGES', { settings.SITE_ID: [{'code': code, 'name': _(name)} for code, name in settings.LANGUAGES] }) if VERIFIED in languages: return languages return _ensure_languages_settings(languages)
def update_from_georeport_v2_url( url, params=None, id_namespace='', ): # pragma: no cover if not translation.get_language(): # For interactive (shell) use: ensure a language is set translation.activate(settings.LANGUAGE_CODE) resp = requests.get(url, params) if 'xml' in resp.headers['Content-Type']: json_data = transform_xml_to_json(resp.content) else: json_data = resp.text issue_datas = json.loads(json_data) return [ update_local_issue(issue_data, id_namespace=id_namespace) for issue_data in issue_datas ]
def validate(self, value: LocalizedValue, *_): """Validates that the values has been filled in for all required languages Exceptions are raises in order to notify the user of invalid values. Arguments: value: The value to validate. """ if self.null: return for lang in self.required: lang_val = getattr(value, settings.LANGUAGE_CODE) if lang_val is None: raise IntegrityError('null value in column "%s.%s" violates ' 'not-null constraint' % (self.name, lang))
def get(self, language: str=None, default: str=None) -> str: """Gets the underlying value in the specified or primary language. Arguments: language: The language to get the value in. Returns: The value in the current language, or the primary language in case no language was specified. """ language = language or settings.LANGUAGE_CODE return super().get(language, default)
def __str__(self) -> str: """Gets the value in the current language, or falls back to the primary language if there's no value in the current language.""" fallbacks = getattr(settings, 'LOCALIZED_FIELDS_FALLBACKS', {}) language = translation.get_language() or settings.LANGUAGE_CODE languages = fallbacks.get(language, [settings.LANGUAGE_CODE])[:] languages.insert(0, language) for lang_code in languages: value = self.get(lang_code) if value: return value or '' return ''
def test_str_fallback_custom_fallback(): """Tests whether the :see:LocalizedValue class's __str__'s fallback functionality properly respects the LOCALIZED_FIELDS_FALLBACKS setting.""" settings.LOCALIZED_FIELDS_FALLBACKS = { 'nl': ['ro'] } localized_value = LocalizedValue({ settings.LANGUAGE_CODE: settings.LANGUAGE_CODE, 'ro': 'ro' }) with translation.override('nl'): assert str(localized_value) == 'ro'
def test_init(): """Tests whether the :see:__init__ function correctly handles parameters""" field = LocalizedField(blank=True) assert field.required == [] field = LocalizedField(blank=False) assert field.required == [settings.LANGUAGE_CODE] field = LocalizedField(required=True) assert field.required == [lang_code for lang_code, _ in settings.LANGUAGES] field = LocalizedField(required=False) assert field.required == []
def reset_cache(**kwargs): """ Reset global state when LANGUAGES setting has been changed, as some languages should no longer be accepted. """ if kwargs['setting'] in ('LANGUAGES', 'LANGUAGE_CODE'): check_for_language.cache_clear() get_languages.cache_clear() get_supported_language_variant.cache_clear()
def _add_fallback(self): """Sets the GNUTranslations() fallback with the default language.""" # Don't set a fallback for the default language or any English variant # (as it's empty, so it'll ALWAYS fall back to the default language) if self.__language == settings.LANGUAGE_CODE or self.__language.startswith('en'): return default_translation = translation(settings.LANGUAGE_CODE) self.add_fallback(default_translation)
def catalog(): """ Returns the current active catalog for further processing. This can be used if you need to modify the catalog or want to access the whole message catalog instead of just translating one string. """ global _default t = getattr(_active, "value", None) if t is not None: return t if _default is None: _default = translation(settings.LANGUAGE_CODE) return _default
def do_translate(message, translation_function): """ Translates 'message' using the given 'translation_function' name -- which will be either gettext or ugettext. It uses the current thread to find the translation object to use. If no current translation is activated, the message will be run through the default translation object. """ global _default # str() is allowing a bytestring message to remain bytestring on Python 2 eol_message = message.replace(str('\r\n'), str('\n')).replace(str('\r'), str('\n')) if len(eol_message) == 0: # Returns an empty value of the corresponding type if an empty message # is given, instead of metadata, which is the default gettext behavior. result = type(message)("") else: _default = _default or translation(settings.LANGUAGE_CODE) translation_object = getattr(_active, "value", _default) result = getattr(translation_object, translation_function)(eol_message) if isinstance(message, SafeData): return mark_safe(result) return result
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 is_default_locale(locale): """ Returns whether the locale is the default locale. """ return locale == supported_language(settings.LANGUAGE_CODE)
def locale_path(path, locale=''): """ Generate the localeurl-enabled path from a path without locale prefix. If the locale is empty settings.LANGUAGE_CODE is used. """ locale = supported_language(locale) if not locale: locale = supported_language(settings.LANGUAGE_CODE) if is_locale_independent(path): return path elif is_default_locale(locale) and not localeurl_settings.PREFIX_DEFAULT_LOCALE: return path else: tmp = path.split("/") if len(tmp) < 3: if tmp[1] == URL_PREFIX: tmp.append("") else: raise Http404() elif len(tmp) < 2: tmp.insert(1, URL_PREFIX) elif tmp[1] == locale: tmp[1] = URL_PREFIX tmp_locale = tmp[2] if tmp_locale == locale: return path if tmp_locale in localeurl_settings.SUPPORTED_LOCALES: tmp[2] = locale else: tmp.insert(2, locale) return "/".join(tmp)
def locale_url(path, locale=''): """ Generate the localeurl-enabled URL from a path without locale prefix. If the locale is empty settings.LANGUAGE_CODE is used. """ path = locale_path(path, locale) return add_script_prefix(path)
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)
def test_default_language(self): root = Page.get_first_root_node() translation.activate(settings.LANGUAGE_CODE) title_en = "The English Title" _created = models.Test( title=title_en, slug="test", url_path='/kiks/', ) _created = root.add_child(instance=_created) test_object = models.Test.objects.get(id=_created.id) self.assertEqual(test_object.title, title_en) root_get = self.client.get("/") self.assertTrue(isinstance(root_get, HttpResponseRedirect))
def _message_to_dict(request, message): created_at = arrow.get(message.created_at) css_class = 'me' if request.user == message.user else '' return {'content': message.content, 'ago': created_at.humanize(locale=settings.LANGUAGE_CODE[:2]), 'author': message.user.profile.nickname, 'key': message.hash_id, 'className': css_class}
def create_nickname(): faker = Factory.create(settings.LANGUAGE_CODE) return faker.first_name_female()
def __call__(self, request): if request.path.startswith('/admin'): request.LANG = getattr(settings, 'ADMIN_LANGUAGE_CODE', settings.LANGUAGE_CODE) translation.activate(request.LANG) request.LANGUAGE_CODE = request.LANG else: request.LANG = settings.LANGUAGE_CODE translation.activate(request.LANG) request.LANGUAGE_CODE = request.LANG return self.get_response(request)
def serve(self, request, *args, **kwargs): activate(self.language.code) request.LANGUAGE_CODE = self.language.code return super(TranslatedPage, self).serve(request, *args, **kwargs)
def make_wsgi_application(): # validate models s = StringIO() if get_validation_errors(s): s.seek(0) error = s.read() msg = "One or more models did not validate:\n%s" % error print(msg, file=sys.stderr) sys.stderr.flush() sys.exit(1) translation.activate(settings.LANGUAGE_CODE) if django14: return get_internal_wsgi_application() return WSGIHandler()
def get_translated_attribute(instance, attr): """ Wraps Django Model __getattribute__ method making translation in templates less painful """ # If its class has no translatable fields, returns attribute try: if not hasattr(instance._meta, "translatable_fields") or len(getattr(instance._meta,"translatable_fields"))==0: return getattr(instance, attr) except AttributeError: return instance # Translatable fields of this instance translatable_fields = instance._meta.translatable_fields # Current language cur_language = get_language() lang = cur_language.title().lower() # If current language is default language, returns attribute if lang == settings.LANGUAGE_CODE: return getattr(instance, attr) # Otherwise, if a translation is NOT needed for attr atribute, get attribute if not attr in translatable_fields: return getattr(instance, attr) # Gets field translations of this instance and return the translated attribute field_translation = _get_fieldtranslations(instance, field=attr, lang=lang) if field_translation: if not field_translation.is_fuzzy: return field_translation.translation return getattr(instance, attr) # Register this template filter
def _save_translations(sender, instance, *args, **kwargs): """ This signal saves model translations. """ # If we are in a site with one language there is no need of saving translations if site_is_monolingual(): return False cls = sender # If its class has no "translatable_fields" then there are no translations if not hasattr(cls._meta, "translatable_fields"): return False # For each translatable field, get its value, computes its md5 and for each language creates its # empty translation. for field in cls._meta.translatable_fields: value = getattr(instance,field) if not value is None: md5_value = checksum(value) setattr( instance, u"md5"+field, md5_value ) for lang in settings.LANGUAGES: lang = lang[0] # print "({0}!={1}) = {2}".format(lang, settings.LANGUAGE_CODE,lang!=settings.LANGUAGE_CODE) if lang != settings.LANGUAGE_CODE: context = u"Updating from object" if hasattr(instance, "trans_context"): context = getattr(instance, "trans_context") trans = FieldTranslation.update(instance, field, lang, context) ######################################################################## ######################################################################## ######################################################################## ## GET TRANSLATIONS ## ######################################################################################################################## ## Get translated fields
def akismet_comment_check(request, comment): """Akismet comment check""" if settings.ENABLE_AKISMET: url_verify_key = 'https://rest.akismet.com/1.1/verify-key' key = settings.AKISMET_API_KEY blog = settings.BLOG_URL data = {'key': key, 'blog': blog} response = requests.post(url_verify_key, data=data) if response.text == 'valid': url = 'https://%s.rest.akismet.com/1.1/comment-check' % key data = { 'blog': blog, 'user_ip': comment.ip, 'user_agent': get_useragent(request), 'referrer': get_referrer(request), 'comment_type': 'comment', 'comment_author': comment.username, 'comment_content': comment.content, 'comment_date_gmt': timezone.now(), 'blog_lang': settings.LANGUAGE_CODE, 'blog_charset': 'UTF-8', } result = requests.post(url, data=data) if result.text == 'true': return True return False
def get_translation(self, language=settings.LANGUAGE_CODE): return self.__class__.objects.get(translation=self, language=language)
def select_language(context, current_code=None): request = context.get('request') if not request: return '' current_code = current_code or get_language() if not current_code or current_code not in options.MULTILANGUAGE_SITES: current_code = settings.LANGUAGE_CODE return loader.render_to_string('multilanguage/allowed_languages.html', { 'current_code': current_code, 'langs': options.MULTILANGUAGE_SITES, }, request=request)
def get_formatter(language=None): if conf.VALUTE_FORMAT: valute_format = conf.VALUTE_FORMAT else: language = language or get_language() or settings.LANGUAGE_CODE for langs, valute_format in conf.VALUTE_FORMAT_BY_LANG.items(): if language in langs: break else: raise ImproperlyConfigured("Valute format not found for language '%s'" % language) return conf.VALUTE_FORMATS[valute_format.upper()]
def __init__(self, language=None, attrs=None): self.language = language or settings.LANGUAGE_CODE[:2] super(ColorPickerWidget, self).__init__(attrs=attrs)
def update(self, index, iterable, commit=True, language_specific=False): if not language_specific and self.connection_alias == "default": current_language = (translation.get_language() or settings.LANGUAGE_CODE)[:2] for lang_code, lang_name in settings.LANGUAGES: using = "default_%s" % lang_code translation.activate(lang_code) backend = connections[using].get_backend() backend.update(index, iterable, commit, language_specific=True) translation.activate(current_language) elif language_specific: super(MultilingualWhooshSearchBackend, self).update(index, iterable, commit)
def index_queryset(self, using=None): """Used when the entire index for model is updated.""" if using and using != "default": lang_code = using.replace("default_", "") else: lang_code = settings.LANGUAGE_CODE[:2] return self.get_model().objects.filter(language=lang_code)
def handle(self, *args, **options): warnings.warn( "FastCGI support has been deprecated and will be removed in Django 1.9.", RemovedInDjango19Warning) from django.conf import settings from django.utils import translation # Activate the current language, because it won't get activated later. try: translation.activate(settings.LANGUAGE_CODE) except AttributeError: pass from django.core.servers.fastcgi import runfastcgi runfastcgi(args)
def process_request(request): if request.path.startswith('/admin'): request.LANG = getattr(settings, 'ADMIN_LANGUAGE_CODE', settings.LANGUAGE_CODE) translation.activate(request.LANG) request.LANGUAGE_CODE = request.LANG else: request.LANG = settings.LANGUAGE_CODE translation.activate(request.LANG) request.LANGUAGE_CODE = request.LANG
def get_targets(combine_media=settings.COMBINE_MEDIA, **kwargs): """Returns all files that must be combined.""" targets = [] for target in sorted(combine_media.keys()): group = combine_media[target] if '.site_data.js' in group: # site_data must always come first because other modules might # depend on it group.remove('.site_data.js') group.insert(0, site_data) if '%(LANGUAGE_CODE)s' in target: # This file uses i18n, so generate a separate file per language. # The language data is always added before all other files. for LANGUAGE_CODE in LANGUAGES: data = kwargs.copy() data['LANGUAGE_CODE'] = LANGUAGE_CODE filename = target % data data['target'] = filename group.insert(0, lang_data) targets.append((filename, data, group)) elif '%(LANGUAGE_DIR)s' in target: # Generate CSS files for both text directions for LANGUAGE_DIR in ('ltr', 'rtl'): data = kwargs.copy() data['LANGUAGE_DIR'] = LANGUAGE_DIR filename = target % data data['target'] = filename targets.append((filename, data, group)) else: data = kwargs.copy() filename = target % data data['target'] = filename targets.append((filename, data, group)) return targets
def translate(func): @wraps(func) def _inner(*args, **kwargs): lang = kwargs.pop('language', settings.LANGUAGE_CODE) prev_lang = translation.get_language() translation.activate(lang) try: ret = func(*args, **kwargs) finally: translation.activate(prev_lang) return ret return _inner