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.

150 Examples 7

Example 1

Project: django-cms Source File: settingsadmin.py
Function: response_post_save_change
    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 2

Project: django-parler Source File: test_model_attributes.py
    def test_fallback_variant(self):
        """Test de-us falls back to de"""
        x = SimpleModel()

        x.set_current_language('de')
        x.tr_title = "Hallo-de"

        x.set_current_language('en')
        x.tr_title = "Hello-en"

        x.save()

        with translation.override('de-ch'):
            x = SimpleModel.objects.get(pk=x.pk)
            self.assertEqual(x.tr_title, 'Hallo-de')

Example 3

Project: django-solid-i18n-urls Source File: test_solid_urls.py
    @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 4

Project: hue Source File: tests.py
    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 5

Project: froide Source File: foi_mail.py
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 6

Project: django-countries Source File: __init__.py
Function: by_name
    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 7

Project: django Source File: test_forms.py
    @override_settings(AUTH_PASSWORD_VALIDATORS=[
        {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'},
        {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': {
            'min_length': 12,
        }},
    ])
    def test_help_text_translation(self):
        french_help_texts = [
            'Votre mot de passe ne peut pas trop ressembler à vos autres informations personnelles.',
            'Votre mot de passe doit contenir au minimum 12 caractères.',
        ]
        form = SetPasswordForm(self.u1)
        with translation.override('fr'):
            html = form.as_p()
            for french_text in french_help_texts:
                self.assertIn(french_text, html)

Example 8

Project: Django--an-app-at-a-time Source File: options.py
Function: verbose_name_raw
    @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 9

Project: django-parler Source File: test_query_count.py
    def assertNumTranslatedQueries(self, num, qs, language_code=None):
        # Use default language if available.
        if language_code is None:
            language_code = self.conf_fallback

        # Easier to understand then a oneline lambda
        # Using str(), not unicode() to be python 3 compatible.
        def test_qs():
            for obj in qs:
                str(obj.tr_title)

        # Queryset is not set to a language, the individual models
        # will default to the currently active project language.
        with translation.override(language_code):
            self.assertNumQueries(num, test_qs)

Example 10

Project: shuup Source File: test_bootstrap_field_renderer.py
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 ""Control"" in force_text(AdminFieldRenderer(form["field1"]).render())
        assert "title=\"\"" not in force_text(AdminFieldRenderer(form["field2"]).render())

Example 11

Project: drf-extensions Source File: tests.py
    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 12

Project: django-two-factor-auth Source File: gateway.py
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 13

Project: SmartElect Source File: test_screens.py
    @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 14

Project: hue Source File: tests.py
    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 15

Project: django-shop Source File: indexes.py
Function: prepare
    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 16

Project: django Source File: test_basic.py
Function: test_user_verbose_names_translatable
    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 17

Project: django-solid-i18n-urls Source File: test_solid_urls.py
    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 18

Project: django-parler Source File: test_forms.py
    def test_form_save_clean_exclude(self):
        """
        Check that non-form fields are properly excluded.
        """
        class CleanPartialFieldForm(TranslatableModelForm):
            class Meta:
                model = CleanFieldModel
                fields = ('shared',)
                exclude = ('tr_title',)

        self.assertEqual(list(CleanPartialFieldForm.base_fields.keys()), ['shared'])

        with translation.override('fr'):
            x = CleanPartialFieldForm(data={'shared': 'TRANS'})
            x.language_code = 'nl'
            self.assertFalse(x.errors)

Example 19

Project: PyClassLessons Source File: test_forms.py
    @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 20

Project: django-parler Source File: test_model_attributes.py
    def test_any_fallback_function(self):
        x = SimpleModel()
        x.set_current_language(self.other_lang1)
        x.tr_title = "TITLE_XX"

        x.save()

        with translation.override(self.other_lang2):
            x = SimpleModel.objects.get(pk=x.pk)
            self.assertRaises(TranslationDoesNotExist, lambda: x._get_translated_model(use_fallback=True))
            self.assertIs(x.safe_translation_getter('tr_title', 'DEFAULT'), 'DEFAULT')  # No lanuage, gives default
            self.assertEqual(x.safe_translation_getter('tr_title', any_language=True), 'TITLE_XX')  # Even though there is no current language, there is a value.

            self.assertNumQueries(0, lambda: x._get_any_translated_model())   # Can fetch from cache next time.
            self.assertEqual(x._get_any_translated_model().language_code, self.other_lang1)

Example 21

Project: django-solid-i18n-urls Source File: test_solid_urls.py
    @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 22

Project: django-solid-i18n-urls Source File: test_solid_urls.py
    @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 23

Project: PyClassLessons Source File: test_forms.py
    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 24

Project: django-synchro Source File: tests.py
    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 25

Project: shuup Source File: test_addresses.py
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 26

