我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.utils.translation.get_language()。
def send(self, request): if (not self.last_email) or self.last_email + timedelta(hours=12) < now(): # TODO: TIMEDELTA mit config old_lang = translation.get_language() translation.activate(self.user.language) link = reverse('poll_vote', args=(self.poll.url,)) # TODO: hier direkt das poll oder das Vote? email_content = render_to_string('invitations/mail_invite.txt', { 'receiver': self.user.username, 'creator': self.creator.username, 'link': link }) try: send_mail("Invitation to vote on {}".format(self.poll.title), email_content, None, [self.user.email]) self.last_email = now() self.save() except SMTPRecipientsRefused: translation.activate(old_lang) messages.error( request, _("The mail server had an error sending the notification to {}".format(self.user.username)) ) translation.activate(old_lang) else: messages.error( request, _("You have send an Email for {} in the last 12 Hours".format(self.user.username)) )
def _select_locale(self, request): supported = request.event.locales language = ( self._language_from_user(request, supported) or self._language_from_cookie(request, supported) or self._language_from_browser(request, supported) or request.event.locale ) translation.activate(language) request.LANGUAGE_CODE = translation.get_language() with suppress(pytz.UnknownTimeZoneError): tzname = request.event.timezone timezone.activate(pytz.timezone(tzname)) request.timezone = tzname
def _send_invitation_mail(request, invitation, subject, template_name): if not invitation.invitee.email: return old_lang = translation.get_language() translation.activate(invitation.invitee.language) template = loader.get_template('groups/mail_{0}.txt'.format(template_name)) message = template.render({ 'invitation': invitation, 'site': get_current_site(request) }) translation.activate(old_lang) send_mail(settings.EMAIL_SUBJECT_PREFIX + subject, message, settings.DEFAULT_FROM_EMAIL, [invitation.invitee.email], fail_silently=True)
def configurePayment(self, **kwargs): # URL de pago según el entorno self.url = self.CECA_URL[self.parent.environment] # Formato para Importe: según ceca, ha de tener un formato de entero positivo self.importe = "{0:.2f}".format(float(self.parent.operation.amount)).replace(".", "") # Idioma de la pasarela, por defecto es español, tomamos # el idioma actual y le asignamos éste self.idioma = self.IDIOMAS["es"] lang = translation.get_language() if lang in self.IDIOMAS: self.idioma = self.IDIOMAS[lang] #################################################################### ## Paso 1.2. Preparación del TPV y Generación del número de operación
def configurePayment(self, **kwargs): # URL de pago según el entorno self.url = self.REDSYS_URL[self.parent.environment] # Formato para Importe: según redsys, ha de tener un formato de entero positivo, con las dos últimas posiciones # ocupadas por los decimales self.importe = "{0:.2f}".format(float(self.parent.operation.amount)).replace(".", "") if self.importe == "000": self.importe = "0" # Idioma de la pasarela, por defecto es español, tomamos # el idioma actual y le asignamos éste self.idioma = self.IDIOMAS["es"] lang = translation.get_language() if lang in self.IDIOMAS: self.idioma = self.IDIOMAS[lang] #################################################################### ## Paso 1.2. Preparación del TPV y Generación del número de operación
def regex(self): """ Returns a compiled regular expression, depending upon the activated language-code. """ language_code = get_language() if language_code not in self._regex_dict: if isinstance(self._regex, six.string_types): regex = self._regex else: regex = force_text(self._regex) try: compiled_regex = re.compile(regex, re.UNICODE) except re.error as e: raise ImproperlyConfigured( '"%s" is not a valid regular expression: %s' % (regex, six.text_type(e))) self._regex_dict[language_code] = compiled_regex return self._regex_dict[language_code]
def pootle_context(request): """Exposes settings to templates.""" # FIXME: maybe we should expose relevant settings only? return { 'settings': { 'POOTLE_TITLE': settings.POOTLE_TITLE, 'POOTLE_INSTANCE_ID': settings.POOTLE_INSTANCE_ID, 'POOTLE_CONTACT_ENABLED': (settings.POOTLE_CONTACT_ENABLED and settings.POOTLE_CONTACT_EMAIL), 'POOTLE_SIGNUP_ENABLED': settings.POOTLE_SIGNUP_ENABLED, 'POOTLE_CACHE_TIMEOUT': settings.POOTLE_CACHE_TIMEOUT, 'TZ': settings.TIME_ZONE, 'TZ_OFFSET': TZ_OFFSET, 'DEBUG': settings.DEBUG, }, 'custom': settings.POOTLE_CUSTOM_TEMPLATE_CONTEXT, 'ALL_LANGUAGES': Language.live.cached_dict(translation.get_language(), request.user.is_superuser), 'ALL_PROJECTS': Project.objects.cached_dict(request.user), 'SOCIAL_AUTH_PROVIDERS': _get_social_auth_providers(request), 'display_agreement': _agreement_context(request), }
def try_geolocator_reverse(coords): """ Tries many times to get a geolocator object from coordinates, or None. """ if settings.TESTING: return test_mockers.geolocator_object(coords=coords) attempts = 0 while attempts < settings.GOOSE_META["max_geolocation_attempts"]: try: position = geolocator.reverse( coords, language=get_language().split('-')[0] ) return position except geopy.exc.GeopyError as e: attempts += 1 if attempts == settings.GOOSE_META["max_geolocation_attempts"]: debug_logger.error( "Too much geopy errors ({}). Aborting.".format(str(e)) ) return None
def try_geolocator_geocode(address): """ Tries many times to get a geolocator object from an address, or None. """ if settings.TESTING: return test_mockers.geolocator_object(address=address) attempts = 0 while attempts < settings.GOOSE_META["max_geolocation_attempts"]: try: position = geolocator.geocode( address, language=get_language().split('-')[0] ) return position except geopy.exc.GeopyError as e: attempts += 1 if attempts == settings.GOOSE_META["max_geolocation_attempts"]: debug_logger.error( "Too much geopy errors ({}). Aborting.".format(str(e)) ) return None
def record_history(self, sender, instance, **kwargs): """When a page is published, make a new PublishHistory object""" from .models import EditHistory, PublishHistory # Make sure we have the draft version. if not instance.publisher_is_draft: instance = publisher_draft editings = EditHistory.objects.filter( page_id=instance.id, published_in__isnull=True, ) if editings.count() == 0: # No changes happened, skip! return public = instance.publisher_public user_id = cache.get('cms-user-id') history = PublishHistory.objects.create( page=public, user_id=user_id, language=get_language()) history.editings = editings history.save()
def cached_student(self): if not self._cache_student_last_update or self._cache_student_last_update < timezone.now() - datetime.timedelta( days=self._cache_student_days): self.force_cache_student() return AttrDict({ 'pk': self.student_id, 'id': self.student_id, 'unicode': self._cache_student_name if get_language() != 'ja' else self._cache_student_japanese_name, 'name': self._cache_student_name, 'japanese_name': self._cache_student_japanese_name, 'image': self._cache_student_image, 'image_url': get_image_url_from_path(self._cache_student_image), 'http_image_url': get_http_image_url_from_path(self._cache_student_image), 'item_url': u'/student/{}/{}/'.format(self.student_id, tourldash(self._cache_student_name)), 'ajax_item_url': u'/ajax/student/{}/'.format(self.student_id), }) # Cache totals
def render(self, name, value, attrs=None): self.editor_options.setdefault('language', get_language()) attrs = attrs or {} attrs.setdefault('class', '') attrs['class'] += ' ckeditor-field' output = super(DefaultWidget, self).render(name, value, attrs) output += mark_safe(''' <script type="text/javascript"> window._ckeditor_confs = window._ckeditor_confs || {}; window._ckeditor_confs["%s"] = %s; </script> ''' % (name, json.dumps(self.editor_options))) return output
def get_static_map_url(longitude, latitude, zoom=None, width=None, height=None): """ ?????????? URL ????????? ????? Google """ if not latitude or not longitude: longitude, latitude = conf.DEFAULT_MAP_CENTER point = _format_point(longitude, latitude) return conf.STATIC_MAP_URL + parse.urlencode(dict( center=point, size='%dx%d' % ( width or conf.STATIC_MAP_WIDTH, height or conf.STATIC_MAP_HEIGHT, ), zoom=zoom or conf.STATIC_MAP_ZOOM, maptype='roadmap', language=get_language(), markers='color:red|label:G|%s' % point, ))
def kolibri_language_globals(context): lang_dir = "rtl" if get_language_bidi() else "ltr" js = """ <script> var languageCode = '{lang_code}'; var languageDir = '{lang_dir}'; var languages = JSON.parse('{languages}'); </script> """.format( lang_code=get_language(), lang_dir=lang_dir, languages=json.dumps({code: { # Format to match the schema of the content Language model 'id': code, 'lang_name': name, 'lang_direction': get_language_info(code)['bidi'] } for code, name in settings.LANGUAGES}), ) return mark_safe(js)
def _select_locale(self, request): supported = request.event.locales if (hasattr(request, 'event') and request.event) else settings.LANGUAGES language = ( self._language_from_user(request, supported) or self._language_from_cookie(request, supported) or self._language_from_browser(request, supported) ) if hasattr(request, 'event') and request.event: language = language or request.event.locale translation.activate(language) request.LANGUAGE_CODE = translation.get_language() with suppress(pytz.UnknownTimeZoneError): if request.user.is_authenticated: tzname = request.user.timezone elif hasattr(request, 'event') and request.event: tzname = request.event.timezone else: tzname = settings.TIME_ZONE timezone.activate(pytz.timezone(tzname)) request.timezone = tzname
def cached_member(self): if not self.member_id: return None if not self._cache_member_last_update or self._cache_member_last_update < timezone.now() - datetime.timedelta(days=self._cache_member_days): self.force_cache_member() return AttrDict({ 'pk': self.member_id, 'id': self.member_id, 'unicode': self._cache_member_name if get_language() != 'ja' else self._cache_member_japanese_name, 'name': self._cache_member_name, 'japanese_name': self._cache_member_japanese_name, 'image': self._cache_member_image, 'image_url': get_image_url_from_path(self._cache_member_image), 'http_image_url': get_http_image_url_from_path(self._cache_member_image), 'item_url': u'/member/{}/{}/'.format(self.member_id, tourldash(self._cache_member_name)) if self.member_id else '#', 'ajax_item_url': u'/ajax/member/{}/'.format(self.member_id) if self.member_id else '', }) # Cache event
def cached_event(self): if not self._cache_event_last_update or self._cache_event_last_update < timezone.now() - datetime.timedelta(days=self._cache_event_days): self.force_cache_event() if not self._cache_event_id: return None return AttrDict({ 'pk': self._cache_event_id, 'id': self._cache_event_id, 'unicode': self._cache_event_name if get_language() != 'ja' else self._cache_event_japanese_name, 'name': self._cache_event_name, 'japanese_name': self._cache_event_japanese_name, 'image': self._cache_event_image, 'image_url': get_image_url_from_path(self._cache_event_image), 'http_image_url': get_http_image_url_from_path(self._cache_event_image), 'item_url': u'/event/{}/{}/'.format(self._cache_event_id, tourldash(self._cache_event_name)), 'ajax_item_url': u'/ajax/event/{}/'.format(self._cache_event_id), }) # Cache gacha
def __unicode__(self): if self.id: return u'{rarity} {member_name} - {attribute}{name}'.format( rarity=self.rarity, member_name=( self.cached_member.japanese_name if get_language() == 'ja' else self.cached_member.name) if self.cached_member else '', attribute=self.attribute, name=(u' - {}'.format( self.japanese_name if (get_language() == 'ja' and self.japanese_name) or not self.name else self.name) if self.name or self.japanese_name else ''), ) return u'' ############################################################ # Owned Cards
def __iter__(self): yield 'js/bootstrap-datepicker.min.js' lang = translation.get_language() if lang: lang = lang.lower() # There is language name that length>2 or contains uppercase. lang_map = { 'en-au': 'en-AU', 'en-gb': 'en-GB', 'en-us': 'en-us', 'fr-CH': 'fr-CH', 'it-ch': 'it-CH', 'nl-be': 'nl-BE', 'pt-br': 'pt-BR', 'rs-latin': 'rs-latin', 'sr-latin': 'sr-latin', 'zh-cn': 'zh-CN', 'zh-tw': 'zh-TW', } if len(lang) > 2: lang = lang_map.get(lang, 'en-us') if lang not in ('en', 'en-us'): yield 'js/locales/bootstrap-datepicker.%s.min.js' % (lang)
def test_model_attributes(self): posts = [] posts.append(MultiLanguagePost.objects.create( title='first post', slug='first-post', )) posts.append(MultiLanguagePost.objects.create( title='second post', slug='second-post', )) for language in [get_language()]: with override(language): for post in posts: knock_create = post.as_knock(True) self.assertEqual(knock_create['title'], 'new {0}'.format(post._meta.verbose_name)) self.assertEqual(knock_create['message'], post.title) self.assertEqual(knock_create['language'], language)
def notify_items(**kwargs): """ Signal endpoint that actually sends knocks whenever an instance is created / saved """ instance = kwargs.get('instance') created = kwargs.get('created', False) if hasattr(instance, 'send_knock') and active_knocks(instance): try: # This is a stupid generic interface for multilanguage models (hvad / parler) if hasattr(instance, 'get_available_languages'): langs = instance.get_available_languages() else: langs = [get_language()] for lang in langs: with override(lang): instance.send_knock(created) return True except AttributeError: # pragma: no cover pass return False
def regex(self): """ Return a compiled regular expression based on the activate language. """ language_code = get_language() if language_code not in self._regex_dict: regex = self._regex if isinstance(self._regex, six.string_types) else force_text(self._regex) try: compiled_regex = re.compile(regex, re.UNICODE) except re.error as e: raise ImproperlyConfigured( '"%s" is not a valid regular expression: %s' % (regex, six.text_type(e)) ) self._regex_dict[language_code] = compiled_regex return self._regex_dict[language_code]
def to_email(email_class, email, language=None, **data): """ Send email to specified email address """ if language: email_class().send([email], language=language, **data) else: email_class().send([email], translation.get_language(), **data)
def to_user(email_class, user, **data): """ Email user """ try: email_class().send([user.email], user.language, **data) except AttributeError: # this is a fallback in case the user model does not have the language field email_class().send([user.email], translation.get_language(), **data)
def to_staff(email_class, **data): """ Email staff users """ for user in get_user_model().objects.filter(is_staff=True): try: email_class().send([user.email], user.language, **data) except AttributeError: email_class().send([user.email], translation.get_language(), **data)
def to_superuser(email_class, **data): """ Email superusers """ for user in get_user_model().objects.filter(is_superuser=True): try: email_class().send([user.email], user.language, **data) except AttributeError: email_class().send([user.email], translation.get_language(), **data)
def send(self, request, vote: Vote): old_lang = translation.get_language() translation.activate(self.user.language) link = reverse('poll', args=(self.poll.url,)) if vote.anonymous: username = _("Annonymus") elif vote.user: username = vote.user.username else: username = vote.name email_content = render_to_string('poll/mail_watch.txt', { 'receiver': self.user.username, 'user': username if self.poll.show_results == "complete" else _("by an user"), 'poll': self.poll.title, 'link': link, 'hide_participants': self.poll.hide_participants # TODO: simplify merge with usernameshadowing above }) try: send_mail(_("New votes for {}".format(self.poll.title)), email_content, None, [self.user.email]) except SMTPRecipientsRefused: translation.activate(old_lang) messages.error( request, _("The mail server had an error sending the notification to {}".format( self.user.username)) ) translation.activate(old_lang)
def perform_create(self, serializer): """ Override to set user country and language. :param serializer: instance of user model serializer. :type serializer: mk42.apps.users.api.serializers.user.UserSerializer. """ defaults = { "country": GeoIP().country(self.request.META.get("REMOTE_ADDR", None)).get("country_code", ""), "language": get_language(), } serializer.save(**defaults)
def datepicker_locale(): locale_mapping = getattr(settings, 'DATEPICKER_LOCALES', bootstrap_datepicker.LOCALE_MAPPING) return locale_mapping.get(translation.get_language(), 'en')
def reverse_dict(self): language_code = get_language() if language_code not in self._reverse_dict: self._populate() return self._reverse_dict[language_code]
def namespace_dict(self): language_code = get_language() if language_code not in self._namespace_dict: self._populate() return self._namespace_dict[language_code]
def app_dict(self): language_code = get_language() if language_code not in self._app_dict: self._populate() return self._app_dict[language_code]
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 django_apps.is_installed('django.contrib.sites'): Site = django_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
def process_request(self, request): language = translation.get_language_from_request( request, check_path=self.is_language_prefix_patterns_used) translation.activate(language) request.LANGUAGE_CODE = translation.get_language()
def process_response(self, request, response): language = translation.get_language() language_from_path = translation.get_language_from_path(request.path_info) if (response.status_code == 404 and not language_from_path and self.is_language_prefix_patterns_used): urlconf = getattr(request, 'urlconf', None) language_path = '/%s%s' % (language, request.path_info) path_valid = is_valid_path(language_path, urlconf) path_needs_slash = ( not path_valid and ( settings.APPEND_SLASH and not language_path.endswith('/') and is_valid_path('%s/' % language_path, urlconf) ) ) if path_valid or path_needs_slash: script_prefix = get_script_prefix() # Insert language after the script prefix and before the # rest of the URL language_url = request.get_full_path(force_append_slash=path_needs_slash).replace( script_prefix, '%s%s/' % (script_prefix, language), 1 ) return self.response_redirect_class(language_url) if not (self.is_language_prefix_patterns_used and language_from_path): patch_vary_headers(response, ('Accept-Language',)) if 'Content-Language' not in response: response['Content-Language'] = language return response
def i18n(request): from django.utils import translation context_extras = {} context_extras['LANGUAGES'] = settings.LANGUAGES context_extras['LANGUAGE_CODE'] = translation.get_language() context_extras['LANGUAGE_BIDI'] = translation.get_language_bidi() return context_extras
def render(self, context): context[self.variable] = translation.get_language() return ''
def get_language(): ''' Return an active language code that is guaranteed to be in settings.LANGUAGES (Django does not seem to guarantee this for us). ''' lang = _get_language() MODELTRANS_AVAILABLE_LANGUAGES = get_available_languages() if lang in MODELTRANS_AVAILABLE_LANGUAGES: return lang return get_default_language()
def process_request(self, request): client_id = analytics.get_client_id(request) path = request.path language = get_language() headers = request.META # FIXME: on production you might want to run this in background try: analytics.report_view(client_id, path=path, language=language, headers=headers) except Exception: logger.exception('Unable to update analytics')
def reverse(*args, **kwargs): reverse_kwargs = kwargs.get('kwargs') or {} locale = utils.supported_language(reverse_kwargs.pop( 'locale', translation.get_language())) url = django_reverse(*args, **kwargs) _, path = utils.strip_script_prefix(url) return utils.locale_url(path, locale)
def process_response(self, request, response): if 'Content-Language' not in response: response['Content-Language'] = translation.get_language() translation.deactivate() return response
def get_language_bidi(): """Override for Django's get_language_bidi that's aware of more RTL languages. """ return gettext.language_dir(translation.get_language()) == 'rtl'
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)