本文整理汇总了Python中django.utils.translation.override方法的典型用法代码示例。如果您正苦于以下问题:Python translation.override方法的具体用法?Python translation.override怎么用?Python translation.override使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.utils.translation
的用法示例。
在下文中一共展示了translation.override方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_registration_view_failure
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import override [as 别名]
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)
示例2: test_description_and_short_description_required_in_name_languages
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import override [as 别名]
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.')
示例3: translate_url
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import override [as 别名]
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
示例4: test_date_filter_uses_timezone
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import override [as 别名]
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)
示例5: notify_message_push_subscribers_with_language
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import override [as 别名]
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),
}
)
示例6: prepare_application_message_notification
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import override [as 别名]
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'
)
示例7: you_were_just_subscribed_message
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import override [as 别名]
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
示例8: __init__
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import override [as 别名]
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')
示例9: test_calendar_template_content
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import override [as 别名]
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)
示例10: mail
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import override [as 别名]
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)
)
示例11: language_preferences
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import override [as 别名]
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,
})
示例12: dispatch
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import override [as 别名]
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
示例13: quotify
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import override [as 别名]
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
示例14: test_cms_wizards_course_run_language_active_not_in_all_languages
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import override [as 别名]
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"])
示例15: notify_items
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import override [as 别名]
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