當前位置: 首頁>>代碼示例>>Python>>正文


Python translation.activate方法代碼示例

本文整理匯總了Python中django.utils.translation.activate方法的典型用法代碼示例。如果您正苦於以下問題:Python translation.activate方法的具體用法?Python translation.activate怎麽用?Python translation.activate使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在django.utils.translation的用法示例。


在下文中一共展示了translation.activate方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: tracker_context

# 需要導入模塊: from django.utils import translation [as 別名]
# 或者: from django.utils.translation import activate [as 別名]
def tracker_context(request, qdict=None):
    starttime = datetime.datetime.now()
    language = translation.get_language_from_request(request)
    translation.activate(language)
    request.LANGUAGE_CODE = translation.get_language()
    profile = None
    qdict = qdict or {}
    qdict.update(
        {
            'djangoversion': dv(),
            'pythonversion': pv(),
            'user': request.user,
            'profile': profile,
            'next': request.POST.get('next', request.GET.get('next', request.path)),
            'starttime': starttime,
            'events': tracker.models.Event.objects.all(),
            'settings': settings,
        }
    )
    qdict.setdefault('event', viewutil.get_event(None))
    qdict.setdefault('user', request.user)
    return qdict 
開發者ID:GamesDoneQuick,項目名稱:donation-tracker,代碼行數:24,代碼來源:common.py

示例2: forward_to_backends

# 需要導入模塊: from django.utils import translation [as 別名]
# 或者: from django.utils.translation import activate [as 別名]
def forward_to_backends(self, method, *args, **kwargs):
        # forwards the desired backend method to all the language backends
        initial_language = translation.get_language()
        # retrieve unique backend name
        backends = []
        for language, _ in settings.LANGUAGES:
            using = '%s-%s' % (self.connection_alias, language)
            # Ensure each backend is called only once
            if using in backends:
                continue
            else:
                backends.append(using)
            translation.activate(language)
            backend = connections[using].get_backend()
            getattr(backend.parent_class, method)(backend, *args, **kwargs)

        if initial_language is not None:
            translation.activate(initial_language)
        else:
            translation.deactivate() 
開發者ID:City-of-Helsinki,項目名稱:linkedevents,代碼行數:22,代碼來源:backends.py

示例3: test_localize

# 需要導入模塊: from django.utils import translation [as 別名]
# 或者: from django.utils.translation import activate [as 別名]
def test_localize(self):
        env = Environment(extensions=[DjangoL10n])
        template = env.from_string("{{ foo }}")
        context1 = {'foo': 1.23}
        date = datetime.datetime(2000, 10, 1, 14, 10, 12, tzinfo=timezone.utc)
        context2 = {'foo': date}

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

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

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

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

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

        timezone.activate('America/Argentina/Buenos_Aires')
        self.assertEqual('1. Oktober 2000 11:10', template.render(context2)) 
開發者ID:MoritzS,項目名稱:jinja2-django-tags,代碼行數:27,代碼來源:tests.py

示例4: handle

# 需要導入模塊: from django.utils import translation [as 別名]
# 或者: from django.utils.translation import activate [as 別名]
def handle(self, *args, **options):
        translation.activate('eo')
        f = NamedTemporaryFile(mode='w+', delete=False, suffix='.csv')
        book = Group.objects.get(name='libro2017')
        writer = csv.writer(f)
        users = (
            User.objects.filter(groups__name='libro2017')
            & User.objects.exclude(reservation__isnull=True)
        ).order_by('reservation__amount', 'first_name').distinct()
        for user in users:
            writer.writerow([
                user.profile.full_name,
                user.email,
                user.profile.rawdisplay_phones(),
                'En la libro' if book in user.groups.all() else 'ne',
                repr(user.reservation_set.first()),
                'http://pspt.se' + user.profile.get_absolute_url(),
            ])
        print(f.name) 
開發者ID:tejoesperanto,項目名稱:pasportaservo,代碼行數:21,代碼來源:reservations.py

示例5: test_i18n_switcher

# 需要導入模塊: from django.utils import translation [as 別名]
# 或者: from django.utils.translation import activate [as 別名]
def test_i18n_switcher(rf):
    """ The language switcher is rendered correctly. """

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

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

    # render the link
    request = rf.get(reverse('home'))
    context = RequestContext(request, {})
    rendered_template = Template(template).render(context)
    for language in settings.LANGUAGES:
        if language == settings.LANGUAGES[0]:
            assert '<a href="/i18n/%s/"><u>%s</u></a>' % language in rendered_template
        else:
            assert'<a href="/i18n/%s/">%s</a>' % language in rendered_template 
開發者ID:rdmorganiser,項目名稱:rdmo,代碼行數:20,代碼來源:test_tags.py

示例6: process_response

# 需要導入模塊: from django.utils import translation [as 別名]
# 或者: from django.utils.translation import activate [as 別名]
def process_response(self, request, response):
        if not hasattr(request, 'user'):
            return response

        if not request.user.is_authenticated:
            return response

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

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

        return response 
開發者ID:Cadasta,項目名稱:cadasta-platform,代碼行數:18,代碼來源:middleware.py

示例7: test_signs_up_sets_language

# 需要導入模塊: from django.utils import translation [as 別名]
# 或者: from django.utils.translation import activate [as 別名]
def test_signs_up_sets_language(self):
        data = {
            'username': 'sherlock',
            'email': 'sherlock.holmes@bbc.uk',
            'password': '221B@bakerstreet',
            'full_name': 'Sherlock Holmes',
            'language': 'es'
        }
        response = self.request(method='POST', post_data=data)
        assert response.status_code == 302
        assert User.objects.count() == 1
        assert 'account/accountverification/' in response.location
        assert translation.get_language() == 'es'

        # Reset language for following tests
        translation.activate('en') 
