django.utils.translation.override

Here are the examples of the python api django.utils.translation.override taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: GAE-Bulk-Mailer
Source File: tests.py
View license
    def test_i18n_intcomma(self):
        test_list = (100, 1000, 10123, 10311, 1000000, 1234567.25,
                     '100', '1000', '10123', '10311', '1000000', None)
        result_list = ('100', '1.000', '10.123', '10.311', '1.000.000', '1.234.567,25',
                       '100', '1.000', '10.123', '10.311', '1.000.000', None)
        with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True):
            with translation.override('de'):
                self.humanize_tester(test_list, result_list, 'intcomma')

Example 2

Project: GAE-Bulk-Mailer
Source File: tests.py
View license
    def test_i18n_intword(self):
        test_list = ('100', '1000000', '1200000', '1290000',
                     '1000000000', '2000000000', '6000000000000')
        result_list = ('100', '1,0 Million', '1,2 Millionen', '1,3 Millionen',
                       '1,0 Milliarde', '2,0 Milliarden', '6,0 Billionen')
        with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True):
            with translation.override('de'):
                self.humanize_tester(test_list, result_list, 'intword')

Example 3

Project: PyClassLessons
Source File: test_basic.py
View license
    @skipIfCustomUser
    def test_user_verbose_names_translatable(self):
        "Default User model verbose names are translatable (#19945)"
        with translation.override('en'):
            self.assertEqual(User._meta.verbose_name, 'user')
            self.assertEqual(User._meta.verbose_name_plural, 'users')
        with translation.override('es'):
            self.assertEqual(User._meta.verbose_name, 'usuario')
            self.assertEqual(User._meta.verbose_name_plural, 'usuarios')

Example 4

Project: PyClassLessons
Source File: test_forms.py
View license
    def test_inactive_user_i18n(self):
        with self.settings(USE_I18N=True), translation.override('pt-br', deactivate=True):
            # The user is inactive.
            data = {
                'username': 'inactive',
                'password': 'password',
            }
            form = AuthenticationForm(None, data)
            self.assertFalse(form.is_valid())
            self.assertEqual(form.non_field_errors(),
                             [force_text(form.error_messages['inactive'])])

Example 5

Project: PyClassLessons
Source File: test_forms.py
View license
    @override_settings(APPEND_SLASH=True,
            MIDDLEWARE_CLASSES=('django.middleware.common.CommonMiddleware',))
    def test_flatpage_requires_trailing_slash_with_append_slash(self):
        form = FlatpageForm(data=dict(url='/no_trailing_slash', **self.form_data))
        with translation.override('en'):
            self.assertFalse(form.is_valid())
            self.assertEqual(form.errors['url'], ["URL is missing a trailing slash."])

Example 6

Project: PyClassLessons
Source File: test_forms.py
View license
    def test_flatpage_admin_form_url_uniqueness_validation(self):
        "The flatpage admin form correctly enforces url uniqueness among flatpages of the same site"
        data = dict(url='/myflatpage1/', **self.form_data)

        FlatpageForm(data=data).save()

        f = FlatpageForm(data=data)

        with translation.override('en'):
            self.assertFalse(f.is_valid())

            self.assertEqual(
                f.errors,
                {'__all__': ['Flatpage with url /myflatpage1/ already exists for site example.com']})

Example 7

Project: PyClassLessons
Source File: tests.py
View license
    def test_ordinal(self):
        test_list = ('1', '2', '3', '4', '11', '12',
                     '13', '101', '102', '103', '111',
                     'something else', None)
        result_list = ('1st', '2nd', '3rd', '4th', '11th',
                       '12th', '13th', '101st', '102nd', '103rd',
                       '111th', 'something else', None)

        with translation.override('en'):
            self.humanize_tester(test_list, result_list, 'ordinal')

Example 8

