Python django.utils.translation.override() Examples

The following are 30 code examples of django.utils.translation.override(). 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: base.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def translate_url(url, lang_code):
    """
    Given a URL (absolute or relative), try to get its translated version in
    the `lang_code` language (either by i18n_patterns or by translated regex).
    Return the original URL if no translated version is found.
    """
    parsed = urlsplit(url)
    try:
        match = resolve(parsed.path)
    except Resolver404:
        pass
    else:
        to_be_reversed = "%s:%s" % (match.namespace, match.url_name) if match.namespace else match.url_name
        with override(lang_code):
            try:
                url = reverse(to_be_reversed, args=match.args, kwargs=match.kwargs)
            except NoReverseMatch:
                pass
            else:
                url = urlunsplit((parsed.scheme, parsed.netloc, url, parsed.query, parsed.fragment))
    return url 
Example #2
Source File: base.py    From adhocracy4 with GNU Affero General Public License v3.0 6 votes vote down vote up
def render(self, template_name, context):
        languages = self.get_languages(context['receiver'])
        template = select_template([
            '{}.{}.email'.format(template_name, lang)
            for lang in languages
        ])

        # Get the actually chosen language from the template name
        language = template.template.name.split('.', 2)[-2]

        with translation.override(language):
            parts = []
            for part_type in ('subject', 'txt', 'html'):
                context['part_type'] = part_type
                parts.append(template.render(context))
                context.pop('part_type')

        return tuple(parts) 
Example #3
Source File: views.py    From anytask with MIT License 6 votes vote down vote up
def test_registration_view_failure(self):
        """
        A ``POST`` to the ``register`` view with invalid data does not
        create a user, and displays appropriate error messages.

        """
        # with translation.override('en'):
        response = self.client.post(reverse('registration_register'),
                                    data={'username': 'bob',
                                          'email': 'bobe@example.com',
                                          'password1': 'foo',
                                          'password2': 'bar'})
        self.assertEqual(response.status_code, 200)
        self.failIf(response.context['form'].is_valid())
        self.assertFormError(response, 'form', field=None,
                             errors=u"Два поля с паролями не совпадают.")
        self.assertEqual(len(mail.outbox), 0) 
Example #4
Source File: test_models.py    From django-knocker with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_model_attributes(self):
        posts = []
        posts.append(MultiLanguagePost.objects.create(
            title='first post',
            slug='first-post',
        ))
        posts.append(MultiLanguagePost.objects.create(
            title='second post',
            slug='second-post',
        ))

        for language in [get_language()]:
            with override(language):
                for post in posts:
                    knock_create = post.as_knock('post_save', True)
                    self.assertEqual(knock_create['title'],
                                     'new {0}'.format(post._meta.verbose_name))
                    self.assertEqual(knock_create['message'], post.title)
                    self.assertEqual(knock_create['language'], language) 
Example #5
Source File: signals.py    From django-knocker with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def notify_items(signal_type, **kwargs):
    """
    Signal endpoint that actually sends knocks whenever an instance is created / saved
    """
    instance = kwargs.get('instance')
    created = kwargs.get('created', False)
    if hasattr(instance, 'send_knock') and active_knocks(instance):
        try:
            # This is a stupid generic interface for multilanguage models (hvad / parler)
            if hasattr(instance, 'get_available_languages'):
                langs = instance.get_available_languages()
            else:
                langs = [get_language()]
            for lang in langs:
                with override(lang):
                    instance.send_knock(signal_type, created)
            return True
        except AttributeError:  # pragma: no cover
            pass
    return False 
Example #6
Source File: test_event_post.py    From linkedevents with MIT License 6 votes vote down vote up
def test_description_and_short_description_required_in_name_languages(api_client, minimal_event_dict, user):
    api_client.force_authenticate(user)

    minimal_event_dict['name'] = {'fi': 'nimi', 'sv': 'namn'}
    minimal_event_dict['short_description'] = {'fi': 'lyhyt kuvaus'}
    minimal_event_dict['description'] = {'sv': 'description in swedish'}

    with translation.override('en'):
        response = api_client.post(reverse('event-list'), minimal_event_dict, format='json')

    # there should be only one error
    assert len(response.data['short_description']) == 1
    assert len(response.data['description']) == 1

    assert (force_text(response.data['short_description']['sv']) ==
            'This field must be specified before an event is published.')
    assert (force_text(response.data['description']['fi']) ==
            'This field must be specified before an event is published.') 
