Python django.utils.translation 模块,override() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.utils.translation.override()

项目:byro    作者:byro    | 项目源码 | 文件源码
def to_mail(self, email, locale=None, context=None, skip_queue=False):
        with override(locale):
            context = context or dict()
            try:
                subject = str(self.subject).format(**context)
                text = str(self.text).format(**context)
            except KeyError as e:
                raise SendMailException(f'Experienced KeyError when rendering Text: {str(e)}')

            mail = EMail(
                to=email,
                reply_to=self.reply_to,
                bcc=self.bcc,
                subject=subject,
                text=text,
            )
            if skip_queue:
                mail.send()
            else:
                mail.save()
        return mail
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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
项目:django-modeltrans    作者:zostera    | 项目源码 | 文件源码
def test_limited_admin(self):
        urls = [
            reverse('admin:app_category_changelist'),
            reverse('admin:app_category_change', args=(self.wikipedia.pk, ))
        ]
        for url in urls:
            response = self.client.get(url)
            self.assertEquals(response.status_code, 200)

            with override('nl'):
                response = self.client.get(url)
                self.assertEquals(response.status_code, 200)

            with override('de'):
                response = self.client.get(url)
                self.assertEquals(response.status_code, 200)
项目:pretalx    作者:pretalx    | 项目源码 | 文件源码
def get(self, request, *args, **kwargs):
        url = request.GET.get('next', request.META.get('HTTP_REFERER', '/'))
        url = url if is_safe_url(url, host=request.get_host()) else '/'
        resp = HttpResponseRedirect(url)

        locale = request.GET.get('locale')
        if locale in [lc for lc, ll in settings.LANGUAGES]:
            if request.user.is_authenticated:
                request.user.locale = locale
                request.user.save()

            max_age = 10 * 365 * 24 * 60 * 60
            resp.set_cookie(settings.LANGUAGE_COOKIE_NAME, locale, max_age=max_age,
                            expires=(datetime.utcnow() + timedelta(seconds=max_age)).strftime(
                                '%a, %d-%b-%Y %H:%M:%S GMT'),
                            domain=settings.SESSION_COOKIE_DOMAIN)
            with override(locale):
                messages.success(request, phrases.cfp.locale_change_success)

        return resp
项目:pretalx    作者:pretalx    | 项目源码 | 文件源码
def to_mail(self, user, event, locale=None, context=None, skip_queue=False):
        with override(locale):
            context = context or dict()
            try:
                subject = str(self.subject).format(**context)
                text = str(self.text).format(**context)
            except KeyError as e:
                raise SendMailException(f'Experienced KeyError when rendering Text: {str(e)}')

            mail = QueuedMail(
                event=self.event,
                to=user.email,
                reply_to=self.reply_to or event.email,
                bcc=self.bcc,
                subject=subject,
                text=text,
            )
            if skip_queue:
                mail.send()
            else:
                mail.save()
        return mail
项目:wanblog    作者:wanzifa    | 项目源码 | 文件源码
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
项目:tabmaster    作者:NicolasMinghetti    | 项目源码 | 文件源码
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
项目:django-knocker    作者:nephila    | 项目源码 | 文件源码
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(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)
项目:django-knocker    作者:nephila    | 项目源码 | 文件源码
def notify_items(**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(created)
            return True
        except AttributeError:  # pragma: no cover
            pass
    return False
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
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
项目:DjangoCMS    作者:farhan711    | 项目源码 | 文件源码
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))
项目:logo-gen    作者:jellene4eva    | 项目源码 | 文件源码
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
项目:gmail_scanner    作者:brandonhub    | 项目源码 | 文件源码
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
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
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
项目:a4-meinberlin    作者:liqd    | 项目源码 | 文件源码
def log_module_component_changes(sender, module, component, user, **kwargs):
    with translation.override(settings.DEFAULT_LANGUAGE):
        message = _(
            '"{username}" modified the component "{component_label}"'
            ' in the module "{module_name}"'
            ' of the project "{project_name}".').format(
                username=user.username,
                project_name=module.project.name,
                module_name=module.name,
                component_label=component.label)

    models.LogEntry.objects.create(
        message=message,
        action=models.MODULE_COMPONENT_UPDATED,
        actor=user,
        component_identifier=component.identifier,
        project=module.project,
        module=module,
    )
