本文整理汇总了Python中django.utils.translation.gettext_lazy方法的典型用法代码示例。如果您正苦于以下问题:Python translation.gettext_lazy方法的具体用法?Python translation.gettext_lazy怎么用?Python translation.gettext_lazy使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.utils.translation
的用法示例。
在下文中一共展示了translation.gettext_lazy方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: save
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext_lazy [as 别名]
def save(self, *args, **kwargs):
"""Generate the oauth consumer key and shared secret randomly upon creation.
Parameters
----------
args : list
Passed onto parent's `save` method
kwargs: dict
Passed onto parent's `save` method
"""
self.full_clean()
if not self.oauth_consumer_key:
self.oauth_consumer_key = "".join(
secrets.choice(OAUTH_CONSUMER_KEY_CHARS)
for _ in range(OAUTH_CONSUMER_KEY_SIZE)
)
if not self.shared_secret:
self.shared_secret = "".join(
secrets.choice(SHARED_SECRET_CHARS) for _ in range(SHARED_SECRET_SIZE)
)
super().save(*args, **kwargs)
示例2: clean
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext_lazy [as 别名]
def clean(self, values):
if not values and values is not False:
if self.required:
raise ValidationError(self.error_required % {
'values': values
})
else:
return values
try:
_ = iter(values)
except TypeError:
raise ValidationError(self.error_non_iterable)
for value in values:
self.check_type(value)
self.check_unsaved(value)
return values
示例3: process_webdriver_cookie
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext_lazy [as 别名]
def process_webdriver_cookie(self, cookie):
expiry = datetime.fromtimestamp(cookie.get("expiry", self.now))
obj, created = CookieDeclaration.objects.update_or_create(
name=cookie.get("name"),
domain=cookie.get("domain"),
defaults={
"security": CookieDeclaration.INSECURE_COOKIE
if cookie.get("httpOnly")
else CookieDeclaration.SECURE_COOKIE,
"purpose": _("Unknown"),
"duration": self.chop_microseconds(expiry - self.now),
},
)
self.increment_status(created)
示例4: process_requests_cookie
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext_lazy [as 别名]
def process_requests_cookie(self, cookie):
cookie_expires = getattr(cookie, "expires")
expiry = datetime.fromtimestamp(cookie_expires) if cookie_expires else self.now
obj, created = CookieDeclaration.objects.update_or_create(
name=getattr(cookie, "name"),
domain=getattr(cookie, "domain"),
defaults={
"security": CookieDeclaration.SECURE_COOKIE
if getattr(cookie, "secure", False)
else CookieDeclaration.INSECURE_COOKIE,
"purpose": _("Unknown"),
"duration": self.chop_microseconds(expiry - self.now),
},
)
self.increment_status(created)
示例5: from_current_timezone
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext_lazy [as 别名]
def from_current_timezone(value):
"""
When time zone support is enabled, convert naive datetimes
entered in the current time zone to aware datetimes.
"""
if settings.USE_TZ and value is not None and timezone.is_naive(value):
current_timezone = timezone.get_current_timezone()
try:
return timezone.make_aware(value, current_timezone)
except Exception as exc:
raise ValidationError(
_('%(datetime)s couldn\'t be interpreted '
'in time zone %(current_timezone)s; it '
'may be ambiguous or it may not exist.'),
code='ambiguous_timezone',
params={'datetime': value, 'current_timezone': current_timezone}
) from exc
return value
示例6: get_text_list
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext_lazy [as 别名]
def get_text_list(list_, last_word=gettext_lazy('or')):
"""
>>> get_text_list(['a', 'b', 'c', 'd'])
'a, b, c or d'
>>> get_text_list(['a', 'b', 'c'], 'and')
'a, b and c'
>>> get_text_list(['a', 'b'], 'and')
'a and b'
>>> get_text_list(['a'])
'a'
>>> get_text_list([])
''
"""
if len(list_) == 0:
return ''
if len(list_) == 1:
return str(list_[0])
return '%s %s %s' % (
# Translators: This string is used as a separator between list elements
_(', ').join(str(i) for i in list_[:-1]), str(last_word), str(list_[-1])
)
示例7: _check_column_name_clashes
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext_lazy [as 别名]
def _check_column_name_clashes(cls):
# Store a list of column names which have already been used by other fields.
used_column_names = []
errors = []
for f in cls._meta.local_fields:
_, column_name = f.get_attname_column()
# Ensure the column name is not already in use.
if column_name and column_name in used_column_names:
errors.append(
checks.Error(
"Field '%s' has column name '%s' that is used by "
"another field." % (f.name, column_name),
hint="Specify a 'db_column' for the field.",
obj=cls,
id='models.E007'
)
)
else:
used_column_names.append(column_name)
return errors
示例8: _check_model_name_db_lookup_clashes
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext_lazy [as 别名]
def _check_model_name_db_lookup_clashes(cls):
errors = []
model_name = cls.__name__
if model_name.startswith('_') or model_name.endswith('_'):
errors.append(
checks.Error(
"The model name '%s' cannot start or end with an underscore "
"as it collides with the query lookup syntax." % model_name,
obj=cls,
id='models.E023'
)
)
elif LOOKUP_SEP in model_name:
errors.append(
checks.Error(
"The model name '%s' cannot contain double underscores as "
"it collides with the query lookup syntax." % model_name,
obj=cls,
id='models.E024'
)
)
return errors
示例9: choices
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext_lazy [as 别名]
def choices(self, changelist):
yield {
'selected': self.lookup_val is None and not self.lookup_val_isnull,
'query_string': changelist.get_query_string(
{},
[self.lookup_kwarg, self.lookup_kwarg_isnull]
),
'display': _('All'),
}
for pk_val, val in self.lookup_choices:
yield {
'selected': self.lookup_val == str(pk_val),
'query_string': changelist.get_query_string({
self.lookup_kwarg: pk_val,
}, [self.lookup_kwarg_isnull]),
'display': val,
}
if self.include_empty_choice:
yield {
'selected': bool(self.lookup_val_isnull),
'query_string': changelist.get_query_string({
self.lookup_kwarg_isnull: 'True',
}, [self.lookup_kwarg]),
'display': self.empty_value_display,
}
示例10: password_reset_done
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext_lazy [as 别名]
def password_reset_done(request,
template_name='registration/password_reset_done.html',
extra_context=None):
warnings.warn("The password_reset_done() view is superseded by the "
"class-based PasswordResetDoneView().",
RemovedInDjango21Warning, stacklevel=2)
context = {
'title': _('Password reset sent'),
}
if extra_context is not None:
context.update(extra_context)
return TemplateResponse(request, template_name, context)
# Doesn't need csrf_protect since no-one can guess the URL
示例11: password_reset_complete
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext_lazy [as 别名]
def password_reset_complete(request,
template_name='registration/password_reset_complete.html',
extra_context=None):
warnings.warn("The password_reset_complete() view is superseded by the "
"class-based PasswordResetCompleteView().",
RemovedInDjango21Warning, stacklevel=2)
context = {
'login_url': resolve_url(settings.LOGIN_URL),
'title': _('Password reset complete'),
}
if extra_context is not None:
context.update(extra_context)
return TemplateResponse(request, template_name, context)
# Class-based password reset views
# - PasswordResetView sends the mail
# - PasswordResetDoneView shows a success message for the above
# - PasswordResetConfirmView checks the link the user clicked and
# prompts for a new password
# - PasswordResetCompleteView shows a success message for the above
示例12: get_context
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext_lazy [as 别名]
def get_context(self, name, value, attrs=None):
attrs = {} if attrs is None else attrs
context = super().get_context(name, value, attrs)
if self.is_localized:
self.widget.is_localized = self.is_localized
value = value or []
context['widget']['subwidgets'] = []
final_attrs = self.build_attrs(attrs)
id_ = final_attrs.get('id')
for i in range(max(len(value), self.size)):
try:
widget_value = value[i]
except IndexError:
widget_value = None
if id_:
final_attrs = dict(final_attrs, id='%s_%s' % (id_, i))
context['widget']['subwidgets'].append(
self.widget.get_context(name + '_%s' % i, widget_value, final_attrs)['widget']
)
return context
示例13: get_transform
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext_lazy [as 别名]
def get_transform(self, name):
transform = super().get_transform(name)
if transform:
return transform
if '_' not in name:
try:
index = int(name)
except ValueError:
pass
else:
index += 1 # postgres uses 1-indexing
return IndexTransformFactory(index, self.base_field)
try:
start, end = name.split('_')
start = int(start) + 1
end = int(end) # don't add one here because postgres slices are weird
except ValueError:
pass
else:
return SliceTransformFactory(start, end)
示例14: get_zones_choices
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext_lazy [as 别名]
def get_zones_choices():
for key in sorted(settings.ADS_ZONES):
yield (key, _(settings.ADS_ZONES[key].get('name', 'Undefined')))
示例15: __str__
# 需要导入模块: from django.utils import translation [as 别名]
# 或者: from django.utils.translation import gettext_lazy [as 别名]
def __str__(self):
"""Get the string representation of an instance."""
result = f"{self.title}"
if self.deleted:
result = _("{:s} [deleted]").format(result)
return result