Example #7
Source File: test_cms_wizards_course_run.py    From richie with MIT License 6 votes vote down vote up
def test_cms_wizards_course_run_language_active_not_in_all_languages(self, *_):
        """
        If the ALL_LANGUAGES setting does not include the full active language, it should match
        on the simple language prefix.
        """
        course = CourseFactory(page_title={"fr-ca": "my title"})

        # Submit a valid form
        user = UserFactory(is_staff=True, is_superuser=True)
        form = CourseRunWizardForm(
            data={"title": "My title"},
            wizard_language="en",
            wizard_user=user,
            wizard_page=course.extended_object,
        )

        self.assertTrue(form.is_valid())
        with translation.override("fr-ca"):
            page = form.save()

        # The language field should have been set to the active language
        self.assertEqual(page.courserun.languages, ["fr"]) 
Example #8
Source File: views.py    From anytask with MIT License 6 votes vote down vote up
def test_registration_view_failure(self):
        """
        A ``POST`` to the ``register`` view with invalid data does not
        create a user, and displays appropriate error messages.

        """
        # with translation.override('en'):
        response = self.client.post(reverse('registration_register'),
                                    data={'username': 'bob',
                                          'email': 'bobe@example.com',
                                          'password1': 'foo',
                                          'password2': 'bar'})
        self.assertEqual(response.status_code, 200)
        self.failIf(response.context['form'].is_valid())
        self.assertFormError(response, 'form', field=None,
                             errors=u"Два поля с паролями не совпадают.")
        self.assertEqual(len(mail.outbox), 0) 
Example #9
Source File: test_rest.py    From edx-proctoring with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_get_attempt_i18n(self):
        attempt = {
            'id': 1,
            'external_id': 'abcd',
            'proctored_exam': self.backend_exam,
            'user': 1,
            'instructions': []
        }
        responses.add(
            responses.GET,
            url=self.provider.exam_attempt_url.format(
                exam_id=self.backend_exam['external_id'], attempt_id=attempt['external_id']),
            json=attempt
        )
        with translation.override('es'):
            external_attempt = self.provider.get_attempt(attempt)
        self.assertEqual(external_attempt, attempt)
        self.assertEqual(responses.calls[-1].request.headers['Accept-Language'], 'es;en-us') 
Example #10
Source File: base.py    From bioforum with MIT License 6 votes vote down vote up
def translate_url(url, lang_code):
    """
    Given a URL (absolute or relative), try to get its translated version in
    the `lang_code` language (either by i18n_patterns or by translated regex).
    Return the original URL if no translated version is found.
    """
    parsed = urlsplit(url)
    try:
        match = resolve(parsed.path)
    except Resolver404:
        pass
    else:
        to_be_reversed = "%s:%s" % (match.namespace, match.url_name) if match.namespace else match.url_name
        with override(lang_code):
            try:
                url = reverse(to_be_reversed, args=match.args, kwargs=match.kwargs)
            except NoReverseMatch:
                pass
            else:
                url = urlunsplit((parsed.scheme, parsed.netloc, url, parsed.query, parsed.fragment))
    return url 
Example #11
Source File: test_email_utils.py    From karrot-backend with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_date_filter_uses_timezone(self):
        # 11pm on Sunday UTC
        datetime = timezone.now().replace(
            tzinfo=pytz.utc,
            year=2018,
            month=3,
            day=11,
            hour=23,
            minute=0,
            second=0,
            microsecond=0,
        )
        with timezone.override(pytz.timezone('Europe/Berlin')), translation.override('en'):
            # ... is Monday in Berlin
            val = date_filter(datetime)
            self.assertIn('Monday', val) 