项目:a4-meinberlin    作者:liqd    | 项目源码 | 文件源码
def log_project_component_changes(sender, project, component, user, **kwargs):
    with translation.override(settings.DEFAULT_LANGUAGE):
        message = _(
            '"{username}" modified the component "{component_label}"'
            ' of the project "{project_name}".').format(
                username=user.username,
                project_name=project.name,
                component_label=component.label)

    models.LogEntry.objects.create(
        message=message,
        action=models.PROJECT_COMPONENT_UPDATED,
        actor=user,
        component_identifier=component.identifier,
        project=project,
        module=None
    )
项目:adhocracy4    作者:liqd    | 项目源码 | 文件源码
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)
项目:django-next-train    作者:bitpixdigital    | 项目源码 | 文件源码
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
项目:money-to-prisoners-send-money    作者:ministryofjustice    | 项目源码 | 文件源码
def test_plain_views_are_cacheable(self, mocked_api_session):
        mocked_api_session().get().json.return_value = {
            'count': 1,
            'results': [{'nomis_id': 'AAA', 'short_name': 'Prison', 'name': 'HMP Prison'}],
        }
        view_names = [
            'send_money:help', 'send_money:prison_list',
            'send_money:help_bank_transfer', 'send_money:help_delays', 'send_money:help_transfered',
            'terms', 'cookies',
            'js-i18n',
            'sitemap_xml',
        ]
        for view_name in view_names:
            response = self.client.get(reverse(view_name))
            self.assertGreaterEqual(get_max_age(response), 3600)
            with override_lang('cy'):
                response = self.client.get(reverse(view_name))
                self.assertGreaterEqual(get_max_age(response), 3600)
项目:DjangoZeroToHero    作者:RayParra    | 项目源码 | 文件源码
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
项目:Roboism    作者:markroxor    | 项目源码 | 文件源码
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
项目:django-localized-fields    作者:SectorLabs    | 项目源码 | 文件源码
def test_str_fallback_custom_fallback():
        """Tests whether the :see:LocalizedValue class's
        __str__'s fallback functionality properly respects
        the LOCALIZED_FIELDS_FALLBACKS setting."""

        settings.LOCALIZED_FIELDS_FALLBACKS = {
            'nl': ['ro']
        }

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

        with translation.override('nl'):
            assert str(localized_value) == 'ro'
项目:byro    作者:byro    | 项目源码 | 文件源码
def mail(email: str, subject: str, template: Union[str, LazyI18nString],
         context: Dict[str, Any]=None, locale: str=None,
         headers: dict=None):
    headers = headers or {}

    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))
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def handle(self, request, data):
        response = shortcuts.redirect(request.build_absolute_uri())
        # Language
        lang_code = data['language']
        if lang_code and translation.check_for_language(lang_code):
            if hasattr(request, 'session'):
                request.session['django_language'] = lang_code
            response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code,
                                expires=_one_year())

        # Timezone
        request.session['django_timezone'] = pytz.timezone(
            data['timezone']).zone
        response.set_cookie('django_timezone', data['timezone'],
                            expires=_one_year())

        request.session['horizon_pagesize'] = data['pagesize']
        response.set_cookie('horizon_pagesize', data['pagesize'],
                            expires=_one_year())

        request.session['instance_log_length'] = data['instance_log_length']
        response.set_cookie('instance_log_length',
                            data['instance_log_length'], expires=_one_year())

        with translation.override(lang_code):
            messages.success(request,
                             encoding.force_text(_("Settings saved.")))

        return response
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def add_logout_reason(request, response, reason):
    # Store the translated string in the cookie
    lang = translation.get_language_from_request(request)
    with translation.override(lang):
        reason = six.text_type(reason)
        if six.PY2:
            reason = reason.encode('utf-8')
        response.set_cookie('logout_reason', reason, max_age=10)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def render(self, context):
        with translation.override(self.language.resolve(context)):
            output = self.nodelist.render(context)
        return output