Project: PyClassLessons
Source File: tests.py
View license
    def test_i18n_html_ordinal(self):
        """Allow html in output on i18n strings"""
        test_list = ('1', '2', '3', '4', '11', '12',
                     '13', '101', '102', '103', '111',
                     'something else', None)
        result_list = ('1<sup>er</sup>', '2<sup>e</sup>', '3<sup>e</sup>', '4<sup>e</sup>',
                       '11<sup>e</sup>', '12<sup>e</sup>', '13<sup>e</sup>', '101<sup>er</sup>',
                       '102<sup>e</sup>', '103<sup>e</sup>', '111<sup>e</sup>', 'something else',
                       'None')

        with translation.override('fr-fr'):
            self.humanize_tester(test_list, result_list, 'ordinal', lambda x: x)

Example 9

Project: django-shop
Source File: indexes.py
View license
    def prepare(self, product):
        if hasattr(product, 'translations'):
            product.set_current_language(self.language)
        with translation.override(self.language):
            data = super(ProductIndex, self).prepare(product)
        return data

Example 10

Project: rapidsms
Source File: app.py
View license
    def handle(self, msg):
        if msg.text == "lang-hello":
            with translation.override(msg.connection.contact.language):
                msg.respond(_('hello'))
            return True
        elif msg.text == 'settings-hello':
            msg.respond(_('hello'))
            return True

Example 11

Project: Django--an-app-at-a-time
Source File: options.py
View license
    @property
    def verbose_name_raw(self):
        """
        There are a few places where the untranslated verbose name is needed
        (so that we get the same value regardless of currently active
        locale).
        """
        with override(None):
            return force_text(self.verbose_name)

Example 12

View license
    @mock.patch('elasticsearch.Elasticsearch')
    def test_multilingual_search(self, mock_es):
        es = ElasticsearchMultilingualSearchBackend('default', **Data.connection_options)
        es.setup()
        kwargs = Data.search_kwargs.copy()
        for language in ['de', 'en', 'ru']:
            with translation.override(language):
                es.search('*:*', end_offset=1)
                kwargs['index'] = es._index_name_for_language(language)
                es.conn.search.assert_called_with(**kwargs)

Example 13

View license
def test_field_title_quoting():
    with translation.override("en"):
        field = forms.ModelMultipleChoiceField(queryset=User.objects.all(), help_text="Something about \"Control\"")
        field.choices = []  # Don't bother with database stuff
        assert "\"Control\"" in force_text(field.help_text)
        form = forms.Form()
        form.fields["field1"] = field
        form.fields["field2"] = forms.CharField(label="An Unrelated Field")
        assert "&quot;Control&quot;" in force_text(AdminFieldRenderer(form["field1"]).render())
        assert "title=\"\"" not in force_text(AdminFieldRenderer(form["field2"]).render())

Example 14

Project: shuup
Source File: test_addresses.py
View license
def test_home_country_in_address():
    with override("fi"):
        finnish_address = MutableAddress(country="FI")
        with override_settings(SHUUP_ADDRESS_HOME_COUNTRY="US"):
            assert "Suomi" in str(finnish_address), "When home is not Finland, Finland appears in address string"
        with override_settings(SHUUP_ADDRESS_HOME_COUNTRY="FI"):
            assert "Suomi" not in str(finnish_address), "When home is Finland, Finland does not appear in address string"

Example 15

Project: shuup
Source File: test_simple_search.py
View license
@pytest.mark.django_db
def test_simple_search_no_results(rf):
    cache.clear()
    with translation.override("xx"):  # use built-in translation
        get_default_shop()
        view = SearchView.as_view()
        resp = view(apply_request_middleware(rf.get("/", {"q": UNLIKELY_STRING})))
        assert NO_RESULTS_FOUND_STRING in resp.rendered_content
        resp = view(apply_request_middleware(rf.get("/")))
        assert NO_RESULTS_FOUND_STRING in resp.rendered_content, "No query string no results"

Example 16

Project: shuup
Source File: test_languages.py
View license
@pytest.mark.django_db
def test_create_multilanguage_page():
    with translation.override("de"):
        page_id = create_multilanguage_page(url="multi").pk

        with translation.override("fi"):
            page = Page.objects.get(pk=page_id)
            assert page.title == "test, Finnisch"
            assert page.url == "multi-fi"

        with translation.override("en"):
            page = Page.objects.get(pk=page_id)
            assert page.title == "test, Englisch"
            assert page.url == "multi-en"

