我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用django.utils.translation.activate()。
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 _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 publish_pages(include_unpublished=False, language=None, site=None): """ Create published public version of selected drafts. """ qs = Page.objects.drafts() if not include_unpublished: qs = qs.filter(title_set__published=True).distinct() if site: qs = qs.filter(site=site) output_language = None for i, page in enumerate(qs): add = True titles = page.title_set if not include_unpublished: titles = titles.filter(published=True) for lang in titles.values_list("language", flat=True): if language is None or lang == language: if not output_language: output_language = lang if not page.publish(lang): add = False # we may need to activate the first (main) language for proper page title rendering activate(output_language) yield (page, add)
def move_all_color_into_groups(apps, schema_editor): LocationGroupCategory = apps.get_model('mapdata', 'LocationGroupCategory') category = LocationGroupCategory.objects.get(name='groups') colors = {} for model_name in ('Level', 'Space', 'Area', 'POI'): model = apps.get_model('mapdata', model_name) for obj in model.objects.filter(color__isnull=False): colors.setdefault(obj.color, []).append(obj) from c3nav.mapdata.models import Location for color, objects in colors.items(): titles = {lang: [] for lang in set(chain(*(obj.titles.keys() for obj in objects)))} for obj in objects: for lang in titles.keys(): translation.activate(lang) titles[lang].append(Location(titles=obj.titles).title) translation.deactivate_all() titles = {lang: ', '.join(values) for lang, values in titles.items()} group = category.groups.create(can_search=False, can_describe=False, color=color, titles=titles) for obj in objects: obj.groups.add(group)
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 send_email(self, request): ''' Sends an email after being successfully added to the database (for user submitted exercises only) ''' try: user = User.objects.get(username=self.license_author) except User.DoesNotExist: return if self.license_author and user.email: translation.activate(user.userprofile.notification_language.short_name) url = request.build_absolute_uri(self.get_absolute_url()) subject = _('Exercise was successfully added to the general database') context = { 'exercise': self.name, 'url': url, 'site': Site.objects.get_current().domain } message = render_to_string('exercise/email_new.tpl', context) mail.send_mail(subject, message, settings.WGER_SETTINGS['EMAIL_FROM'], [user.email], fail_silently=True)
def send_email(self, request): ''' Sends an email after being successfully added to the database (for user submitted ingredients only) ''' if self.user and self.user.email: translation.activate(self.user.userprofile.notification_language.short_name) url = request.build_absolute_uri(self.get_absolute_url()) subject = _('Ingredient was successfully added to the general database') context = { 'ingredient': self.name, 'url': url, 'site': Site.objects.get_current().domain } message = render_to_string('ingredient/email_new.tpl', context) mail.send_mail(subject, message, settings.WGER_SETTINGS['EMAIL_FROM'], [self.user.email], fail_silently=True)
def send_email(user, last_entry, datediff): ''' Notify a user to input the weight entry :type user User :type last_entry Date ''' # Compose and send the email translation.activate(user.userprofile.notification_language.short_name) context = {'site': Site.objects.get_current(), 'date': last_entry, 'days': datediff, 'user': user} subject = _('You have to enter your weight') message = loader.render_to_string('workout/email_weight_reminder.tpl', context) mail.send_mail(subject, message, settings.WGER_SETTINGS['EMAIL_FROM'], [user.email], fail_silently=True)
def translate_url(context, lang=None, *args, **kwargs): """ Get active page's url by a specified language Usage: {% translate_url 'en' %} """ path = context['request'].path cur_language = translation.get_language() try: view = resolve(path) translation.activate(lang) url = reverse( view.view_name, args=view.args, kwargs=view.kwargs, ) except Http404: url = '/' + lang + '/' finally: translation.activate(cur_language) return url
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 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 setUp(self): self.settings_manager = test_utils.TestSettingsManager() settings_fixture(self.settings_manager) translation.activate("en") reload(localeurl_settings)
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 __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 process_request(self, request): translation.activate(self.get_language_for_user(request)) request.LANGUAGE_CODE = translation.get_language()
def process_request(self, request): account = getattr(request.user, "account", None) if account: timezone.activate(account.timezone)
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 process_request(self, request): try: account = getattr(request.user, "account", None) except Account.DoesNotExist: pass else: if account: tz = settings.TIME_ZONE if not account.timezone else account.timezone timezone.activate(tz)
def __setLocale(self): self.__active_locale = translation.get_language() translation.activate(self.locale)
def __resetLocale(self): translation.activate(self.__active_locale) self.__active_locale = None
def process_request(self, request): language = get_language_from_request(request) translation.activate(language) request.LANGUAGE_CODE = translation.get_language()
def handle(self, *args, **options): try: event = Event.objects.get(slug__iexact=options['event']) except Event.DoesNotExist: raise CommandError('Could not find event with slug "{}"'.format(options['event'])) self._exporting_event = event translation.activate(event.locale) settings.COMPRESS_ENABLED = True settings.COMPRESS_OFFLINE = True call_command('rebuild') # collect static files and combine/compress them super().handle(*args, **options)
def __call__(self, request): url = resolve(request.path_info) event_slug = url.kwargs.get('event') if event_slug: request.event = get_object_or_404( Event, slug__iexact=event_slug, ) if hasattr(request, 'event') and request.event: if not request.user.is_anonymous: request.is_orga = request.user.is_superuser or EventPermission.objects.filter( user=request.user, event=request.event, is_orga=True ).exists() request.is_reviewer = request.user.is_superuser or EventPermission.objects.filter( user=request.user, event=request.event, is_reviewer=True ).exists() else: request.is_orga = False request.is_reviewer = False timezone.activate(pytz.timezone(request.event.timezone)) self._set_orga_events(request) if 'orga' in url.namespaces: url = self._handle_orga_url(request, url) if url: return redirect(url) return self.get_response(request)
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 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(self, request): check_path = self.is_language_prefix_patterns_used() language = translation.get_language_from_request( request, check_path=check_path) translation.activate(language) request.LANGUAGE_CODE = translation.get_language()
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 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
def save_records_to_database(organizations): translation.activate('en') counters = ImportCounters() save_organizations(organizations, counters) return counters
def handle(self, *args, **options): translation.activate(settings.LANGUAGE_CODE) try: inquiry = Inquiry.objects.get(pk=options['inquiry_id']) except Inquiry.DoesNotExist: raise CommandError('Inquiry "%s" does not exist' % options['inquiry_id']) for ir in InquiryRequest.objects.filter(inquiry=inquiry, sent=False): result = ir.send_by_email() if result: self.stdout.write(self.style.SUCCESS( 'Successfully sent inquiry to "%s" via %s' % (ir.recipient, ir.recipient.email))) else: self.stderr.write('Failed to send inquiry to "%s" via' % (ir.recipient, ir.recipient.email))
def dispatch(self, request, *args, **kwargs): if self.translations_enabled: translation.activate(request.LANGUAGE_CODE) return super().dispatch(request, *args, **kwargs)
def test_force_default_locale_sets_to_english(rf, settings): request = rf.get('/') instance = middleware.ForceDefaultLocale() translation.activate('de') assert translation.get_language() == 'de' instance.process_request(request) assert translation.get_language() == settings.LANGUAGE_CODE