Python django.utils.translation.deactivate() Examples

The following are 25 code examples of django.utils.translation.deactivate(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.utils.translation , or try the search function .
Example #1
Source File: locale.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def process_response(self, request, response):
        language = translation.get_language()
        if (response.status_code == 404 and
                not translation.get_language_from_path(request.path_info)
                    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)
            if (not path_valid and settings.APPEND_SLASH
                    and not language_path.endswith('/')):
                path_valid = is_valid_path("%s/" % language_path, urlconf)

            if path_valid:
                language_url = "%s://%s/%s%s" % (
                    request.is_secure() and 'https' or 'http',
                    request.get_host(), language, request.get_full_path())
                return HttpResponseRedirect(language_url)
        translation.deactivate()

        patch_vary_headers(response, ('Accept-Language',))
        if 'Content-Language' not in response:
            response['Content-Language'] = language
        return response 
Example #2
Source File: backends.py    From linkedevents with MIT License 6 votes vote down vote up
def forward_to_backends(self, method, *args, **kwargs):
        # forwards the desired backend method to all the language backends
        initial_language = translation.get_language()
        # retrieve unique backend name
        backends = []
        for language, _ in settings.LANGUAGES:
            using = '%s-%s' % (self.connection_alias, language)
            # Ensure each backend is called only once
            if using in backends:
                continue
            else:
                backends.append(using)
            translation.activate(language)
            backend = connections[using].get_backend()
            getattr(backend.parent_class, method)(backend, *args, **kwargs)

        if initial_language is not None:
            translation.activate(initial_language)
        else:
            translation.deactivate() 
Example #3
Source File: test_views.py    From ideascube with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_export_loan_should_be_ok_in_arabic(staffapp):
    translation.activate('ar')
    specimen = SpecimenFactory(item__name="an item", barcode="123")
    loan = LoanFactory(specimen=specimen, comments=u"النبي (كتاب)")
    url = reverse('monitoring:export_loan')
    resp = staffapp.get(url, status=200)
    assert resp.content.decode().startswith("item,barcode,serial,user,loaned at,due date,returned at,comments\r\nan item,123")  # noqa
    resp.mustcontain(loan.comments)
    translation.deactivate() 
Example #4
Source File: test_utils.py    From donate-wagtail with Mozilla Public License 2.0 5 votes vote down vote up
def test_reverse_produces_correct_url_prefix(self):
        translation.activate('en-GB')
        url = reverse('payments:completed')
        self.assertTrue(url.startswith('/en-GB/'))
        translation.deactivate() 
Example #5
Source File: test_manythings.py    From ls.joyous with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def tearDown(self):
        translation.deactivate() 
Example #6
Source File: test_manythings.py    From ls.joyous with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def tearDown(self):
        translation.deactivate() 
Example #7
Source File: test_calendar.py    From ls.joyous with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def tearDown(self):
        translation.deactivate() 
Example #8
Source File: test_pages.py    From ls.joyous with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def tearDown(self):
        translation.deactivate() 
Example #9
Source File: test_extra_info.py    From ls.joyous with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def tearDown(self):
        translation.deactivate() 
Example #10
Source File: middleware.py    From devops with MIT License 5 votes vote down vote up
def process_response(self, request, response):
        patch_vary_headers(response, ("Accept-Language",))
        response["Content-Language"] = translation.get_language()
        translation.deactivate()
        return response 
Example #11
Source File: helpers.py    From janeway with GNU Affero General Public License v3.0 5 votes vote down vote up
def __exit__(self, *exc):
        translation.deactivate() 
Example #12
Source File: locale.py    From django2-project-template with MIT License 5 votes vote down vote up
def __call__(self, request):
        if request.META['PATH_INFO'].startswith('/en'):
            language = 'en'
        else:
            language = 'tr'

        translation.activate(language)
        request.LANGUAGE_CODE = translation.get_language()
        response = self.get_response(request)

        patch_vary_headers(response, ('Accept-Language',))
        response['Content-Language'] = translation.get_language()
        translation.deactivate()
        return response 
Example #13
Source File: send_mail_notifications.py    From anytask with MIT License 5 votes vote down vote up
def send_fulltext(domain, from_email):
    notify_messages = []

    for i_message, message in enumerate(
            Message.objects.exclude(
                send_notify_messages__isnull=True
            ).prefetch_related('recipients')
    ):
        notify_messages.append([])
        for user in message.recipients.all():
            if not user.email:
                continue

            user_profile = user.profile
            user_profile.send_notify_messages.remove(message)

            lang = user_profile.language
            translation.activate(lang)

            subject = message.title
            message_text = render_mail(message, user)

            plain_text = strip_tags(message_text).replace(' ', ' ')

            context = {
                "domain": domain,
                "title": subject,
                "message_text": message_text,
            }
            html = render_to_string('email_fulltext_mail.html', context)

            notify_messages[i_message].append((subject, plain_text, html, from_email, [user.email]))

            translation.deactivate()

    return notify_messages 
Example #14
Source File: send_mail_notifications.py    From anytask with MIT License 5 votes vote down vote up
def send_only_notify(domain, from_email):
    notify_messages = []

    for user_profile in UserProfile.objects.exclude(send_notify_messages__isnull=True).select_related('user'):
        user = user_profile.user
        if not user.email:
            continue

        unread_messages = user_profile.send_notify_messages.all()
        unread_count = len(unread_messages)

        if not unread_count:
            continue

        lang = user_profile.language
        translation.activate(lang)

        user_profile.send_notify_messages.clear()

        subject = u'{0}, '.format(user.first_name) + _(u'est_novye_soobshenija')

        unread_count_string = get_string(unread_count)

        context = {
            "domain": domain,
            "title": subject,
            "user": user,
            "unread_count": unread_count,
            "unread_count_string": unread_count_string,
            "messages": unread_messages,
            "STATIC_URL": settings.STATIC_URL,
        }

        plain_text = render_to_string('email_notification_mail.txt', context)
        html = render_to_string('email_notification_mail.html', context)
        notify_messages.append((subject, plain_text, html, from_email, [user.email]))

        translation.deactivate()

    return notify_messages 
Example #15
Source File: send_notifications.py    From anytask with MIT License 5 votes vote down vote up
def get_message(user, user_type, issue, events, from_email, domain):
    user_profile = user.profile

    if not user_profile.send_my_own_events:
        events = events.exclude(author_id=user.id)

    if not events:
        return ()

    lang = user_profile.language
    translation.activate(lang)
    timezone.activate(user_profile.time_zone)

    subject = (_(u'kurs') + u': {0} | ' + _(u'zadacha') + u': {1} | ' + _(u'student') + u': {2} {3}'). \
        format(issue.task.course.name, issue.task.get_title(lang), issue.student.last_name, issue.student.first_name)

    context = {
        "user": user,
        "domain": domain,
        "title": subject,
        "user_type": user_type,
        "issue": issue,
        "events": events,
        "STATIC_URL": settings.STATIC_URL,
    }

    plain_text = render_to_string('email_issue_notification.txt', context)
    html = render_to_string('email_issue_notification.html', context)
    translation.deactivate()
    timezone.deactivate()

    return subject, plain_text, html, from_email, [user.email] 
Example #16
Source File: test_views.py    From ideascube with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_export_users_should_be_ok_in_arabic(staffapp, settings):
    translation.activate('ar')
    user1 = UserFactory(serial="جبران خليل جبران")
    user2 = UserFactory(serial="النبي (كتاب)")
    resp = staffapp.get(reverse('user_export'), status=200)
    resp.mustcontain('serial')
    resp.mustcontain(user1.serial)
    resp.mustcontain(user2.serial)
    translation.deactivate() 
Example #17
Source File: test_views.py    From ideascube with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_create_content_with_default_language(staffapp):
    translation.activate('fr')

    url = reverse('blog:content_create')
    form = staffapp.get(url).forms['model_form']
    form['title'] = 'my content title'
    form['text'] = 'my content text'
    assert form['lang'].value == 'fr'
    form.submit().follow()

    content = Content.objects.last()
    assert content.lang == 'fr'

    translation.deactivate() 
Example #18
Source File: test_views.py    From ideascube with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_published_at_can_be_still_set_the_French_way(staffapp, published):
    # We force the input at load time, but we should still accept other format
    # at save.
    translation.activate('fr')
    url = reverse('blog:content_update', kwargs={'pk': published.pk})
    form = staffapp.get(url).forms['model_form']
    form['published_at'] = '11/01/2015'
    form.submit().follow()
    assert Content.objects.count()
    assert Content.objects.first().published_at.date() == date(2015, 1, 11)
    translation.deactivate() 
Example #19
Source File: test_views.py    From ideascube with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_published_at_is_YMD_formatted_even_in_other_locale(staffapp,
                                                            published):
    published.published_at = datetime(2015, 1, 7, tzinfo=timezone.utc)
    published.save()
    translation.activate('fr')
    url = reverse('blog:content_update', kwargs={'pk': published.pk})
    form = staffapp.get(url).forms['model_form']
    assert form['published_at'].value == '2015-01-07'
    translation.deactivate() 
Example #20
Source File: test_views.py    From ideascube with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_export_inventory_should_be_ok_in_arabic(staffapp, settings):
    translation.activate('ar')
    inventory = InventoryFactory()
    specimen = SpecimenFactory(item__name="an item", comments=u"النبي (كتاب)")
    InventorySpecimen.objects.create(inventory=inventory, specimen=specimen)
    url = reverse('monitoring:inventory_export', kwargs={'pk': inventory.pk})
    resp = staffapp.get(url, status=200)
    resp.mustcontain(specimen.comments)
    translation.deactivate() 
Example #21
Source File: notifymail.py    From django-nyt with Apache License 2.0 4 votes vote down vote up
def handle(self, *args, **options):  # noqa: max-complexity=12
        # activate the language
        activate(settings.LANGUAGE_CODE)

        options.setdefault('daemon', False)
        options.setdefault('cron', False)
        options.setdefault('no_sys_exit', False)

        self.options = options

        daemon = options['daemon']
        cron = options['cron']

        assert not (daemon and cron), (
            "You cannot both choose cron and daemon options"
        )

        self.logger = logging.getLogger('django_nyt')

        if not self.logger.handlers:
            if daemon:
                handler = logging.FileHandler(filename=options['log'])
            else:
                handler = logging.StreamHandler(self.stdout)
            self.logger.addHandler(handler)
            self.logger.setLevel(logging.INFO)

        self.logger.info("Starting django_nyt e-mail dispatcher")

        if not nyt_settings.SEND_EMAILS:
            print("E-mails disabled - quitting.")
            sys.exit()

        # Run as daemon, ie. fork the process
        if daemon:
            self._daemonize()

        # create a connection to smtp server for reuse
        connection = mail.get_connection()

        if cron:
            self.send_mails(connection)
            return

        if not daemon:
            print("Entering send-loop, CTRL+C to exit")
        try:
            self.send_loop(connection, int(options['sleep_time']))
        except KeyboardInterrupt:
            print("\nQuitting...")

        # deactivate the language
        deactivate() 
Example #22
Source File: notifymail.py    From django-nyt with Apache License 2.0 4 votes vote down vote up
def handle(self, *args, **options):  # noqa: max-complexity=12
        # activate the language
        activate(settings.LANGUAGE_CODE)

        options.setdefault('daemon', False)
        options.setdefault('cron', False)
        options.setdefault('no_sys_exit', False)

        self.options = options

        daemon = options['daemon']
        cron = options['cron']

        assert not (daemon and cron), (
            "You cannot both choose cron and daemon options"
        )

        self.logger = logging.getLogger('django_nyt')

        if not self.logger.handlers:
            if daemon:
                handler = logging.FileHandler(filename=options['log'])
            else:
                handler = logging.StreamHandler(self.stdout)
            self.logger.addHandler(handler)
            self.logger.setLevel(logging.INFO)

        self.logger.info("Starting django_nyt e-mail dispatcher")

        if not nyt_settings.SEND_EMAILS:
            print("E-mails disabled - quitting.")
            sys.exit()

        # Run as daemon, ie. fork the process
        if daemon:
            self._daemonize()

        # create a connection to smtp server for reuse
        connection = mail.get_connection()

        if cron:
            self.send_mails(connection)
            return

        if not daemon:
            print("Entering send-loop, CTRL+C to exit")
        try:
            self.send_loop(connection, int(options['sleep_time']))
        except KeyboardInterrupt:
            print("\nQuitting...")

        # deactivate the language
        deactivate() 
Example #23
Source File: check_contest.py    From anytask with MIT License 4 votes vote down vote up
def handle(self, **options):
        start_time = time.time()
        contest_marks_len = 0
        contest_submissions = ContestSubmission.objects \
            .filter(Q(got_verdict=False) & (Q(send_error__isnull=True) | Q(send_error=""))) \
            .exclude(run_id__exact="") \
            .exclude(run_id__isnull=True)
        for contest_submission in contest_submissions:
            try:
                issue = contest_submission.issue
                task = issue.task
                lang = UserProfile.objects.get(user=contest_submission.author).language
                translation.activate(lang)

                comment = contest_submission.check_submission()
                if contest_submission.got_verdict:
                    if contest_submission.verdict == 'ok' and \
                            not task.course.send_rb_and_contest_together and \
                            task.rb_integrated:
                        anyrb = AnyRB(contest_submission.file.event)
                        review_request_id = anyrb.upload_review()
                        if review_request_id is not None:
                            comment += '\n' + u'<a href="{1}/r/{0}">Review request {0}</a>'. \
                                format(review_request_id, settings.RB_API_URL)
                        else:
                            comment += '\n' + _(u'oshibka_otpravki_v_rb')
                    if contest_submission.verdict == 'ok' and \
                            task.accepted_after_contest_ok and \
                            not issue.is_status_accepted():
                        if task.deadline_time and task.deadline_time < timezone.now() and \
                                task.course.issue_status_system.has_accepted_after_deadline():
                            issue.set_status_accepted_after_deadline()
                            if not issue.task.score_after_deadline:
                                comment += '\n' + _(u'bally_ne_uchityvautsia')
                        else:
                            issue.set_status_accepted()

                    if contest_submission.verdict == 'ok':
                        if issue.task.course.take_mark_from_contest:
                            contest_submission.get_contest_mark()
                            contest_marks_len += 1

                    comment_verdict(issue, contest_submission.verdict == 'ok', comment)
                translation.deactivate()
            except Exception as e:
                logger.exception(e)

        # for contest_id, students_info in contest_marks.iteritems():
        #     set_contest_marks(contest_id, students_info)

        # logging to cron log
        print "Command check_contest check {0} submissions ({1} - with marks) took {2} seconds" \
            .format(len(contest_submissions), contest_marks_len, time.time() - start_time) 
Example #24
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 4 votes vote down vote up
def test_middleware(self):
        def set_cache(request, lang, msg):
            translation.activate(lang)
            response = HttpResponse()
            response.content = msg
            return UpdateCacheMiddleware().process_response(request, response)

        # cache with non empty request.GET
        request = self.factory.get(self.path, {'foo': 'bar', 'other': 'true'})
        request._cache_update_cache = True

        get_cache_data = FetchFromCacheMiddleware().process_request(request)
        # first access, cache must return None
        self.assertIsNone(get_cache_data)
        response = HttpResponse()
        content = 'Check for cache with QUERY_STRING'
        response.content = content
        UpdateCacheMiddleware().process_response(request, response)
        get_cache_data = FetchFromCacheMiddleware().process_request(request)
        # cache must return content
        self.assertIsNotNone(get_cache_data)
        self.assertEqual(get_cache_data.content, content.encode())
        # different QUERY_STRING, cache must be empty
        request = self.factory.get(self.path, {'foo': 'bar', 'somethingelse': 'true'})
        request._cache_update_cache = True
        get_cache_data = FetchFromCacheMiddleware().process_request(request)
        self.assertIsNone(get_cache_data)

        # i18n tests
        en_message = "Hello world!"
        es_message = "Hola mundo!"

        request = self.factory.get(self.path)
        request._cache_update_cache = True
        set_cache(request, 'en', en_message)
        get_cache_data = FetchFromCacheMiddleware().process_request(request)
        # The cache can be recovered
        self.assertIsNotNone(get_cache_data)
        self.assertEqual(get_cache_data.content, en_message.encode())
        # change the session language and set content
        request = self.factory.get(self.path)
        request._cache_update_cache = True
        set_cache(request, 'es', es_message)
        # change again the language
        translation.activate('en')
        # retrieve the content from cache
        get_cache_data = FetchFromCacheMiddleware().process_request(request)
        self.assertEqual(get_cache_data.content, en_message.encode())
        # change again the language
        translation.activate('es')
        get_cache_data = FetchFromCacheMiddleware().process_request(request)
        self.assertEqual(get_cache_data.content, es_message.encode())
        # reset the language
        translation.deactivate() 
Example #25
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 4 votes vote down vote up
def test_middleware(self):
        def set_cache(request, lang, msg):
            translation.activate(lang)
            response = HttpResponse()
            response.content = msg
            return UpdateCacheMiddleware().process_response(request, response)

        # cache with non empty request.GET
        request = self.factory.get(self.path, {'foo': 'bar', 'other': 'true'})
        request._cache_update_cache = True

        get_cache_data = FetchFromCacheMiddleware().process_request(request)
        # first access, cache must return None
        self.assertIsNone(get_cache_data)
        response = HttpResponse()
        content = 'Check for cache with QUERY_STRING'
        response.content = content
        UpdateCacheMiddleware().process_response(request, response)
        get_cache_data = FetchFromCacheMiddleware().process_request(request)
        # cache must return content
        self.assertIsNotNone(get_cache_data)
        self.assertEqual(get_cache_data.content, content.encode())
        # different QUERY_STRING, cache must be empty
        request = self.factory.get(self.path, {'foo': 'bar', 'somethingelse': 'true'})
        request._cache_update_cache = True
        get_cache_data = FetchFromCacheMiddleware().process_request(request)
        self.assertIsNone(get_cache_data)

        # i18n tests
        en_message = "Hello world!"
        es_message = "Hola mundo!"

        request = self.factory.get(self.path)
        request._cache_update_cache = True
        set_cache(request, 'en', en_message)
        get_cache_data = FetchFromCacheMiddleware().process_request(request)
        # The cache can be recovered
        self.assertIsNotNone(get_cache_data)
        self.assertEqual(get_cache_data.content, en_message.encode())
        # change the session language and set content
        request = self.factory.get(self.path)
        request._cache_update_cache = True
        set_cache(request, 'es', es_message)
        # change again the language
        translation.activate('en')
        # retrieve the content from cache
        get_cache_data = FetchFromCacheMiddleware().process_request(request)
        self.assertEqual(get_cache_data.content, en_message.encode())
        # change again the language
        translation.activate('es')
        get_cache_data = FetchFromCacheMiddleware().process_request(request)
        self.assertEqual(get_cache_data.content, es_message.encode())
        # reset the language
        translation.deactivate()