Example #12
Source File: base.py    From python with Apache License 2.0 6 votes vote down vote up
def translate_url(url, lang_code):
    """
    Given a URL (absolute or relative), try to get its translated version in
    the `lang_code` language (either by i18n_patterns or by translated regex).
    Return the original URL if no translated version is found.
    """
    parsed = urlsplit(url)
    try:
        match = resolve(parsed.path)
    except Resolver404:
        pass
    else:
        to_be_reversed = "%s:%s" % (match.namespace, match.url_name) if match.namespace else match.url_name
        with override(lang_code):
            try:
                url = reverse(to_be_reversed, args=match.args, kwargs=match.kwargs)
            except NoReverseMatch:
                pass
            else:
                url = urlunsplit((parsed.scheme, parsed.netloc, url, parsed.query, parsed.fragment))
    return url 
Example #13
Source File: tasks.py    From karrot-backend with GNU Affero General Public License v3.0 6 votes vote down vote up
def notify_message_push_subscribers_with_language(message, subscriptions, language):
    conversation = message.conversation

    if not translation.check_for_language(language):
        language = 'en'

    with translation.override(language):
        message_title = get_message_title(message, language)

    if message.is_thread_reply():
        click_action = frontend_urls.thread_url(message.thread)
    else:
        click_action = frontend_urls.conversation_url(conversation, message.author)

    notify_subscribers_by_device(
        subscriptions,
        click_action=click_action,
        fcm_options={
            'message_title': message_title,
            'message_body': Truncator(message.content).chars(num=1000),
            # this causes each notification for a given conversation to replace previous notifications
            # fancier would be to make the new notifications show a summary not just the latest message
            'tag': 'conversation:{}'.format(conversation.id),
        }
    ) 
Example #14
Source File: quote.py    From Spirit with MIT License 6 votes vote down vote up
def quotify(comment, username):
    """
    Converts 'Foo\nbar' to:
    > @username said:
    > Foo
    > bar
    \n\n
    """
    with translation.override(settings.LANGUAGE_CODE):
        header = _("@%(username)s said:") % {'username': username}

    comment = _strip_polls(comment)
    lines = comment.splitlines()
    quote = "\n> ".join(lines)
    quote = "> %(header)s\n> %(quote)s\n\n" % {'header': header, 'quote': quote}
    return quote 
Example #15
Source File: emails.py    From karrot-backend with GNU Affero General Public License v3.0 6 votes vote down vote up
def prepare_application_message_notification(user, messages):
    application = target_from_messages(messages)
    with translation.override(language_for_user(user)):
        reply_to_name = application.user.display_name
        if application.user == user:
            conversation_name = _('New message in your application to %(group_name)s') % {
                'group_name': application.group.name
            }
        else:
            conversation_name = _('New message in application of %(user_name)s to %(group_name)s') % {
                'user_name': application.user.display_name,
                'group_name': application.group.name,
            }
        return prepare_message_notification(
            user,
            messages,
            reply_to_name=reply_to_name,
            group=application.group,
            conversation_name=conversation_name,
            conversation_url=application_url(application),
            stats_category='application_message'
        ) 
Example #16
Source File: account.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def dispatch(self, request, *args, **kwargs):
        response = super().dispatch(request, *args, **kwargs)

        messages.success(self.request, _('You have been successfully logged out.'))
        # By default, logging out will generate a fresh sessionid cookie. We want to use the
        # absence of sessionid as an indication that front-end pages are being viewed by a
        # non-logged-in user and are therefore cacheable, so we forcibly delete the cookie here.
        response.delete_cookie(
            settings.SESSION_COOKIE_NAME,
            domain=settings.SESSION_COOKIE_DOMAIN,
            path=settings.SESSION_COOKIE_PATH
        )

        # HACK: pretend that the session hasn't been modified, so that SessionMiddleware
        # won't override the above and write a new cookie.
        self.request.session.modified = False

        return response 