项目:django-modeltrans    作者:zostera    | 项目源码 | 文件源码
def test_model_fields(self):
        falcon = Blog.objects.get(title='Falcon')
        self.assertEquals(falcon.i18n['title_nl'], 'Valk')
        self.assertEquals(falcon.i18n['title_de'], 'Falk')
        self.assertIn('body_nl', falcon.i18n)

        with override('nl'):
            self.assertEquals(falcon.title_i18n, 'Valk')

        with override('de'):
            self.assertEquals(falcon.title_i18n, 'Falk')
项目:django-modeltrans    作者:zostera    | 项目源码 | 文件源码
def test_data_available(self):
        def get_titles():
            return {m.title for m in Blog.objects.all()}

        self.assertEquals(get_titles(), {'Falcon', 'Dolphin', 'Vulture'})

        with override('de'):
            self.assertEquals(get_titles(), {'Falk', 'Delfin', ''})
项目:django-modeltrans    作者:zostera    | 项目源码 | 文件源码
def test_get_active_language(self):
        m = Blog(title='Falcon', i18n={
            'title_nl': 'Valk',
            'title_de': 'Falk'
        })

        with override('nl'):
            # value for the active language
            self.assertEquals(m.title_i18n, 'Valk')

            self.assertEquals(m.title_en, 'Falcon')
            self.assertEquals(m.title_de, 'Falk')

        with override('de'):
            self.assertEquals(m.title_i18n, 'Falk')
项目:django-modeltrans    作者:zostera    | 项目源码 | 文件源码
def test_get_has_no_translation(self):
        m = Blog(title='Falcon', i18n={
            'title_nl': 'Valk',
            'title_de': 'Falk'
        })

        # Fallback to base langauge
        with override('fr'):
            self.assertEquals(m.title_i18n, 'Falcon')

        # other translations are still there.
        self.assertEquals(m.title_nl, 'Valk')
        self.assertEquals(m.title_de, 'Falk')
项目:django-modeltrans    作者:zostera    | 项目源码 | 文件源码
def test_set_translatable_field_active_language(self):
        m = Blog.objects.create(title='Toad')

        with override('nl'):
            m.title_i18n = 'Pad'
        m.save()

        self.assertEquals(Blog.objects.get(title='Toad').title_nl, 'Pad')
项目:django-modeltrans    作者:zostera    | 项目源码 | 文件源码
def test_fallback_getting_TextField(self):
        DESCRIPTION = 'Story about Falcon'
        m = TextModel(title='Falcon', description_en=DESCRIPTION)
        with override('fr'):
            self.assertEquals(m.description_i18n, DESCRIPTION)

        m = NullableTextModel.objects.create(description=DESCRIPTION, description_fr='')
        with override('fr'):
            self.assertEquals(m.description_i18n, DESCRIPTION)
项目:django-modeltrans    作者:zostera    | 项目源码 | 文件源码
def test_creationg_prevents_double_definition(self):
        expected_message = (
            'Attempted override of "title" with "title_en". Only '
            'one of the two is allowed.'
        )
        with self.assertRaisesMessage(ValueError, expected_message):
            Blog.objects.create(
                title='Foo',
                title_en='Bar'
            )