Example 17

Project: SmartElect
Source File: test_screens.py
View license
    @override_settings(MAX_REGISTRATIONS_PER_PHONE=2)
    def test_display_max_registrations_warning(self):
        PHONE_NUMBER = self.case.registration.sms.from_number
        url = reverse(self.screen_name, args=[self.case.pk])
        with override(language='en'):
            rsp = self.client.get(url)
        self.assertNotContains(rsp, "has been used for the maximum number")
        RegistrationFactory(archive_time=None, sms__from_number=PHONE_NUMBER)
        rsp = self.client.get(url)
        self.assertContains(rsp, "has been used for the maximum number")

Example 18

Project: SmartElect
Source File: base.py
View license
    @staticmethod
    def translate(message_code, context={}, language='ar', enhanced=False):
        with translation.override(language):
            if enhanced:
                text = get_message(message_code).enhanced
            else:
                text = get_message(message_code).msg
            return text.format(**context)

Example 19

Project: django-countries
Source File: __init__.py
View license
    def by_name(self, country, language='en'):
        """
        Fetch a country's ISO3166-1 two letter country code from its name.

        An optional language parameter is also available.
        Warning: This depends on the quality of the available translations.

        If no match is found, returns an empty string.
        """
        with override(language):
            for code, name in self:
                if name == country:
                    return code
        return ''

Example 20

Project: splunk-webframework
Source File: forms.py
View license
    def test_inactive_user_i18n(self):
        with self.settings(USE_I18N=True):
            with translation.override('pt-br', deactivate=True):
                # The user is inactive.
                data = {
                    'username': 'inactive',
                    'password': 'password',
                    }
                form = AuthenticationForm(None, data)
                self.assertFalse(form.is_valid())
                self.assertEqual(form.non_field_errors(),
                                 [force_text(form.error_messages['inactive'])])

Example 21

Project: splunk-webframework
Source File: forms.py
View license
    @override_settings(APPEND_SLASH=True,
            MIDDLEWARE_CLASSES=('django.middleware.common.CommonMiddleware',))
    def test_flatpage_requires_trailing_slash_with_append_slash(self):
        form = FlatpageForm(data=dict(url='/no_trailing_slash', **self.form_data))
        with translation.override('en'):
            self.assertFalse(form.is_valid())
            self.assertEqual(form.errors['url'], ["URL is missing a trailing slash."])

Example 22

Project: splunk-webframework
Source File: tests.py
View license
    def test_i18n_intcomma(self):
        test_list = (100, 1000, 10123, 10311, 1000000, 1234567.25,
                     '100', '1000', '10123', '10311', '1000000', None)
        result_list = ('100', '1.000', '10.123', '10.311', '1.000.000', '1.234.567,25',
                       '100', '1.000', '10.123', '10.311', '1.000.000', None)
        with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True):
            with translation.override('de'):
                self.humanize_tester(test_list, result_list, 'intcomma')

Example 23

Project: splunk-webframework
Source File: tests.py
View license
    def test_i18n_intword(self):
        test_list = ('100', '1000000', '1200000', '1290000',
                     '1000000000', '2000000000', '6000000000000')
        result_list = ('100', '1,0 Million', '1,2 Millionen', '1,3 Millionen',
                       '1,0 Milliarde', '2,0 Milliarden', '6,0 Billionen')
        with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True):
            with translation.override('de'):
                self.humanize_tester(test_list, result_list, 'intword')

Example 24

View license
    def _base_page_check(self, url_name, url_path):
        self.assertEqual(reverse(url_name), url_path)
        with translation.override('en'):
            self.assertEqual(reverse(url_name), url_path)
        with translation.override('ru'):
            self.assertEqual(reverse(url_name), '/ru' + url_path)

Example 25

