Python django.utils.translation.activate() Examples

The following are 30 code examples of django.utils.translation.activate(). 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: test_views_default.py    From cadasta-platform with GNU Affero General Public License v3.0 7 votes vote down vote up
def test_signs_up_sets_language(self):
        data = {
            'username': 'sherlock',
            'email': 'sherlock.holmes@bbc.uk',
            'password': '221B@bakerstreet',
            'full_name': 'Sherlock Holmes',
            'language': 'es'
        }
        response = self.request(method='POST', post_data=data)
        assert response.status_code == 302
        assert User.objects.count() == 1
        assert 'account/accountverification/' in response.location
        assert translation.get_language() == 'es'

        # Reset language for following tests
        translation.activate('en') 
Example #2
Source File: test_tags.py    From rdmo with Apache License 2.0 6 votes vote down vote up
def test_i18n_switcher(rf):
    """ The language switcher is rendered correctly. """

    # create a fake template with a name
    template = "{% load core_tags %}{% i18n_switcher %}"

    # set a language
    translation.activate(settings.LANGUAGES[0][0])

    # render the link
    request = rf.get(reverse('home'))
    context = RequestContext(request, {})
    rendered_template = Template(template).render(context)
    for language in settings.LANGUAGES:
        if language == settings.LANGUAGES[0]:
            assert '<a href="/i18n/%s/"><u>%s</u></a>' % language in rendered_template
        else:
            assert'<a href="/i18n/%s/">%s</a>' % language in rendered_template 
Example #3
Source File: tests.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_table_options_language(self):
        """
        Test that the envrionment's language is used if no language provided.
        """
        # default must always contain a language value
        block = TableBlock()
        self.assertIn('language', block.table_options)
        # French
        translation.activate('fr-fr')
        block_fr = TableBlock()
        self.assertEqual('fr-fr', block_fr.table_options['language'])
        translation.activate('it')
        # Italian
        block_it = TableBlock()
        self.assertEqual('it', block_it.table_options['language'])
        # table_options with language provided, different to envrionment
        block_with_lang = TableBlock(table_options={'language': 'ja'})
        self.assertNotEqual('it', block_with_lang.table_options['language'])
        self.assertEqual('ja', block_with_lang.table_options['language'])
        translation.activate('en') 
Example #4
Source File: admin.py    From django-leonardo with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_changeform_initial_data(self, request):
        '''Copy initial data from parent'''
        initial = super(PageAdmin, self).get_changeform_initial_data(request)
        if ('translation_of' in request.GET):
            original = self.model._tree_manager.get(
                pk=request.GET.get('translation_of'))
            initial['layout'] = original.layout
            initial['theme'] = original.theme
            initial['color_scheme'] = original.color_scheme

            # optionaly translate title and make slug
            old_lang = translation.get_language()
            translation.activate(request.GET.get('language'))
            title = _(original.title)
            if title != original.title:
                initial['title'] = title
                initial['slug'] = slugify(title)
            translation.activate(old_lang)

        return initial 
Example #5
Source File: common.py    From donation-tracker with Apache License 2.0 6 votes vote down vote up
def tracker_context(request, qdict=None):
    starttime = datetime.datetime.now()
    language = translation.get_language_from_request(request)
    translation.activate(language)
    request.LANGUAGE_CODE = translation.get_language()
    profile = None
    qdict = qdict or {}
    qdict.update(
        {
            'djangoversion': dv(),
            'pythonversion': pv(),
            'user': request.user,
            'profile': profile,
            'next': request.POST.get('next', request.GET.get('next', request.path)),
            'starttime': starttime,
            'events': tracker.models.Event.objects.all(),
            'settings': settings,
        }
    )
    qdict.setdefault('event', viewutil.get_event(None))
    qdict.setdefault('user', request.user)
    return qdict 