Example #17
Source File: account.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def language_preferences(request):
    if request.method == 'POST':
        form = PreferredLanguageForm(request.POST, instance=UserProfile.get_for_user(request.user))

        if form.is_valid():
            user_profile = form.save()
            # This will set the language only for this request/thread
            # (so that the 'success' messages is in the right language)
            with override(user_profile.get_preferred_language()):
                messages.success(request, _("Your preferences have been updated."))
            return redirect('wagtailadmin_account')
    else:
        form = PreferredLanguageForm(instance=UserProfile.get_for_user(request.user))

    return TemplateResponse(request, 'wagtailadmin/account/language_preferences.html', {
        'form': form,
    }) 
Example #18
Source File: streams.py    From zulip with Apache License 2.0 6 votes vote down vote up
def you_were_just_subscribed_message(acting_user: UserProfile,
                                     recipient_user: UserProfile,
                                     stream_names: Set[str]) -> str:
    subscriptions = sorted(list(stream_names))
    if len(subscriptions) == 1:
        with override_language(recipient_user.default_language):
            return _("{user_full_name} subscribed you to the stream {stream_name}.").format(
                user_full_name=f"@**{acting_user.full_name}**",
                stream_name=f"#**{subscriptions[0]}**",
            )

    with override_language(recipient_user.default_language):
        message = _("{user_full_name} subscribed you to the following streams:").format(
            user_full_name=f"@**{acting_user.full_name}**",
        )
    message += "\n\n"
    for stream_name in subscriptions:
        message += f"* #**{stream_name}**\n"
    return message 
Example #19
Source File: countrier.py    From clist with Apache License 2.0 6 votes vote down vote up
def __init__(self):
        self.countries_name = {name.lower(): code for code, name in countries}
        with override('ru'):
            self.countries_name.update({name.lower(): code for code, name in countries})
        self.countries_name.update({code.lower(): code for code, name in countries})
        self.countries_name.update({countries.alpha3(code).lower(): code for code, name in countries})

        d = defaultdict(list)
        for code, name in countries:
            k = name[:3].lower().strip()
            if k in self.countries_name or len(k) < 3:
                continue
            d[k].append(code)
        for k, v in d.items():
            if len(v) == 1:
                self.countries_name[k] = v[0]

        self.missed_countries = defaultdict(int)
        self.logger = getLogger('ranking.parse.countrier') 
Example #20
Source File: test_calendar.py    From xblock-google-drive with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_calendar_template_content(self, override, activate_lang, expected_lang):
        """ Test content of GoogleCalendarBlock's rendered views """
        # pylint: disable=no-value-for-parameter
        if override:
            with override_language(activate_lang):
                _block, student_fragment, studio_fragment = self._render_calendar_block()
        else:
            _block, student_fragment, studio_fragment = self._render_calendar_block()

        src_url = 'https://www.google.com/calendar/embed?mode=Month&src={id}&showCalendars=0&hl={lang}'.format(
            id=DEFAULT_CALENDAR_ID,
            lang=expected_lang,
        )

        assert_in('<div class="google-calendar-xblock-wrapper">', student_fragment.content)
        assert_in(escape(src_url), student_fragment.content)
        assert_in('Google Calendar', student_fragment.content)

        assert_in(STUDIO_EDIT_WRAPPER, studio_fragment.content)
        assert_in(VALIDATION_WRAPPER, studio_fragment.content)
        assert_in(USER_INPUTS_WRAPPER, studio_fragment.content)
        assert_in(BUTTONS_WRAPPER, studio_fragment.content) 
Example #21
Source File: send.py    From byro with Apache License 2.0 6 votes vote down vote up
def mail(
    email: str,
    subject: str,
    template: Union[str, LazyI18nString],
    context: Dict[str, Any] = None,
    locale: str = None,
    headers: dict = None,
):
    headers = headers or {}
    c = Configuration.get_solo()
    locale = locale or c.language

    with override(locale):
        body = str(template)
        if context:
            body = body.format_map(TolerantDict(context))

        sender = Configuration.get_solo().mail_from
        subject = str(subject)
        body_plain = body
        return mail_send_task.apply_async(
            args=([email], subject, body_plain, sender, headers)
        ) 