View license
    @override_settings(SOLID_I18N_HANDLE_DEFAULT_PREFIX=True)
    def test_about_page_default_prefix_ru(self):
        with translation.override('ru'):
            response = self.client.get('/en/about/')
            self._base_page_check(response, "en", "about")
            self.assertTrue('<test>/en/about/</test>' in str(response.content))

            response = self.client.get('/ru/about/')
            self._base_page_check(response, "ru", "about")
            self.assertTrue('<test>/ru/about/</test>' in response.content.decode('utf8'))

Example 26

View license
    @override_settings(SOLID_I18N_HANDLE_DEFAULT_PREFIX=True)
    def test_home_page_default_prefix_en(self):
        """
        Check, that url with explicit default language prefix is still
        accessible.
        """
        with translation.override('en'):
            response = self.client.get('/en/')
            self._base_page_check(response, "en", "home")

Example 27

View license
    @override_settings(SOLID_I18N_HANDLE_DEFAULT_PREFIX=True)
    def test_home_page_default_prefix_ru(self):
        """
        Check, that language is got from url prefix, even this laguage is
        not equal to client preferred langauge.
        """
        with translation.override('ru'):
            response = self.client.get('/en/')
            self._base_page_check(response, "en", "home")

Example 28

View license
    @override_settings(SOLID_I18N_DEFAULT_PREFIX_REDIRECT=True)
    def test_home_page_default_prefix_en_redirect(self):
        with translation.override('en'):
            response = self.client.get('/en/')
            self.assertEqual(response.status_code, 301)
            self.assertTrue('/en/' not in response['Location'])
            response = self.client.get(response['Location'])
            self._base_page_check(response, "en", "home")

Example 29

View license
    @override_settings(SOLID_I18N_DEFAULT_PREFIX_REDIRECT=True)
    def test_home_page_default_prefix_ru_redirect(self):
        with translation.override('ru'):
            response = self.client.get('/en/')
            self.assertEqual(response.status_code, 301)
            self.assertTrue('/en/' not in response['Location'])
            response = self.client.get(response['Location'])
            self._base_page_check(response, "en", "home")

Example 30

Project: froide
Source File: foi_mail.py
View license
def create_deferred(secret_mail, mail_string, b64_encoded=False, spam=False,
                    subject=_('Unknown FoI-Mail Recipient'), body=unknown_foimail_message):
    from .models import DeferredMessage

    if mail_string is not None:
        if not b64_encoded:
            mail_string = base64.b64encode(mail_string.encode('utf-8')).decode("utf-8")
    DeferredMessage.objects.create(
        recipient=secret_mail,
        mail=mail_string,
        spam=spam
    )
    with override(settings.LANGUAGE_CODE):
        mail_managers(subject,
            body % {
                'address': secret_mail,
                'url': settings.SITE_URL + reverse('admin:foirequest_deferredmessage_changelist')
            }
        )

Example 31

Project: django-synchro
Source File: tests.py
View license
    def test_translation(self):
        """Test if texts are translated."""
        from django.utils.translation import override
        from django.utils.encoding import force_unicode
        from synchro import call_synchronize
        languages = ('en', 'pl', 'de', 'es', 'fr')
        messages = set()
        for lang in languages:
            with override(lang):
                messages.add(force_unicode(call_synchronize()))
        self.assertEqual(len(messages), len(languages), 'Some language is missing.')

Example 32

Project: django-two-factor-auth
Source File: gateway.py
View license
def validate_voice_locale(locale):
    with translation.override(locale):
        voice_locale = pgettext('twilio_locale', 'en')
        if voice_locale not in VOICE_LANGUAGES:
            raise NotImplementedError('The language "%s" is not '
                                      'supported by Twilio' % voice_locale)

Example 33

Project: django-two-factor-auth
Source File: views.py
View license
    def create_response(self, template):
        with translation.override(self.get_locale()):
            prompt_context = self.get_prompt_context()
            template_context = dict((k, v % prompt_context) for k, v in self.prompts.items())
            template_context['locale'] = self.get_twilio_locale()
            return HttpResponse(template % template_context, 'text/xml')

Example 34