Example #6
Source File: tests.py    From jinja2-django-tags with MIT License 6 votes vote down vote up
def test_localize(self):
        env = Environment(extensions=[DjangoL10n])
        template = env.from_string("{{ foo }}")
        context1 = {'foo': 1.23}
        date = datetime.datetime(2000, 10, 1, 14, 10, 12, tzinfo=timezone.utc)
        context2 = {'foo': date}

        translation.activate('en')
        self.assertEqual('1.23', template.render(context1))

        translation.activate('de')
        self.assertEqual('1,23', template.render(context1))

        translation.activate('es')
        timezone.activate('America/Argentina/Buenos_Aires')
        self.assertEqual('1 de Octubre de 2000 a las 11:10', template.render(context2))

        timezone.activate('Europe/Berlin')
        self.assertEqual('1 de Octubre de 2000 a las 16:10', template.render(context2))

        translation.activate('de')
        self.assertEqual('1. Oktober 2000 16:10', template.render(context2))

        timezone.activate('America/Argentina/Buenos_Aires')
        self.assertEqual('1. Oktober 2000 11:10', template.render(context2)) 
Example #7
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 #8
Source File: test_value.py    From django-localized-fields with MIT License 6 votes vote down vote up
def test_translate_fallback():
        """Tests whether the :see:LocalizedValue class's translate()'s fallback
        functionality works properly."""

        test_value = "myvalue"

        localized_value = LocalizedValue({settings.LANGUAGE_CODE: test_value})

        other_language = settings.LANGUAGES[-1][0]

        # make sure that, by default it returns
        # the value in the default language
        assert localized_value.translate() == test_value

        # make sure that it falls back to the
        # primary language when there's no value
        # available in the current language
        translation.activate(other_language)
        assert localized_value.translate() == test_value

        # make sure that it's just __str__ falling
        # back and that for the other language
        # there's no actual value
        assert localized_value.get(other_language) != test_value 
Example #9
Source File: test_lookups.py    From django-localized-fields with MIT License 6 votes vote down vote up
def test_localized_lookup(self):
        """Tests whether localized lookup properly works."""

        self.TestModel.objects.create(
            text=LocalizedValue(dict(en="text_en", ro="text_ro", nl="text_nl"))
        )

        # assert that it properly lookups the currently active language
        for lang_code, _ in settings.LANGUAGES:
            translation.activate(lang_code)
            assert self.TestModel.objects.filter(
                text="text_" + lang_code
            ).exists()

        # ensure that the default language is used in case no
        # language is active at all
        translation.deactivate_all()
        assert self.TestModel.objects.filter(text="text_en").exists()

        # ensure that hstore lookups still work
        assert self.TestModel.objects.filter(text__ro="text_ro").exists() 
Example #10
Source File: reservations.py    From pasportaservo with GNU Affero General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):
        translation.activate('eo')
        f = NamedTemporaryFile(mode='w+', delete=False, suffix='.csv')
        book = Group.objects.get(name='libro2017')
        writer = csv.writer(f)
        users = (
            User.objects.filter(groups__name='libro2017')
            & User.objects.exclude(reservation__isnull=True)
        ).order_by('reservation__amount', 'first_name').distinct()
        for user in users:
            writer.writerow([
                user.profile.full_name,
                user.email,
                user.profile.rawdisplay_phones(),
                'En la libro' if book in user.groups.all() else 'ne',
                repr(user.reservation_set.first()),
                'http://pspt.se' + user.profile.get_absolute_url(),
            ])
        print(f.name) 
Example #11
Source File: check_settings_files.py    From janeway with GNU Affero General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):
        translation.activate('en')

        with codecs.open(os.path.join(settings.BASE_DIR, 'utils/install/journal_defaults.json'), 'r+', encoding='utf-8') as json_data:
            default_data = json.load(json_data)

        with codecs.open(os.path.join(settings.BASE_DIR, 'utils/install/test.json'), 'r+', encoding='utf-8') as test_json_data:
            test_data = json.load(test_json_data)

        print(len(default_data))
        print(len(test_data))

        for setting in default_data:
            setting_name = setting['setting']['name']
            found = False

            for test_setting in test_data:
                test_setting_name = setting['setting']['name']
                if test_setting_name == setting_name:
                    found = True

            if found:
                print('{0} found'.format(setting_name))
            else:
                print('{0} not found'.format(setting_name)) 
Example #12
Source File: run_upgrade.py    From janeway with GNU Affero General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):

        if not options.get('path'):
            print('No upgrade selected. Available upgrade paths: ')
            for file in get_modules():
                module_name = file.split('.')[0]
                print('- {module_name}'.format(module_name=module_name))
                print('To run an upgrade use the following: `python3 manage.py run_upgrade --script 12_13`')
        else:
            translation.activate('en')
            upgrade_module_name = options.get('path')
            upgrade_module_path = 'utils.upgrade.{module_name}'.format(module_name=upgrade_module_name)

            try:
                upgrade_module = import_module(upgrade_module_path)
                upgrade_module.execute()
            except ImportError as e:
                print('There was an error running the requested upgrade: ')
                print(e) 