Project: plan Source File: middleware.py
    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 27

Project: django-two-factor-auth Source File: views.py
Function: create_response
    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 28

Project: shuup Source File: test_languages.py
@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 29

Project: hue Source File: tests.py
Function: test_intcomma
    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 30

Project: PyClassLessons Source File: tests.py
    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 31

Project: hue Source File: tests.py
Function: test_intword
    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 32

Project: SmartElect Source File: base.py
Function: translate
    @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 33

Project: cmsplugin-filer Source File: base.py
    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 34

Project: PyClassLessons Source File: test_forms.py
    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 35

Project: django Source File: test_logentry.py
    @override_settings(USE_L10N=True)
    def test_logentry_change_message_localized_datetime_input(self):
        """
        Localized date/time inputs shouldn't affect changed form data detection.
        """
        post_data = {
            'site': self.site.pk, 'title': 'Changed', 'hist': 'Some content',
            'created_0': '12/03/2008', 'created_1': '11:54',
        }
        with translation.override('fr'):
            change_url = reverse('admin:admin_utils_article_change', args=[quote(self.a1.pk)])
            response = self.client.post(change_url, post_data)
            self.assertRedirects(response, reverse('admin:admin_utils_article_changelist'))
        logentry = LogEntry.objects.filter(content_type__model__iexact='article').latest('id')
        self.assertEqual(logentry.get_change_message(), 'Changed title and hist.')

Example 36

Project: splunk-webframework Source File: forms.py
Function: test_inactive_user_i18n
    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 37

Project: django Source File: test_forms.py
    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 38

Project: rapidsms Source File: app.py
Function: handle
    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 39

Project: django-fluent-blogs Source File: test_blogpage.py
    def test_blogpage_fallback_url(self):
        """
        Testing how translated entries appear on a ``BlogPage`` that has no translation except for the default/fallback.
        """
        page = BlogPage.objects.language('en').create(author=self.user, status=BlogPage.PUBLISHED, slug='blogpage')
        self.assertEqual(page.default_url, '/en/blogpage/')

        date = datetime(year=2016, month=5, day=1)
        entry = Entry.objects.language('en').create(author=self.user, slug='hello-en', publication_date=date)
        self.assertEqual(entry.default_url, '/en/blogpage/2016/05/hello-en/')

        # Simulate fetched entry in new language
        with translation.override('nl'):
            entry.set_current_language('nl')
            self.assertEqual(entry.default_url, '/nl/blogpage/2016/05/hello-en/')

            # Create new language
            entry.create_translation('nl', slug='hello-nl')
            self.assertEqual(entry.default_url, '/nl/blogpage/2016/05/hello-nl/')

Example 40

Project: django-solid-i18n-urls Source File: test_solid_urls.py
    @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 41

Project: django-parler Source File: test_model_attributes.py
    def test_fallback_language(self):
        """
        Test whether the fallback language will be returned.
        """
        x = SimpleModel()
        x.set_current_language(self.conf_fallback)
        x.tr_title = "TITLE_FALLBACK"

        x.set_current_language(self.other_lang1)
        x.tr_title = 'TITLE_XX'
        x.save()

        with translation.override(self.other_lang2):
            x = SimpleModel.objects.get(pk=x.pk)
            self.assertEqual(x.tr_title, 'TITLE_FALLBACK')

Example 42

Project: GAE-Bulk-Mailer Source File: tests.py
    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 43

Project: django-parler Source File: test_model_attributes.py
    def test_any_fallback_model(self):
        """
        Test whether a failure in the fallback language can return any saved language (if configured for it).
        """
        x = AnyLanguageModel()
        x.set_current_language(self.other_lang1)
        x.tr_title = "TITLE_XX"

        x.save()

        with translation.override(self.other_lang2):
            x = AnyLanguageModel.objects.get(pk=x.pk)
            self.assertRaises(TranslationDoesNotExist, lambda: x._get_translated_model(use_fallback=True))
            self.assertEqual(x.tr_title, 'TITLE_XX')  # Even though there is no current language, there is a value.

            self.assertNumQueries(0, lambda: x._get_any_translated_model())   # Can fetch from cache next time.
            self.assertEqual(x._get_any_translated_model().language_code, self.other_lang1)

Example 44

Project: django-solid-i18n-urls Source File: test_solid_urls.py
    @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 45

Project: django-multilingual-search Source File: test_query.py
    @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 46

Project: GAE-Bulk-Mailer Source File: tests.py
    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: PyClassLessons Source File: test_basic.py
Function: test_user_verbose_names_translatable
    @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 48

Project: PyClassLessons Source File: tests.py
Function: test_ordinal
    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 49

Project: shuup Source File: test_simple_search.py
@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 50

Project: plan Source File: middleware.py
    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
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3