项目:django-modeltrans    作者:zostera    | 项目源码 | 文件源码
def test_fallback_chain(self):
        '''
        Testing the fallback chain setting for model
        '''
        b = Blog.objects.create(title='Buzzard', i18n={
            'title_fy': 'Mûzefalk',
            'title_nl': 'Buizerd',
            'title_fr': 'Buse'
        })

        with override('nl'):
            self.assertEquals(b.title_i18n, 'Buizerd')
        with override('fr'):
            self.assertEquals(b.title_i18n, 'Buse')
        with override('fy'):
            self.assertEquals(b.title_i18n, 'Mûzefalk')

        b = Blog.objects.create(title='Buzzard', i18n={
            'title_nl': 'Buizerd',
            'title_fr': 'Buse'
        })
        with override('fy'):
            self.assertEquals(b.title_i18n, 'Buizerd')

        b = Blog.objects.create(title='Buzzard', i18n={
            'title_fr': 'Buse'
        })
        with override('fy'):
            self.assertEquals(b.title_i18n, 'Buzzard')
        with override('fr'):
            self.assertEquals(b.title_i18n, 'Buse')
项目:django-modeltrans    作者:zostera    | 项目源码 | 文件源码
def test_filter_i18n(self):
        Blog.objects.create(title='Cod')

        with override('nl'):
            # should fallback to english
            qs = Blog.objects.filter(title_i18n='Cod')
            self.assertEquals({m.title for m in qs}, {'Cod'})

            # should not fallback
            qs = Blog.objects.filter(title_nl='Cod')
            self.assertEquals({m.title for m in qs}, set())
项目:django-modeltrans    作者:zostera    | 项目源码 | 文件源码
def test_filter_Q_object(self):
        b = Blog.objects.get(Q(title_nl__contains='al'))
        self.assertEquals(b.title, 'Falcon')

        qs = Blog.objects.filter(Q(title_nl__contains='al') | Q(title_en__contains='Fro'))
        self.assertEquals({m.title for m in qs}, {'Falcon', 'Frog'})

        b = Blog.objects.get(Q(title_nl__contains='al'), Q(title_en__contains='al'))
        self.assertEquals(b.title, 'Falcon')

        with override('nl'):
            b = Blog.objects.get(Q(title_i18n='Kikker'))
            self.assertEquals(b.title, 'Frog')
项目:django-modeltrans    作者:zostera    | 项目源码 | 文件源码
def test_order_by_i18n(self):
        Blog.objects.create(title='H')
        with override('nl'):
            qs = Blog.objects.all().order_by('title_i18n')

            self.assertEquals(key(qs, 'title_i18n'), 'A B C D H X Y Z'.split())
项目:django-modeltrans    作者:zostera    | 项目源码 | 文件源码
def test_annotate_upper(self):
        with override('nl'):
            qs = Blog.objects.annotate(e=models.functions.Upper('title_i18n'))

            self.assertEquals(
                list(qs.values_list('e', flat=True)),
                ['VALK', 'VULTURE', 'BAT', 'DOLFIN', 'ZEBRA']
            )
项目:django-modeltrans    作者:zostera    | 项目源码 | 文件源码
def test_annotate_length(self):
        with override('nl'):
            qs = Blog.objects.annotate(l=models.functions.Length('title_i18n'))

            self.assertEquals(
                list(qs.values_list('l', flat=True)),
                list(map(len, ['VALK', 'VULTURE', 'BAT', 'DOLFIN', 'ZEBRA']))
            )
项目:django-modeltrans    作者:zostera    | 项目源码 | 文件源码
def test_order_by_lower(self):
        from django.db.models.functions import Lower

        c = Category.objects.create(name='test')
        Blog.objects.create(title='A', title_nl='c', category=c)
        Blog.objects.create(title='a', title_nl='b', category=c)

        filtered = Blog.objects.filter(category=c)

        # order by title should result in aA because it is case sensitive.
        qs = filtered.order_by('title', 'title_nl')
        self.assertEquals(key(qs, 'title'), ['a', 'A'])

        # order by Lower('title') should result in Aa because lower('A') == lower('A')
        # so the title_nl field should determine the sorting
        qs = filtered.order_by(Lower('title'), 'title_nl')
        self.assertEquals(key(qs, 'title'), ['a', 'A'])

        # applying lower to title_nl should not matter since it is not the same letter
        qs = filtered.order_by(Lower('title_nl'))
        self.assertEquals(key(qs, 'title'), ['a', 'A'])

        # should be the same as previous
        with override('nl'):
            qs = filtered.order_by(Lower('title_i18n'))
            self.assertEquals(key(qs, 'title'), ['a', 'A'])