Example #13
Source File: process_crossref_events.py    From janeway with GNU Affero General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):
        """Collects Crossref Events, parses them and stores new events locally.

        :param args: None
        :param options: None
        :return: None
        """

        translation.activate(settings.LANGUAGE_CODE)

        file_name = '{date}.json'.format(date=timezone.localdate())
        file_path = os.path.join(settings.BASE_DIR, 'files', 'temp', file_name)

        if os.path.isfile(file_path):

            # Process file
            print('Existing file found.')
            process_events()

        else:

            # Fetch data
            print('Fetching data from crossref event tracking API.')
            fetch_crossref_data()
            process_events() 
Example #14
Source File: middleware.py    From cadasta-platform with GNU Affero General Public License v3.0 6 votes vote down vote up
def process_response(self, request, response):
        if not hasattr(request, 'user'):
            return response

        if not request.user.is_authenticated:
            return response

        user_language = request.user.language
        current_language = translation.get_language()
        if user_language == current_language:
            return response

        translation.activate(user_language)
        request.session[translation.LANGUAGE_SESSION_KEY] = user_language

        return response 
Example #15
Source File: test_manager_mixin.py    From django-linguist with MIT License 5 votes vote down vote up
def test_language_activation(self):
        # Default to "en" (settings.LANGUAGE_CODE)
        self.assertEqual(translation.get_language(), "en")

        self.instance.activate_language("en")
        self.instance.title = "hello"
        self.instance.activate_language("fr")
        self.instance.title = "bonjour"
        self.instance.save()
        self.assertEqual(Translation.objects.count(), 2)
        self.assertEqual(
            FooModel.objects.with_translations().first().active_language, "en"
        )

        # Switch to "fr"
        translation.activate("fr")
        self.assertEqual(translation.get_language(), "fr")
        instance = FooModel.objects.with_translations().first()
        self.assertEqual(instance.active_language, "fr")
        self.assertEqual(instance.title, "bonjour")

        # Switch to "en"
        translation.activate("en")
        self.assertEqual(translation.get_language(), "en")
        instance = FooModel.objects.with_translations().first()
        self.assertEqual(instance.active_language, "en")
        self.assertEqual(instance.title, "hello") 
Example #16
Source File: test_utils.py    From django-linguist with MIT License 5 votes vote down vote up
def test_build_localized_field_name(self):
        self.assertEqual(utils.build_localized_field_name("title", "fr"), "title_fr")
        self.assertEqual(
            utils.build_localized_field_name("title", "fr-ca"), "title_fr_ca"
        )

        translation.deactivate_all()
        self.assertEqual(utils.build_localized_field_name("title"), "title_en")

        translation.activate("it")
        self.assertEqual(utils.build_localized_field_name("title"), "title_it") 
Example #17
Source File: test_views.py    From django-linguist with MIT License 5 votes vote down vote up
def test_translation_activate(self):
        for language in self.languages:
            translation.activate(language)
            response = self.client.get("/")
            self.assertEqual(response.status_code, 200)
            self._check_language(response) 
Example #18
Source File: helpers.py    From janeway with GNU Affero General Public License v3.0 5 votes vote down vote up
def __enter__(self):
        translation.activate(self.language_code) 
Example #19
Source File: scrape_oai.py    From janeway with GNU Affero General Public License v3.0 5 votes vote down vote up
def handle(self, *args, **options):
        """Imports an OAI feed into Janeway.

        :param args: None
        :param options: Dictionary containing 'url', 'journal_id', 'user_id', and a boolean '--delete' flag
        :return: None
        """
        translation.activate('en')
        importer.import_oai(**options) 
Example #20
Source File: test_model_mixin.py    From django-linguist with MIT License 5 votes vote down vote up
def test_no_translation_default_language(self):
        # This is the case of:
        # * "default_language" is not defined in linguist meta
        # * No translation is available for the current supported language
        # So we always try to display default language or empty value
        m = FooModel(title_en="hello", title_fr="bonjour")
        m.save()

        saved_lang = translation.get_language()
        translation.activate("it")

        self.assertEqual(m.title, "hello")

        translation.activate(saved_lang) 