Example #22
Source File: autoslug_field.py    From django-localized-fields with MIT License 5 votes vote down vote up
def _get_populate_from_value(
        instance, field_name: Union[str, Tuple[str]], language: str
    ):
        """Gets the value to create a slug from in the specified language.

        Arguments:
            instance:
                The model that the field resides on.

            field_name:
                The name of the field to generate a slug for.

            language:
                The language to generate the slug for.

        Returns:
            The text to generate a slug for.
        """

        if callable(field_name):
            return field_name(instance)

        def get_field_value(name):
            value = resolve_object_property(instance, name)
            with translation.override(language):
                return str(value)

        if isinstance(field_name, tuple) or isinstance(field_name, list):
            value = "-".join(
                [
                    value
                    for value in [get_field_value(name) for name in field_name]
                    if value
                ]
            )
            return value

        return get_field_value(field_name) 
Example #23
Source File: test_value.py    From django-localized-fields with MIT License 5 votes vote down vote up
def test_translate_custom_language():
        """Tests whether the :see:LocalizedValue class's translate() ignores
        the active language when one is specified explicitely."""

        localized_value = LocalizedValue(
            {settings.LANGUAGE_CODE: settings.LANGUAGE_CODE, "ro": "ro"}
        )

        with translation.override("en"):
            assert localized_value.translate("ro") == "ro" 
Example #24
Source File: i18n.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def render(self, context):
        with translation.override(self.language.resolve(context)):
            output = self.nodelist.render(context)
        return output 
Example #25
Source File: test_integer_field.py    From django-localized-fields with MIT License 5 votes vote down vote up
def test_translate_primary_fallback(self):
        """Tests whether casting the value to an integer results in the value
        begin returned in the active language and falls back to the primary
        language if there is no value in that language."""

        obj = self.TestModel()
        obj.score.set(settings.LANGUAGE_CODE, 25)

        secondary_language = settings.LANGUAGES[-1][0]
        assert obj.score.get(secondary_language) is None

        with translation.override(secondary_language):
            assert obj.score.translate() == 25
            assert int(obj.score) == 25 
Example #26
Source File: test_integer_field.py    From django-localized-fields with MIT License 5 votes vote down vote up
def test_translate(self):
        """Tests whether casting the value to an integer results in the value
        being returned in the currently active language as an integer."""

        obj = self.TestModel()
        for index, (lang_code, _) in enumerate(settings.LANGUAGES):
            obj.score.set(lang_code, index + 1)
        obj.save()

        obj.refresh_from_db()
        for index, (lang_code, _) in enumerate(settings.LANGUAGES):
            with translation.override(lang_code):
                assert int(obj.score) == index + 1
                assert obj.score.translate() == index + 1 
Example #27
Source File: test_claims.py    From django-oidc-provider with MIT License 5 votes vote down vote up
def test_locale(self):
        with override_language('fr'):
            self.assertEqual(text_type(StandardScopeClaims.info_profile[0]), 'Profil de base') 
Example #28
Source File: options.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
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 #29
Source File: utils.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def construct_change_message(form, formsets, add):
    """
    Construct a JSON structure describing changes from a changed object.
    Translations are deactivated so that strings are stored untranslated.
    Translation happens later on LogEntry access.
    """
    change_message = []
    if add:
        change_message.append({'added': {}})
    elif form.changed_data:
        change_message.append({'changed': {'fields': form.changed_data}})

    if formsets:
        with translation_override(None):
            for formset in formsets:
                for added_object in formset.new_objects:
                    change_message.append({
                        'added': {
                            'name': str(added_object._meta.verbose_name),
                            'object': str(added_object),
                        }
                    })
                for changed_object, changed_fields in formset.changed_objects:
                    change_message.append({
                        'changed': {
                            'name': str(changed_object._meta.verbose_name),
                            'object': str(changed_object),
                            'fields': changed_fields,
                        }
                    })
                for deleted_object in formset.deleted_objects:
                    change_message.append({
                        'deleted': {
                            'name': str(deleted_object._meta.verbose_name),
                            'object': str(deleted_object),
                        }
                    })
    return change_message 
Example #30
Source File: options.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def verbose_name_raw(self):
        """Return the untranslated verbose name."""
        with override(None):
            return str(self.verbose_name)