開發者ID:Cadasta,項目名稱:cadasta-platform,代碼行數:18,代碼來源:test_views_default.py

示例8: handle

# 需要導入模塊: from django.utils import translation [as 別名]
# 或者: from django.utils.translation import activate [as 別名]
def handle(self, *args, **options):
        """Collects Crossref Events, parses them and stores new events locally.

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

        translation.activate(settings.LANGUAGE_CODE)

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

        if os.path.isfile(file_path):

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

        else:

            # Fetch data
            print('Fetching data from crossref event tracking API.')
            fetch_crossref_data()
            process_events() 
開發者ID:BirkbeckCTP,項目名稱:janeway,代碼行數:27,代碼來源:process_crossref_events.py

示例9: handle

# 需要導入模塊: from django.utils import translation [as 別名]
# 或者: from django.utils.translation import activate [as 別名]
def handle(self, *args, **options):

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

            try:
                upgrade_module = import_module(upgrade_module_path)
                upgrade_module.execute()
            except ImportError as e:
                print('There was an error running the requested upgrade: ')
                print(e) 
開發者ID:BirkbeckCTP,項目名稱:janeway,代碼行數:21,代碼來源:run_upgrade.py

示例10: handle

# 需要導入模塊: from django.utils import translation [as 別名]
# 或者: from django.utils.translation import activate [as 別名]
def handle(self, *args, **options):
        translation.activate('en')

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

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

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

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

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

            if found:
                print('{0} found'.format(setting_name))
            else:
                print('{0} not found'.format(setting_name)) 
開發者ID:BirkbeckCTP,項目名稱:janeway,代碼行數:27,代碼來源:check_settings_files.py

示例11: test_localized_lookup

# 需要導入模塊: from django.utils import translation [as 別名]
# 或者: from django.utils.translation import activate [as 別名]
def test_localized_lookup(self):
        """Tests whether localized lookup properly works."""

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

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

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

        # ensure that hstore lookups still work
        assert self.TestModel.objects.filter(text__ro="text_ro").exists() 
開發者ID:SectorLabs,項目名稱:django-localized-fields,代碼行數:23,代碼來源:test_lookups.py

示例12: test_translate_fallback

# 需要導入模塊: from django.utils import translation [as 別名]
# 或者: from django.utils.translation import activate [as 別名]
def test_translate_fallback():
        """Tests whether the :see:LocalizedValue class's translate()'s fallback
        functionality works properly."""

        test_value = "myvalue"

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

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

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

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

        # make sure that it's just __str__ falling
        # back and that for the other language
        # there's no actual value
        assert localized_value.get(other_language) != test_value 
開發者ID:SectorLabs,項目名稱:django-localized-fields,代碼行數:26,代碼來源:test_value.py

示例13: test_table_options_language

# 需要導入模塊: from django.utils import translation [as 別名]
# 或者: from django.utils.translation import activate [as 別名]
def test_table_options_language(self):
        """
        Test that the envrionment's language is used if no language provided.
        """
        # default must always contain a language value
        block = TableBlock()
        self.assertIn('language', block.table_options)
        # French
        translation.activate('fr-fr')
        block_fr = TableBlock()
        self.assertEqual('fr-fr', block_fr.table_options['language'])
        translation.activate('it')
        # Italian
        block_it = TableBlock()
        self.assertEqual('it', block_it.table_options['language'])
        # table_options with language provided, different to envrionment
        block_with_lang = TableBlock(table_options={'language': 'ja'})
        self.assertNotEqual('it', block_with_lang.table_options['language'])
        self.assertEqual('ja', block_with_lang.table_options['language'])
        translation.activate('en') 
開發者ID:wagtail,項目名稱:wagtail,代碼行數:22,代碼來源:tests.py

示例14: get_changeform_initial_data

# 需要導入模塊: from django.utils import translation [as 別名]
# 或者: from django.utils.translation import activate [as 別名]
def get_changeform_initial_data(self, request):
        '''Copy initial data from parent'''
        initial = super(PageAdmin, self).get_changeform_initial_data(request)
        if ('translation_of' in request.GET):
            original = self.model._tree_manager.get(
                pk=request.GET.get('translation_of'))
            initial['layout'] = original.layout
            initial['theme'] = original.theme
            initial['color_scheme'] = original.color_scheme

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

        return initial 
開發者ID:django-leonardo,項目名稱:django-leonardo,代碼行數:22,代碼來源:admin.py

示例15: settings

# 需要導入模塊: from django.utils import translation [as 別名]
# 或者: from django.utils.translation import activate [as 別名]
def settings(request):
    """User editing their profile."""
    title = _("Profile Settings")
    form = ProfileForm(instance=request.user)

    if request.method == "POST":

        form = ProfileForm(request.POST, request.FILES, instance=request.user)

        if form.is_valid():
            user = form.save()
            messages.success(request, _("Settings saved"))
            User.refresh_nomail()

            if form.cleaned_data['password1']:
                request.user.set_password(form.cleaned_data['password1'])
                request.user.save()

            lang = user.activate_locale()
            translation.activate(lang)
            request.session[translation.LANGUAGE_SESSION_KEY] = lang
            request.session['django_timezone'] = user.timezone

            return redirect(settings)
        else:
            messages.error(request, _("Error in profile data"))

    return render(request, "accounts/settings.html", locals()) 
開發者ID:fpsw,項目名稱:Servo,代碼行數:30,代碼來源:account.py


注:本文中的django.utils.translation.activate方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。