Example #21
Source File: serializers.py    From SchoolIdolAPI with Apache License 2.0 5 votes vote down vote up
def get_japanese_center_skill(self, obj):
        if not obj.center_skill:
            return None
        old_lang = translation.get_language()
        translation.activate("ja")
        sentence = string_concat(_(obj.center_skill.split(' ')[0]), ' ', _(obj.center_skill.split(' ')[1]))
        sentence = unicode(sentence)
        translation.activate(old_lang)
        return sentence 
Example #22
Source File: install_journal.py    From janeway with GNU Affero General Public License v3.0 5 votes vote down vote up
def handle(self, *args, **options):
        """ Create a new journal on this Janeway install.

        :param args: None
        :param options: Dictionary containing keys '--journal_name', '--journal_code' and '--base_url'. If any of these
        are not provided, they will be requested via raw_input. --delete can be provided to find and delete the journal
        if it already exists.
        :return: None
        """

        translation.activate('en')
        delete = True if options.get('delete') else False
        journal_name = options.get('journal_name') if options.get('journal_name') else input(
            'Enter the full name of the Journal: ')
        journal_code = options.get('journal_code') if options.get('journal_code') else input(
            'Enter a short name for the Journal: ')
        base_url = options.get('base_url') if options.get('base_url') else input(
            'Enter a base url for the Journal: ')

        if journal_name and journal_code and base_url:
            print('Creating new journal {0} ({1}) with domain {2}.'.format(journal_name, journal_code, base_url))

            install.journal(name=journal_name, code=journal_code, base_url=base_url, delete=delete)

            if not delete:
                journal = journal_models.Journal.objects.get(code=journal_code)
                install.update_license(journal, management_command=False)
                install.update_issue_types(journal, management_command=False)

            call_command('show_configured_journals') 
Example #23
Source File: serializers.py    From SchoolIdolAPI with Apache License 2.0 5 votes vote down vote up
def get_japanese_center_skill_details(self, obj):
        if not obj.center_skill:
            return None
        sentence, data = obj.get_center_skill_details()
        if sentence and data:
            old_lang = translation.get_language()
            translation.activate("ja")
            sentence = _(sentence).format(*[_(d) for d in data])
            translation.activate(old_lang)
            return sentence
        return None 
Example #24
Source File: locale.py    From python with Apache License 2.0 5 votes vote down vote up
def process_request(self, request):
        urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
        i18n_patterns_used, prefixed_default_language = is_language_prefix_patterns_used(urlconf)
        language = translation.get_language_from_request(request, check_path=i18n_patterns_used)
        language_from_path = translation.get_language_from_path(request.path_info)
        if not language_from_path and i18n_patterns_used and not prefixed_default_language:
            language = settings.LANGUAGE_CODE
        translation.activate(language)
        request.LANGUAGE_CODE = translation.get_language() 
Example #25
Source File: load_default_settings.py    From janeway with GNU Affero General Public License v3.0 5 votes vote down vote up
def handle(self, *args, **options):

        translation.activate('en')
        install.update_settings(management_command=True) 
Example #26
Source File: __init__.py    From python with Apache License 2.0 5 votes vote down vote up
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 
Example #27
Source File: test_translations.py    From cadasta-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_translations(self):
        cur_language = translation.get_language()
        try:
            translation.activate('de')
            assert _("First name") == "Vorname"
        finally:
            translation.activate(cur_language) 
Example #28
Source File: django_wsgi.py    From Flask-P2P with MIT License 5 votes vote down vote up
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() 
Example #29
Source File: test_fields_array.py    From richie with MIT License 5 votes vote down vote up
def setUp(self):
        """
        Force i18n language so we can check the value of error messages without having our tests
        broken when the local language on the host machine changes
        """
        translation.activate("en") 
Example #30
Source File: test_value.py    From django-localized-fields with MIT License 5 votes vote down vote up
def test_get_default_language():
        """Tests whether the :see:LocalizedValue class's see:get function
        properly gets the value in the default language."""

        keys = get_init_values()
        localized_value = LocalizedValue(keys)

        for language, _ in keys.items():
            translation.activate(language)
            assert localized_value.get() == keys[settings.LANGUAGE_CODE]