本文整理汇总了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
示例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()
示例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))
示例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)
示例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
示例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
示例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')
示例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()
示例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)
示例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))
示例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()
示例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
示例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')
示例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
示例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())