项目:django-modeltrans    作者:zostera    | 项目源码 | 文件源码
def test_order_by_fallback_chain(self):

        class TestObj(models.Model):
            title = models.CharField(max_length=100)
            i18n = TranslationField(fields=('title', ))

            class Meta:
                app_label = 'django-modeltrans_tests'

        translate_model(TestObj)

        with CreateTestModel(TestObj):
            TestObj.objects.bulk_create([
                TestObj(title='Falcon', title_nl='Valk'),
                TestObj(title='Frog', title_nl='Kikker', title_fr='Grenouilles', title_fy='Frosk'),
                TestObj(title='Fox', title_nl='Vos', title_fy='Foks'),
                TestObj(title='Gecko'),
                TestObj(title='Gerbil'),
                TestObj(title='Vulture', title_nl='Gier', title_fr='Vautour')
            ])

            # should use the 'default' fallback chain
            with override('nl'):
                qs = TestObj.objects.all().order_by('title_i18n')
                self.assertEquals(key(qs, 'title_i18n'), ['Gecko', 'Gerbil', 'Gier', 'Kikker', 'Valk', 'Vos'])

            # should use the 'fy' fallback chain
            with override('fy'):
                expected = ['Foks', 'Frosk', 'Gecko', 'Gerbil', 'Gier', 'Valk']
                qs = TestObj.objects.all().order_by('title_i18n')
                self.assertEquals(key(qs, 'title_i18n'), expected)

                expected.reverse()
                qs = TestObj.objects.all().order_by('-title_i18n')
                self.assertEquals(key(qs, 'title_i18n'), expected)

            # should use the 'default' fallback chain
            with override('fr'):
                qs = TestObj.objects.all().order_by('title_i18n')
                self.assertEquals(key(qs, 'title_i18n'), ['Falcon', 'Fox', 'Gecko', 'Gerbil', 'Grenouilles', 'Vautour'])
项目:django-modeltrans    作者:zostera    | 项目源码 | 文件源码
def test_queryset_values_i18n(self):
        with override('nl'):
            self.assertEqualsList(
                Blog.objects.all().order_by('title_i18n').values('title_i18n'),
                [{'title_i18n': 'Gecko'}, {'title_i18n': 'Kikker'}, {'title_i18n': 'Valk'}]
            )
项目:django-open-volunteering-platform    作者:OpenVolunteeringPlatform    | 项目源码 | 文件源码
def startup(request):
  """ This view provides initial data to the client, such as available skills and causes """
  with translation.override(translation.get_language_from_request(request)):
    skills = serializers.SkillSerializer(models.Skill.objects.filter(channel__slug=request.channel), many=True)
    causes = serializers.FullCauseSerializer(models.Cause.objects.filter(channel__slug=request.channel), many=True, context={'request': request})

    return response.Response({
      "skills": skills.data,
      "causes": causes.data
    })
项目:django-open-volunteering-platform    作者:OpenVolunteeringPlatform    | 项目源码 | 文件源码
def test_returns_localized_startup_data(self):
    """ Test startup route returns skills and causes """
    client = APIClient(HTTP_ACCEPT_LANGUAGE="pt-br")
    response = client.get(reverse("startup"), format="json")

    with translation.override('pt-br'):
      skills_data = serializers.SkillSerializer(models.Skill.objects.all(), many=True).data
      causes_data = serializers.FullCauseSerializer(models.Cause.objects.all(), many=True).data
      self.assertTrue(response.status_code == 200)
      self.assertTrue(response.data["skills"] == skills_data)
      self.assertTrue(response.data["causes"] == causes_data)