Project: plan
Source File: middleware.py
View license
    def __init__(self):
        self.languages = {}  # Localised semester type -> lang
        self.values = {}     # Localised semester type -> db value

        for lang, name in settings.LANGUAGES:
            with translation.override(lang):
                for value, slug in Semester.SEMESTER_SLUG:
                    self.languages[unicode(slug)] = lang
                    self.values[unicode(slug)] = value

Example 35

Project: plan
Source File: middleware.py
View license
    def rederict_to_new_language(self, request, args, kwargs):
        # Support ?lang etc, if this is present we activate the lang and
        # resolve the current url to get its name and reverse it with a
        # localised semester type.
        with translation.override(request.META['QUERY_STRING'], deactivate=True):
            match = urlresolvers.resolve(request.path_info)
            kwargs['semester_type'] = dict(Semester.SEMESTER_SLUG)[kwargs['semester_type']]
            return shortcuts.redirect(match.url_name, *args, **kwargs)

Example 36

Project: cgstudiomap
Source File: options.py
View license
    @property
    def verbose_name_raw(self):
        """
        There are a few places where the untranslated verbose name is needed
        (so that we get the same value regardless of currently active
        locale).
        """
        with override(None):
            return force_text(self.verbose_name)

Example 37

Project: drf-extensions
Source File: tests.py
View license
    def test_resulting_dict(self):
        kwargs = {
            'params': None,
            'view_instance': None,
            'view_method': None,
            'request': None,
            'args': None,
            'kwargs': None
        }
        expected = u'br'

        with override('br'):
            self.assertEqual(LanguageKeyBit().get_data(**kwargs), expected)

Example 38

Project: hue
Source File: test_forms.py
View license
    def test_inactive_user_i18n(self):
        with self.settings(USE_I18N=True):
            with translation.override('pt-br', deactivate=True):
                # The user is inactive.
                data = {
                    'username': 'inactive',
                    'password': 'password',
                    }
                form = AuthenticationForm(None, data)
                self.assertFalse(form.is_valid())
                self.assertEqual(form.non_field_errors(),
                                 [force_text(form.error_messages['inactive'])])

Example 39

Project: hue
Source File: tests.py
View license
    def test_ordinal(self):
        test_list = ('1', '2', '3', '4', '11', '12',
                     '13', '101', '102', '103', '111',
                     'something else', None)
        result_list = ('1st', '2nd', '3rd', '4th', '11th',
                       '12th', '13th', '101st', '102nd', '103rd',
                       '111th', 'something else', None)

        with translation.override('en'):
            self.humanize_tester(test_list, result_list, 'ordinal')

Example 40

Project: hue
Source File: tests.py
View license
    def test_intcomma(self):
        test_list = (100, 1000, 10123, 10311, 1000000, 1234567.25,
                     '100', '1000', '10123', '10311', '1000000', '1234567.1234567', Decimal('1234567.1234567'),
                     None)
        result_list = ('100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.25',
                       '100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.1234567', '1,234,567.1234567',
                     None)

        with translation.override('en'):
            self.humanize_tester(test_list, result_list, 'intcomma')

Example 41

Project: hue
Source File: tests.py
View license
    def test_l10n_intcomma(self):
        test_list = (100, 1000, 10123, 10311, 1000000, 1234567.25,
                     '100', '1000', '10123', '10311', '1000000', '1234567.1234567', Decimal('1234567.1234567'),
                     None)
        result_list = ('100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.25',
                       '100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.1234567', '1,234,567.1234567',
                     None)

        with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=False):
            with translation.override('en'):
                self.humanize_tester(test_list, result_list, 'intcomma')

Example 42

Project: hue
Source File: tests.py
View license
    def test_intword(self):
        test_list = ('100', '1000000', '1200000', '1290000',
                     '1000000000', '2000000000', '6000000000000',
                     '1300000000000000', '3500000000000000000000',
                     '8100000000000000000000000000000000', None)
        result_list = ('100', '1.0 million', '1.2 million', '1.3 million',
                       '1.0 billion', '2.0 billion', '6.0 trillion',
                       '1.3 quadrillion', '3.5 sextillion',
                       '8.1 decillion', None)
        with translation.override('en'):
            self.humanize_tester(test_list, result_list, 'intword')

