本文整理汇总了Python中django.utils.text.format_lazy方法的典型用法代码示例。如果您正苦于以下问题:Python text.format_lazy方法的具体用法?Python text.format_lazy怎么用?Python text.format_lazy使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.utils.text
的用法示例。
在下文中一共展示了text.format_lazy方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: prefix_validation_error
# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import format_lazy [as 别名]
def prefix_validation_error(error, prefix, code, params):
"""
Prefix a validation error message while maintaining the existing
validation data structure.
"""
if error.error_list == [error]:
error_params = error.params or {}
return ValidationError(
# We can't simply concatenate messages since they might require
# their associated parameters to be expressed correctly which
# is not something `format_lazy` does. For example, proxied
# ngettext calls require a count parameter and are converted
# to an empty string if they are missing it.
message=format_lazy(
'{}{}',
SimpleLazyObject(lambda: prefix % params),
SimpleLazyObject(lambda: error.message % error_params),
),
code=code,
params=dict(error_params, **params),
)
return ValidationError([
prefix_validation_error(e, prefix, code, params) for e in error.error_list
])
示例2: allowed
# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import format_lazy [as 别名]
def allowed(self, request, share=None):
usages = manila.tenant_absolute_limits(request)
shares_allowed = (usages['maxTotalShares'] >
usages['totalSharesUsed'] and
usages['maxTotalShareGigabytes'] >
usages['totalShareGigabytesUsed'])
if not shares_allowed:
if "disabled" not in self.classes:
self.classes = [c for c in self.classes] + ['disabled']
self.verbose_name = format_lazy(
'{verbose_name} {quota_exceeded}',
verbose_name=self.verbose_name,
quota_exceeded=_("(Quota exceeded)"))
else:
self.verbose_name = _("Create Share")
classes = [c for c in self.classes if c != "disabled"]
self.classes = classes
return True
示例3: validate_not_too_many_caps
# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import format_lazy [as 别名]
def validate_not_too_many_caps(value):
"""
Tries to figure out whether the value has too many capitals.
Maximum two capitals per word.
"""
authorized_begining = ("a", "de", "la", "mac", "mc")
message = _("It seems there are too many uppercase letters. Please try with '{correct_value}'.")
message = format_lazy(message, correct_value=title_with_particule(value))
words = split(value)
if not any(words):
pass # For non latin letters
elif value == value.upper():
validate_not_all_caps(value)
else:
for word in words:
nb_caps = sum(1 for char in word if char.isupper())
if nb_caps > 1:
if any([word.lower().startswith(s) for s in authorized_begining]):
# This should validate 'McCoy'
if nb_caps > 2:
raise ValidationError(message, code='caps')
else:
raise ValidationError(message, code='caps')
示例4: get_permission_denied_message
# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import format_lazy [as 别名]
def get_permission_denied_message(self, object, context_omitted=False):
if not context_omitted:
countries = [self.get_location(object)]
if not countries[0]:
countries = self.get_owner(object).owned_places.filter(
deleted=False
).values_list('country', flat=True).distinct()
elif not countries[0].name:
countries = []
else:
countries = None
if not countries:
return _("Only administrators can access this page")
to_string = lambda item: str(Country(item).name)
join_lazy = keep_lazy_text(lambda items: ", ".join(map(to_string, items)))
return format_lazy(self.permission_denied_message, this_country=join_lazy(countries))
示例5: prefix_validation_error
# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import format_lazy [as 别名]
def prefix_validation_error(error, prefix, code, params):
"""
Prefix a validation error message while maintaining the existing
validation data structure.
"""
if error.error_list == [error]:
error_params = error.params or {}
return ValidationError(
# We can't simply concatenate messages since they might require
# their associated parameters to be expressed correctly which
# is not something `format_lazy` does. For example, proxied
# ngettext calls require a count parameter and are converted
# to an empty string if they are missing it.
message=format_lazy(
'{} {}',
SimpleLazyObject(lambda: prefix % params),
SimpleLazyObject(lambda: error.message % error_params),
),
code=code,
params={**error_params, **params},
)
return ValidationError([
prefix_validation_error(e, prefix, code, params) for e in error.error_list
])
示例6: prefix_validation_error
# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import format_lazy [as 别名]
def prefix_validation_error(error, prefix, code, params):
"""
Prefix a validation error message while maintaining the existing
validation data structure.
"""
if error.error_list == [error]:
error_params = error.params or {}
return ValidationError(
# We can't simply concatenate messages since they might require
# their associated parameters to be expressed correctly which
# is not something `format_lazy` does. For example, proxied
# ungettext calls require a count parameter and are converted
# to an empty string if they are missing it.
message=format_lazy(
'{}{}',
SimpleLazyObject(lambda: prefix % params),
SimpleLazyObject(lambda: error.message % error_params),
),
code=code,
params=dict(error_params, **params),
)
return ValidationError([
prefix_validation_error(e, prefix, code, params) for e in error.error_list
])
示例7: test_format_lazy
# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import format_lazy [as 别名]
def test_format_lazy(self):
self.assertEqual('django/test', format_lazy('{}/{}', 'django', lazystr('test')))
self.assertEqual('django/test', format_lazy('{0}/{1}', *('django', 'test')))
self.assertEqual('django/test', format_lazy('{a}/{b}', **{'a': 'django', 'b': 'test'}))
self.assertEqual('django/test', format_lazy('{a[0]}/{a[1]}', a=('django', 'test')))
t = {}
s = format_lazy('{0[a]}-{p[a]}', t, p=t)
t['a'] = lazystr('django')
self.assertEqual('django-django', s)
t['a'] = 'update'
self.assertEqual('update-update', s)
# The format string can be lazy. (string comes from contrib.admin)
s = format_lazy(
gettext_lazy("Added {name} \"{object}\"."),
name='article', object='My first try',
)
with override('fr'):
self.assertEqual('Ajout de article «\xa0My first try\xa0».', s)
示例8: formfield_for_manytomany
# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import format_lazy [as 别名]
def formfield_for_manytomany(self, db_field, request, **kwargs):
"""
Get a form Field for a ManyToManyField.
"""
# If it uses an intermediary model that isn't auto created, don't show
# a field in admin.
if not db_field.remote_field.through._meta.auto_created:
return None
db = kwargs.get('using')
autocomplete_fields = self.get_autocomplete_fields(request)
if db_field.name in autocomplete_fields:
kwargs['widget'] = AutocompleteSelectMultiple(db_field.remote_field, self.admin_site, using=db)
elif db_field.name in self.raw_id_fields:
kwargs['widget'] = widgets.ManyToManyRawIdWidget(db_field.remote_field, self.admin_site, using=db)
elif db_field.name in list(self.filter_vertical) + list(self.filter_horizontal):
kwargs['widget'] = widgets.FilteredSelectMultiple(
db_field.verbose_name,
db_field.name in self.filter_vertical
)
if 'queryset' not in kwargs:
queryset = self.get_field_queryset(db, db_field, request)
if queryset is not None:
kwargs['queryset'] = queryset
form_field = db_field.formfield(**kwargs)
if (isinstance(form_field.widget, SelectMultiple) and
not isinstance(form_field.widget, (CheckboxSelectMultiple, AutocompleteSelectMultiple))):
msg = _('Hold down "Control", or "Command" on a Mac, to select more than one.')
help_text = form_field.help_text
form_field.help_text = format_lazy('{} {}', help_text, msg) if help_text else msg
return form_field
示例9: allowed
# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import format_lazy [as 别名]
def allowed(self, request, share=None):
usages = manila.tenant_absolute_limits(request)
snapshots_allowed = (usages['maxTotalShareSnapshots'] >
usages['totalShareSnapshotsUsed'] and
usages['maxTotalSnapshotGigabytes'] >
usages['totalSnapshotGigabytesUsed'])
if not snapshots_allowed:
if "disabled" not in self.classes:
self.classes = [c for c in self.classes] + ['disabled']
self.verbose_name = format_lazy(
'{verbose_name} {quota_exceeded}',
verbose_name=self.verbose_name,
quota_exceeded=_("(Quota exceeded)"))
else:
self.verbose_name = _("Create Share Snapshot")
classes = [c for c in self.classes if c != "disabled"]
self.classes = classes
# NOTE(vponomaryov): Disable form with creation of a snapshot for
# shares that has attr 'snapshot_support' equal to False.
if hasattr(share, 'snapshot_support'):
snapshot_support = share.snapshot_support
else:
# NOTE(vponomaryov): Allow creation of a snapshot for shares that
# do not have such attr for backward compatibility.
snapshot_support = True
return share.status in ("available", "in-use") and snapshot_support
示例10: get_success_url
# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import format_lazy [as 别名]
def get_success_url(self):
success_url = reverse_lazy('authorize_user', kwargs={'pk': self.kwargs['pk']})
redirect_to = sanitize_next(self.request)
if redirect_to:
return format_lazy('{}?{}', success_url, next_link(self.request, redirect_to))
return success_url
示例11: clean
# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import format_lazy [as 别名]
def clean(self):
cleaned_data = super().clean()
if cleaned_data.get('country') in COUNTRIES_WITH_MANDATORY_REGION and not cleaned_data.get('state'):
# Verifies that the region is indeed indicated when it is mandatory.
message = _("For an address in {country}, the name of the state or province must be indicated.")
self.add_error('state', format_lazy(message, country=Country(cleaned_data['country']).name))
return cleaned_data
示例12: __init__
# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import format_lazy [as 别名]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
config = SiteConfiguration.get_solo()
self.fields['first_name'].widget.attrs['inputmode'] = 'latin-name'
self.fields['last_name'].widget.attrs['inputmode'] = 'latin-name'
self.fields['names_inversed'].label = _("Names ordering")
field_bd = self.fields['birth_date']
if hasattr(self, 'instance') and \
(self.instance.has_places_for_hosting or self.instance.has_places_for_meeting):
if self.instance.has_places_for_hosting:
message = _("The minimum age to be allowed hosting is {age:d}.")
allowed_age = config.host_min_age
else:
message = _("The minimum age to be allowed meeting with visitors is {age:d}.")
allowed_age = config.meet_min_age
message = format_lazy(message, age=allowed_age)
field_bd.required = True
field_bd.validators.append(TooNearPastValidator(allowed_age))
field_bd.error_messages['max_value'] = message
field_bd.widget.attrs['placeholder'] = 'jjjj-mm-tt'
field_bd.widget.attrs['data-date-end-date'] = '0d'
field_bd.widget.attrs['pattern'] = '[1-2][0-9]{3}-((0[1-9])|(1[0-2]))-((0[1-9])|([12][0-9])|(3[0-1]))'
if hasattr(self, 'instance') and self.instance.has_places_for_in_book:
message = _("This field is required to be printed in the book.")
for field in self._validation_meta.book_required_fields:
req_field = self.fields[field]
req_field.required = True
req_field.error_messages['required'] = message
req_field.widget.attrs['data-error-required'] = message
self.fields['avatar'].widget.attrs['accept'] = 'image/*'
示例13: clean
# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import format_lazy [as 别名]
def clean(self):
"""
Sets specific fields as required when user wants their data to be
printed in the paper edition.
"""
cleaned_data = super().clean()
if hasattr(self, 'instance'):
profile = self.instance
for_book = profile.has_places_for_in_book
all_filled = all([
cleaned_data.get(field, False)
for field in self._validation_meta.book_required_fields
])
message = _("You want to be in the printed edition of Pasporta Servo. "
"In order to have a quality product, some fields are required. "
"If you think there is a problem, please contact us.")
if for_book and not all_filled:
if profile.has_places_for_hosting != profile.has_places_for_in_book:
clarify_message = format_lazy(
_("You are a host in {count_as_host} places, "
"of which {count_for_book} should be in the printed edition."),
count_as_host=profile.has_places_for_accepting_guests,
count_for_book=profile.has_places_for_in_book)
raise forms.ValidationError([message, clarify_message])
else:
raise forms.ValidationError(message)
if profile.death_date and 'birth_date' in cleaned_data:
if cleaned_data['birth_date'] > profile.death_date:
# Sanity check for life dates congruence.
# xgettext:python-brace-format
field_bd_message = _("The indicated date of birth is in conflict "
"with the date of death ({:%Y-%m-%d}).")
self.add_error(
'birth_date', format_lazy(field_bd_message, profile.death_date)
)
return cleaned_data
示例14: get_locality_display
# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import format_lazy [as 别名]
def get_locality_display(self):
"""
Returns "city (country)" or just "country" when no city is given.
"""
if self.city:
return format_lazy("{city} ({state})", city=self.city, state=self.country.name)
else:
return self.country.name
示例15: validate_size
# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import format_lazy [as 别名]
def validate_size(content):
"""Validates if the size of the content in not too big."""
if content.file.size > validate_size.MAX_UPLOAD_SIZE:
message = format_lazy(
_("Please keep filesize under {limit}. Current filesize {current}"),
limit=filesizeformat(validate_size.MAX_UPLOAD_SIZE),
current=filesizeformat(content.file.size))
raise ValidationError(message, code='file-size')