项目:pretalx    作者:pretalx    | 项目源码 | 文件源码
def notify_speakers(self):
        tz = pytz.timezone(self.event.timezone)
        speakers = defaultdict(lambda: {'create': [], 'update': []})
        if self.changes['action'] == 'create':
            speakers = {
                speaker: {'create': self.talks.filter(submission__speakers=speaker), 'update': []}
                for speaker in User.objects.filter(submissions__slots__schedule=self)
            }
        else:
            if self.changes['count'] == len(self.changes['canceled_talks']):
                return

            for new_talk in self.changes['new_talks']:
                for speaker in new_talk.submission.speakers.all():
                    speakers[speaker]['create'].append(new_talk)
            for moved_talk in self.changes['moved_talks']:
                for speaker in moved_talk['submission'].speakers.all():
                    speakers[speaker]['update'].append(moved_talk)
        for speaker in speakers:
            with override(speaker.locale), tzoverride(tz):
                text = get_template('schedule/speaker_notification.txt').render(
                    {'speaker': speaker, **speakers[speaker]}
                )
            QueuedMail.objects.create(
                event=self.event,
                to=speaker.email,
                reply_to=self.event.email,
                subject=_('[{event}] New schedule!').format(event=self.event.slug),
                text=text
            )
项目:pretalx    作者:pretalx    | 项目源码 | 文件源码
def create_user_as_orga(email, submission=None):
    if not email:
        return

    nick = email.split('@')[0].lower()
    while User.objects.filter(nick__iexact=nick).exists():
        nick += random.choice([
            '_1', '_2', '_11', '_42', '_the_first', '_the_third',
            '_speaker', '_third_of_their_name', '_', '123', nick
        ])

    user = User.objects.create_user(
        nick=nick,
        password=get_random_string(32),
        email=email.lower(),
        pw_reset_token=get_random_string(32),
        pw_reset_time=now() + timedelta(days=7),
    )
    with override(submission.content_locale):
        invitation_link = build_absolute_uri('cfp:event.recover', kwargs={'event': submission.event.slug, 'token': user.pw_reset_token})
        invitation_text = _('''Hi!

You have been set as the speaker of a submission to the Call for Participation
of {event}, titled »{title}«. An account has been created for you – please follow
this link to set your account password.

{invitation_link}

Afterwards, you can edit your user profile and see the state of your submission.

The {event} orga crew''').format(event=submission.event.name, title=submission.title, invitation_link=invitation_link)
        QueuedMail.objects.create(
            event=submission.event,
            to=user.email,
            reply_to=submission.event.email,
            subject=str(_('You have been added to a submission for {event}').format(event=submission.event.name)),
            text=invitation_text,
        )
    return user
项目:pretalx    作者:pretalx    | 项目源码 | 文件源码
def mail(user: User, subject: str, template: Union[str, LazyI18nString],
         context: Dict[str, Any]=None, event: Event=None, locale: str=None,
         headers: dict=None):
    from pretalx.mail.models import QueuedMail
    headers = headers or {}

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

        QueuedMail(
            event=event, to=user.email, subject=str(subject), text=body,
            reply_to=headers.get('reply-to'), bcc=headers.get('bcc'),
        ).send()
项目:rudi    作者:lexxodus    | 项目源码 | 文件源码
def send_code(request, team):
    text_template = loader.get_template(
        "rudi/mails/code.txt")

    context = Context({
        "team": team,
        "link": request.build_absolute_uri(reverse(
            "rudi:confirm",
            args=(
                team.code,
            ),
        )),
    })
    subject = SUBJECT_CODE % (team.event.name, team.event.semester)
    if team.participant_2_email:
        recipients = [
            team.participant_1_email,
            team.participant_2_email
        ]
    else:
        recipients = [team.participant_1_email]
    with override(team.language):
        send_single(
            context,
            text_template,
            subject,
            team.event.advisor.email,
            recipients,
        )
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
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)