Example 43

Project: hue
Source File: tests.py
View license
    def test_localization(self):
        w = widgets.AdminSplitDateTime()

        with self.settings(USE_L10N=True):
            with translation.override('de-at'):
                w.is_localized = True
                self.assertHTMLEqual(
                    w.render('test', datetime(2007, 12, 1, 9, 30)),
                    '<p class="datetime">Datum: <input value="01.12.2007" type="text" class="vDateField" name="test_0" size="10" /><br />Zeit: <input value="09:30:00" type="text" class="vTimeField" name="test_1" size="8" /></p>',
                )

Example 44

Project: decode-Django
Source File: forms.py
View license
    def test_inactive_user_i18n(self):
        with self.settings(USE_I18N=True):
            with translation.override('pt-br', deactivate=True):
                # The user is inactive.
                data = {
                    'username': 'inactive',
                    'password': 'password',
                    }
                form = AuthenticationForm(None, data)
                self.assertFalse(form.is_valid())
                self.assertEqual(form.non_field_errors(),
                                 [force_text(form.error_messages['inactive'])])

Example 45

Project: decode-Django
Source File: forms.py
View license
    @override_settings(APPEND_SLASH=True,
            MIDDLEWARE_CLASSES=('django.middleware.common.CommonMiddleware',))
    def test_flatpage_requires_trailing_slash_with_append_slash(self):
        form = FlatpageForm(data=dict(url='/no_trailing_slash', **self.form_data))
        with translation.override('en'):
            self.assertFalse(form.is_valid())
            self.assertEqual(form.errors['url'], ["URL is missing a trailing slash."])

Example 46

Project: decode-Django
Source File: tests.py
View license
    def test_i18n_intcomma(self):
        test_list = (100, 1000, 10123, 10311, 1000000, 1234567.25,
                     '100', '1000', '10123', '10311', '1000000', None)
        result_list = ('100', '1.000', '10.123', '10.311', '1.000.000', '1.234.567,25',
                       '100', '1.000', '10.123', '10.311', '1.000.000', None)
        with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True):
            with translation.override('de'):
                self.humanize_tester(test_list, result_list, 'intcomma')

Example 47

Project: decode-Django
Source File: tests.py
View license
    def test_i18n_intword(self):
        test_list = ('100', '1000000', '1200000', '1290000',
                     '1000000000', '2000000000', '6000000000000')
        result_list = ('100', '1,0 Million', '1,2 Millionen', '1,3 Millionen',
                       '1,0 Milliarde', '2,0 Milliarden', '6,0 Billionen')
        with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True):
            with translation.override('de'):
                self.humanize_tester(test_list, result_list, 'intword')

Example 48

Project: cmsplugin-filer
Source File: base.py
View license
    def test_plugin_does_not_breakes_page(self):
        self.create_plugin()
        with override('en'):
            page_url = self.page.get_absolute_url()

        response = self.client.get(page_url)
        self.assertEqual(response.status_code, 200)

Example 49

Project: django-cms
Source File: settingsadmin.py
View license
    def response_post_save_change(self, request, obj):
        #
        # When the user changes his language setting, we need to do two things:
        # 1. Change the language-prefix for the sideframed admin view
        # 2. Reload the whole window so that the new language affects the
        #    toolbar, etc.
        #
        # To do this, we first redirect the sideframe to the correct new, URL,
        # but we pass a GET param 'reload_window', which instructs JS on that
        # page to strip (to avoid infinite redirection loops) that param then
        # reload the whole window again.
        #
        with override(obj.language):
            post_url = admin_reverse(
                'cms_usersettings_change',
                args=[obj.id, ],
                current_app=self.admin_site.name
            )
        return HttpResponseRedirect("{0}?reload_window".format(post_url))

Example 50

Project: django
Source File: options.py
View license
    @property
    def verbose_name_raw(self):
        """
        There are a few places where the untranslated verbose name is needed
        (so that we get the same value regardless of currently active
        locale).
        """
        with override(None):
            return force_text(self.verbose_name)