Converted usage of ugettext* functions to their gettext* aliases

Thanks Tim Graham for the review.
This commit is contained in:
Claude Paroz 2017-01-26 20:58:33 +01:00
parent 4353640ea9
commit c651331b34
129 changed files with 362 additions and 355 deletions

View File

@ -9,7 +9,7 @@ from django.core.exceptions import PermissionDenied
from django.db import router
from django.template.response import TemplateResponse
from django.utils.encoding import force_text
from django.utils.translation import ugettext as _, ugettext_lazy
from django.utils.translation import gettext as _, gettext_lazy
def delete_selected(modeladmin, request, queryset):
@ -84,4 +84,4 @@ def delete_selected(modeladmin, request, queryset):
], context)
delete_selected.short_description = ugettext_lazy("Delete selected %(verbose_name_plural)s")
delete_selected.short_description = gettext_lazy("Delete selected %(verbose_name_plural)s")

View File

@ -1,7 +1,7 @@
from django.apps import AppConfig
from django.contrib.admin.checks import check_admin_app, check_dependencies
from django.core import checks
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class SimpleAdminConfig(AppConfig):

View File

@ -15,7 +15,7 @@ from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.db import models
from django.utils import timezone
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class ListFilter:

View File

@ -1,6 +1,6 @@
from django import forms
from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class AdminAuthenticationForm(AuthenticationForm):

View File

@ -13,7 +13,7 @@ from django.template.defaultfilters import capfirst, linebreaksbr
from django.utils.encoding import force_text
from django.utils.html import conditional_escape, format_html
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext, ugettext_lazy as _
from django.utils.translation import gettext, gettext_lazy as _
ACTION_CHECKBOX_NAME = '_selected_action'
@ -290,10 +290,10 @@ class InlineAdminFormSet:
'name': '#%s' % self.formset.prefix,
'options': {
'prefix': self.formset.prefix,
'addText': ugettext('Add another %(verbose_name)s') % {
'addText': gettext('Add another %(verbose_name)s') % {
'verbose_name': capfirst(verbose_name),
},
'deleteText': ugettext('Remove'),
'deleteText': gettext('Remove'),
}
})

View File

@ -8,7 +8,7 @@ from django.urls import NoReverseMatch, reverse
from django.utils import timezone
from django.utils.encoding import force_text
from django.utils.text import get_text_list
from django.utils.translation import ugettext, ugettext_lazy as _
from django.utils.translation import gettext, gettext_lazy as _
ADDITION = 1
CHANGE = 2
@ -68,16 +68,16 @@ class LogEntry(models.Model):
def __str__(self):
if self.is_addition():
return ugettext('Added "%(object)s".') % {'object': self.object_repr}
return gettext('Added "%(object)s".') % {'object': self.object_repr}
elif self.is_change():
return ugettext('Changed "%(object)s" - %(changes)s') % {
return gettext('Changed "%(object)s" - %(changes)s') % {
'object': self.object_repr,
'changes': self.get_change_message(),
}
elif self.is_deletion():
return ugettext('Deleted "%(object)s."') % {'object': self.object_repr}
return gettext('Deleted "%(object)s."') % {'object': self.object_repr}
return ugettext('LogEntry Object')
return gettext('LogEntry Object')
def is_addition(self):
return self.action_flag == ADDITION
@ -102,29 +102,29 @@ class LogEntry(models.Model):
for sub_message in change_message:
if 'added' in sub_message:
if sub_message['added']:
sub_message['added']['name'] = ugettext(sub_message['added']['name'])
messages.append(ugettext('Added {name} "{object}".').format(**sub_message['added']))
sub_message['added']['name'] = gettext(sub_message['added']['name'])
messages.append(gettext('Added {name} "{object}".').format(**sub_message['added']))
else:
messages.append(ugettext('Added.'))
messages.append(gettext('Added.'))
elif 'changed' in sub_message:
sub_message['changed']['fields'] = get_text_list(
sub_message['changed']['fields'], ugettext('and')
sub_message['changed']['fields'], gettext('and')
)
if 'name' in sub_message['changed']:
sub_message['changed']['name'] = ugettext(sub_message['changed']['name'])
messages.append(ugettext('Changed {fields} for {name} "{object}".').format(
sub_message['changed']['name'] = gettext(sub_message['changed']['name'])
messages.append(gettext('Changed {fields} for {name} "{object}".').format(
**sub_message['changed']
))
else:
messages.append(ugettext('Changed {fields}.').format(**sub_message['changed']))
messages.append(gettext('Changed {fields}.').format(**sub_message['changed']))
elif 'deleted' in sub_message:
sub_message['deleted']['name'] = ugettext(sub_message['deleted']['name'])
messages.append(ugettext('Deleted {name} "{object}".').format(**sub_message['deleted']))
sub_message['deleted']['name'] = gettext(sub_message['deleted']['name'])
messages.append(gettext('Deleted {name} "{object}".').format(**sub_message['deleted']))
change_message = ' '.join(msg[0].upper() + msg[1:] for msg in messages)
return change_message or ugettext('No fields changed.')
return change_message or gettext('No fields changed.')
else:
return self.change_message

View File

@ -43,7 +43,7 @@ from django.utils.html import format_html
from django.utils.http import urlencode
from django.utils.safestring import mark_safe
from django.utils.text import capfirst, format_lazy, get_text_list
from django.utils.translation import ugettext as _, ungettext
from django.utils.translation import gettext as _, ngettext
from django.views.decorators.csrf import csrf_protect
from django.views.generic import RedirectView
@ -1609,7 +1609,7 @@ class ModelAdmin(BaseModelAdmin):
changecount += 1
if changecount:
msg = ungettext(
msg = ngettext(
"%(count)s %(name)s was changed successfully.",
"%(count)s %(name)s were changed successfully.",
changecount
@ -1641,7 +1641,7 @@ class ModelAdmin(BaseModelAdmin):
else:
action_form = None
selection_note_all = ungettext(
selection_note_all = ngettext(
'%(total_count)s selected',
'All %(total_count)s selected',
cl.result_count

View File

@ -10,7 +10,7 @@ from django.http import Http404, HttpResponseRedirect
from django.template.response import TemplateResponse
from django.urls import NoReverseMatch, reverse
from django.utils.text import capfirst
from django.utils.translation import ugettext as _, ugettext_lazy
from django.utils.translation import gettext as _, gettext_lazy
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from django.views.i18n import JavaScriptCatalog
@ -36,13 +36,13 @@ class AdminSite:
"""
# Text to put at the end of each page's <title>.
site_title = ugettext_lazy('Django site admin')
site_title = gettext_lazy('Django site admin')
# Text to put in each page's <h1>.
site_header = ugettext_lazy('Django administration')
site_header = gettext_lazy('Django administration')
# Text to put at the top of the admin index page.
index_title = ugettext_lazy('Site administration')
index_title = gettext_lazy('Site administration')
# URL for the "View site" link at the top of each admin page.
site_url = '/'

View File

@ -19,7 +19,7 @@ from django.utils.encoding import force_text
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from django.utils.text import capfirst
from django.utils.translation import ugettext as _
from django.utils.translation import gettext as _
register = Library()

View File

@ -2,7 +2,7 @@ from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.test import modify_settings
from django.test.selenium import SeleniumTestCase
from django.utils.deprecation import MiddlewareMixin
from django.utils.translation import ugettext as _
from django.utils.translation import gettext as _
class CSPMiddleware(MiddlewareMixin):

View File

@ -14,9 +14,7 @@ from django.utils import formats, timezone
from django.utils.encoding import force_text, smart_text
from django.utils.html import format_html
from django.utils.text import capfirst
from django.utils.translation import (
override as translation_override, ungettext,
)
from django.utils.translation import ngettext, override as translation_override
class FieldIsAForeignKeyColumnName(Exception):
@ -271,7 +269,7 @@ def model_ngettext(obj, n=None):
obj = obj.model
d = model_format_dict(obj)
singular, plural = d["verbose_name"], d["verbose_name_plural"]
return ungettext(singular, plural, n or 0)
return ngettext(singular, plural, n or 0)
def lookup_field(name, obj, model_admin=None):

View File

@ -18,7 +18,7 @@ from django.db import models
from django.urls import reverse
from django.utils.encoding import force_text
from django.utils.http import urlencode
from django.utils.translation import ugettext
from django.utils.translation import gettext
# Changelist settings
ALL_VAR = 'all'
@ -76,9 +76,9 @@ class ChangeList:
self.queryset = self.get_queryset(request)
self.get_results(request)
if self.is_popup:
title = ugettext('Select %s')
title = gettext('Select %s')
else:
title = ugettext('Select %s to change')
title = gettext('Select %s to change')
self.title = title % force_text(self.opts.verbose_name)
self.pk_attname = self.lookup_opts.pk.attname

View File

@ -11,7 +11,7 @@ from django.utils.encoding import force_text
from django.utils.html import smart_urlquote
from django.utils.safestring import mark_safe
from django.utils.text import Truncator
from django.utils.translation import ugettext as _
from django.utils.translation import gettext as _
class FilteredSelectMultiple(forms.SelectMultiple):

View File

@ -1,5 +1,5 @@
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class AdminDocsConfig(AppConfig):

View File

@ -20,7 +20,7 @@ from django.utils.inspect import (
func_accepts_kwargs, func_accepts_var_args, func_has_no_args,
get_func_full_args,
)
from django.utils.translation import ugettext as _
from django.utils.translation import gettext as _
from django.views.generic import TemplateView
# Exclude methods starting with these strings from documentation

View File

@ -16,7 +16,7 @@ from django.urls import reverse
from django.utils.decorators import method_decorator
from django.utils.encoding import force_text
from django.utils.html import escape
from django.utils.translation import ugettext, ugettext_lazy as _
from django.utils.translation import gettext, gettext_lazy as _
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.debug import sensitive_post_parameters
@ -144,7 +144,7 @@ class UserAdmin(admin.ModelAdmin):
form.save()
change_message = self.construct_change_message(request, form, None)
self.log_change(request, user, change_message)
msg = ugettext('Password changed successfully.')
msg = gettext('Password changed successfully.')
messages.success(request, msg)
update_session_auth_hash(request, form.user)
return HttpResponseRedirect(

View File

@ -1,7 +1,7 @@
from django.apps import AppConfig
from django.core import checks
from django.db.models.signals import post_migrate
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
from .checks import check_models_permissions, check_user_model
from .management import create_permissions

View File

@ -11,7 +11,7 @@ from django.contrib.auth.hashers import (
from django.db import models
from django.utils.crypto import get_random_string, salted_hmac
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class BaseUserManager(models.Manager):

View File

@ -15,7 +15,7 @@ from django.template import loader
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from django.utils.text import capfirst
from django.utils.translation import ugettext, ugettext_lazy as _
from django.utils.translation import gettext, gettext_lazy as _
UserModel = get_user_model()
@ -27,15 +27,15 @@ class ReadOnlyPasswordHashWidget(forms.Widget):
context = super().get_context(name, value, attrs)
summary = []
if not value or value.startswith(UNUSABLE_PASSWORD_PREFIX):
summary.append({'label': ugettext("No password set.")})
summary.append({'label': gettext("No password set.")})
else:
try:
hasher = identify_hasher(value)
except ValueError:
summary.append({'label': ugettext("Invalid password format or unknown hashing algorithm.")})
summary.append({'label': gettext("Invalid password format or unknown hashing algorithm.")})
else:
for key, value_ in hasher.safe_summary(value).items():
summary.append({'label': ugettext(key), 'value': value_})
summary.append({'label': gettext(key), 'value': value_})
context['summary'] = summary
return context

View File

@ -15,7 +15,7 @@ from django.utils.crypto import (
)
from django.utils.encoding import force_bytes, force_text
from django.utils.module_loading import import_string
from django.utils.translation import ugettext_noop as _
from django.utils.translation import gettext_noop as _
UNUSABLE_PASSWORD_PREFIX = '!' # This will never be a valid encoded hash
UNUSABLE_PASSWORD_SUFFIX_LENGTH = 40 # number of random chars to add after UNUSABLE_PASSWORD_PREFIX

View File

@ -7,7 +7,7 @@ from django.core.mail import send_mail
from django.db import models
from django.db.models.manager import EmptyManager
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
from .validators import UnicodeUsernameValidator

View File

@ -12,7 +12,7 @@ from django.utils.encoding import force_text
from django.utils.functional import lazy
from django.utils.html import format_html
from django.utils.module_loading import import_string
from django.utils.translation import ugettext as _, ungettext
from django.utils.translation import gettext as _, ngettext
@functools.lru_cache(maxsize=None)
@ -99,7 +99,7 @@ class MinimumLengthValidator:
def validate(self, password, user=None):
if len(password) < self.min_length:
raise ValidationError(
ungettext(
ngettext(
"This password is too short. It must contain at least %(min_length)d character.",
"This password is too short. It must contain at least %(min_length)d characters.",
self.min_length
@ -109,7 +109,7 @@ class MinimumLengthValidator:
)
def get_help_text(self):
return ungettext(
return ngettext(
"Your password must contain at least %(min_length)d character.",
"Your password must contain at least %(min_length)d characters.",
self.min_length

View File

@ -2,7 +2,7 @@ import re
from django.core import validators
from django.utils.deconstruct import deconstructible
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
@deconstructible

View File

@ -21,7 +21,7 @@ from django.utils.decorators import method_decorator
from django.utils.deprecation import RemovedInDjango21Warning
from django.utils.encoding import force_text
from django.utils.http import is_safe_url, urlsafe_base64_decode
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.debug import sensitive_post_parameters

View File

@ -2,7 +2,7 @@ from django.apps import AppConfig
from django.contrib.contenttypes.checks import check_generic_foreign_keys
from django.core import checks
from django.db.models.signals import post_migrate, pre_migrate
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
from .management import (
create_contenttypes, inject_rename_contenttypes_operations,

View File

@ -3,7 +3,7 @@ from collections import defaultdict
from django.apps import apps
from django.db import models
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class ContentTypeManager(models.Manager):

View File

@ -3,7 +3,7 @@ from django.apps import apps
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.requests import RequestSite
from django.core.exceptions import ObjectDoesNotExist
from django.utils.translation import ugettext as _
from django.utils.translation import gettext as _
def shortcut(request, content_type_id, object_id):

View File

@ -1,7 +1,7 @@
from django.contrib import admin
from django.contrib.flatpages.forms import FlatpageForm
from django.contrib.flatpages.models import FlatPage
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
@admin.register(FlatPage)

View File

@ -1,5 +1,5 @@
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class FlatPagesConfig(AppConfig):

View File

@ -1,7 +1,7 @@
from django import forms
from django.conf import settings
from django.contrib.flatpages.models import FlatPage
from django.utils.translation import ugettext, ugettext_lazy as _
from django.utils.translation import gettext, gettext_lazy as _
class FlatpageForm(forms.ModelForm):
@ -26,14 +26,14 @@ class FlatpageForm(forms.ModelForm):
url = self.cleaned_data['url']
if not url.startswith('/'):
raise forms.ValidationError(
ugettext("URL is missing a leading slash."),
gettext("URL is missing a leading slash."),
code='missing_leading_slash',
)
if (settings.APPEND_SLASH and
'django.middleware.common.CommonMiddleware' in settings.MIDDLEWARE and
not url.endswith('/')):
raise forms.ValidationError(
ugettext("URL is missing a trailing slash."),
gettext("URL is missing a trailing slash."),
code='missing_trailing_slash',
)
return url

View File

@ -2,7 +2,7 @@ from django.contrib.sites.models import Site
from django.db import models
from django.urls import get_script_prefix
from django.utils.encoding import iri_to_uri
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class FlatPage(models.Model):

View File

@ -1,6 +1,6 @@
from django.apps import AppConfig
from django.core import serializers
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class GISConfig(AppConfig):

View File

@ -10,7 +10,7 @@ from django.contrib.gis.geometry.backend import Geometry, GeometryException
from django.core.exceptions import ImproperlyConfigured
from django.db.models.expressions import Expression
from django.db.models.fields import Field
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
# Local cache of the spatial_ref_sys table, which holds SRID data for each
# spatial database alias. This cache exists so that the database isn't queried

View File

@ -1,6 +1,6 @@
from django import forms
from django.contrib.gis.geos import GEOSException, GEOSGeometry
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
from .widgets import OpenLayersWidget

View File

@ -1,5 +1,5 @@
from django.http import Http404
from django.utils.translation import ugettext as _
from django.utils.translation import gettext as _
def feed(request, url, feed_dict=None):

View File

@ -1,5 +1,5 @@
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class HumanizeConfig(AppConfig):

View File

@ -9,7 +9,7 @@ from django.utils.encoding import force_text
from django.utils.formats import number_format
from django.utils.safestring import mark_safe
from django.utils.timezone import is_aware, utc
from django.utils.translation import pgettext, ugettext as _, ungettext
from django.utils.translation import gettext as _, ngettext, pgettext
register = template.Library()
@ -56,48 +56,48 @@ def intcomma(value, use_l10n=True):
# A tuple of standard large number to their converters
intword_converters = (
(6, lambda number: (
ungettext('%(value).1f million', '%(value).1f million', number),
ungettext('%(value)s million', '%(value)s million', number),
ngettext('%(value).1f million', '%(value).1f million', number),
ngettext('%(value)s million', '%(value)s million', number),
)),
(9, lambda number: (
ungettext('%(value).1f billion', '%(value).1f billion', number),
ungettext('%(value)s billion', '%(value)s billion', number),
ngettext('%(value).1f billion', '%(value).1f billion', number),
ngettext('%(value)s billion', '%(value)s billion', number),
)),
(12, lambda number: (
ungettext('%(value).1f trillion', '%(value).1f trillion', number),
ungettext('%(value)s trillion', '%(value)s trillion', number),
ngettext('%(value).1f trillion', '%(value).1f trillion', number),
ngettext('%(value)s trillion', '%(value)s trillion', number),
)),
(15, lambda number: (
ungettext('%(value).1f quadrillion', '%(value).1f quadrillion', number),
ungettext('%(value)s quadrillion', '%(value)s quadrillion', number),
ngettext('%(value).1f quadrillion', '%(value).1f quadrillion', number),
ngettext('%(value)s quadrillion', '%(value)s quadrillion', number),
)),
(18, lambda number: (
ungettext('%(value).1f quintillion', '%(value).1f quintillion', number),
ungettext('%(value)s quintillion', '%(value)s quintillion', number),
ngettext('%(value).1f quintillion', '%(value).1f quintillion', number),
ngettext('%(value)s quintillion', '%(value)s quintillion', number),
)),
(21, lambda number: (
ungettext('%(value).1f sextillion', '%(value).1f sextillion', number),
ungettext('%(value)s sextillion', '%(value)s sextillion', number),
ngettext('%(value).1f sextillion', '%(value).1f sextillion', number),
ngettext('%(value)s sextillion', '%(value)s sextillion', number),
)),
(24, lambda number: (
ungettext('%(value).1f septillion', '%(value).1f septillion', number),
ungettext('%(value)s septillion', '%(value)s septillion', number),
ngettext('%(value).1f septillion', '%(value).1f septillion', number),
ngettext('%(value)s septillion', '%(value)s septillion', number),
)),
(27, lambda number: (
ungettext('%(value).1f octillion', '%(value).1f octillion', number),
ungettext('%(value)s octillion', '%(value)s octillion', number),
ngettext('%(value).1f octillion', '%(value).1f octillion', number),
ngettext('%(value)s octillion', '%(value)s octillion', number),
)),
(30, lambda number: (
ungettext('%(value).1f nonillion', '%(value).1f nonillion', number),
ungettext('%(value)s nonillion', '%(value)s nonillion', number),
ngettext('%(value).1f nonillion', '%(value).1f nonillion', number),
ngettext('%(value)s nonillion', '%(value)s nonillion', number),
)),
(33, lambda number: (
ungettext('%(value).1f decillion', '%(value).1f decillion', number),
ungettext('%(value)s decillion', '%(value)s decillion', number),
ngettext('%(value).1f decillion', '%(value).1f decillion', number),
ngettext('%(value)s decillion', '%(value)s decillion', number),
)),
(100, lambda number: (
ungettext('%(value).1f googol', '%(value).1f googol', number),
ungettext('%(value)s googol', '%(value)s googol', number),
ngettext('%(value).1f googol', '%(value).1f googol', number),
ngettext('%(value)s googol', '%(value)s googol', number),
)),
)
@ -202,21 +202,21 @@ def naturaltime(value):
elif delta.seconds == 0:
return _('now')
elif delta.seconds < 60:
return ungettext(
return ngettext(
# Translators: please keep a non-breaking space (U+00A0)
# between count and time unit.
'a second ago', '%(count)s seconds ago', delta.seconds
) % {'count': delta.seconds}
elif delta.seconds // 60 < 60:
count = delta.seconds // 60
return ungettext(
return ngettext(
# Translators: please keep a non-breaking space (U+00A0)
# between count and time unit.
'a minute ago', '%(count)s minutes ago', count
) % {'count': count}
else:
count = delta.seconds // 60 // 60
return ungettext(
return ngettext(
# Translators: please keep a non-breaking space (U+00A0)
# between count and time unit.
'an hour ago', '%(count)s hours ago', count
@ -230,21 +230,21 @@ def naturaltime(value):
elif delta.seconds == 0:
return _('now')
elif delta.seconds < 60:
return ungettext(
return ngettext(
# Translators: please keep a non-breaking space (U+00A0)
# between count and time unit.
'a second from now', '%(count)s seconds from now', delta.seconds
) % {'count': delta.seconds}
elif delta.seconds // 60 < 60:
count = delta.seconds // 60
return ungettext(
return ngettext(
# Translators: please keep a non-breaking space (U+00A0)
# between count and time unit.
'a minute from now', '%(count)s minutes from now', count
) % {'count': count}
else:
count = delta.seconds // 60 // 60
return ungettext(
return ngettext(
# Translators: please keep a non-breaking space (U+00A0)
# between count and time unit.
'an hour from now', '%(count)s hours from now', count

View File

@ -1,5 +1,5 @@
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class MessagesConfig(AppConfig):

View File

@ -2,7 +2,7 @@ from django.apps import AppConfig
from django.db import connections
from django.db.backends.signals import connection_created
from django.db.models import CharField, TextField
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
from .lookups import SearchLookup, TrigramSimilar, Unaccent
from .signals import register_hstore_handler

View File

@ -6,7 +6,7 @@ from django.contrib.postgres.validators import ArrayMaxLengthValidator
from django.core import checks, exceptions
from django.db.models import Field, IntegerField, Transform
from django.db.models.lookups import Exact, In
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
from ..utils import prefix_validation_error
from .utils import AttributeSetter

View File

@ -5,7 +5,7 @@ from django.contrib.postgres.fields.array import ArrayField
from django.core import exceptions
from django.db.models import Field, TextField, Transform
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
__all__ = ['HStoreField']

View File

@ -7,7 +7,7 @@ from django.core import exceptions
from django.db.models import (
Field, TextField, Transform, lookups as builtin_lookups,
)
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
__all__ = ['JSONField']

View File

@ -7,7 +7,7 @@ from django.contrib.postgres.validators import (
)
from django.core.exceptions import ValidationError
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
from ..utils import prefix_validation_error

View File

@ -2,7 +2,7 @@ import json
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
__all__ = ['HStoreField']

View File

@ -1,7 +1,7 @@
import json
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
__all__ = ['JSONField']

View File

@ -3,7 +3,7 @@ from psycopg2.extras import DateRange, DateTimeTZRange, NumericRange
from django import forms
from django.core import exceptions
from django.forms.widgets import MultiWidget
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
__all__ = ['IntegerRangeField', 'FloatRangeField', 'DateTimeRangeField', 'DateRangeField']

View File

@ -14,7 +14,7 @@ def prefix_validation_error(error, prefix, code, params):
# 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
# ngettext calls require a count parameter and are converted
# to an empty string if they are missing it.
message=format_lazy(
'{}{}',

View File

@ -6,18 +6,18 @@ from django.core.validators import (
MinValueValidator,
)
from django.utils.deconstruct import deconstructible
from django.utils.translation import ugettext_lazy as _, ungettext_lazy
from django.utils.translation import gettext_lazy as _, ngettext_lazy
class ArrayMaxLengthValidator(MaxLengthValidator):
message = ungettext_lazy(
message = ngettext_lazy(
'List contains %(show_value)d item, it should contain no more than %(limit_value)d.',
'List contains %(show_value)d items, it should contain no more than %(limit_value)d.',
'limit_value')
class ArrayMinLengthValidator(MinLengthValidator):
message = ungettext_lazy(
message = ngettext_lazy(
'List contains %(show_value)d item, it should contain no fewer than %(limit_value)d.',
'List contains %(show_value)d items, it should contain no fewer than %(limit_value)d.',
'limit_value')

View File

@ -1,5 +1,5 @@
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class RedirectsConfig(AppConfig):

View File

@ -1,6 +1,6 @@
from django.contrib.sites.models import Site
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class Redirect(models.Model):

View File

@ -1,5 +1,5 @@
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class SessionsConfig(AppConfig):

View File

@ -3,7 +3,7 @@ This module allows importing AbstractBaseSession even
when django.contrib.sessions is not in INSTALLED_APPS.
"""
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class BaseSessionManager(models.Manager):

View File

@ -1,5 +1,5 @@
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class SiteMapsConfig(AppConfig):

View File

@ -1,6 +1,6 @@
from django.apps import AppConfig
from django.db.models.signals import post_migrate
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
from .management import create_default_site

View File

@ -4,7 +4,7 @@ from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.db import models
from django.db.models.signals import pre_delete, pre_save
from django.http.request import split_domain_port
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
SITE_CACHE = {}

View File

@ -1,7 +1,7 @@
from django.apps import AppConfig
from django.contrib.staticfiles.checks import check_finders
from django.core import checks
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class StaticFilesConfig(AppConfig):

View File

@ -1,5 +1,5 @@
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class SyndicationConfig(AppConfig):

View File

@ -3,7 +3,7 @@ import warnings
from math import ceil
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class UnorderedObjectListWarning(RuntimeWarning):

View File

@ -8,7 +8,7 @@ from django.utils.deconstruct import deconstructible
from django.utils.encoding import force_text
from django.utils.functional import SimpleLazyObject
from django.utils.ipv6 import is_valid_ipv6_address
from django.utils.translation import ugettext_lazy as _, ungettext_lazy
from django.utils.translation import gettext_lazy as _, ngettext_lazy
# These values, if given to validate(), will trigger the self.required check.
EMPTY_VALUES = (None, '', [], (), {})
@ -359,7 +359,7 @@ class MinValueValidator(BaseValidator):
@deconstructible
class MinLengthValidator(BaseValidator):
message = ungettext_lazy(
message = ngettext_lazy(
'Ensure this value has at least %(limit_value)d character (it has %(show_value)d).',
'Ensure this value has at least %(limit_value)d characters (it has %(show_value)d).',
'limit_value')
@ -374,7 +374,7 @@ class MinLengthValidator(BaseValidator):
@deconstructible
class MaxLengthValidator(BaseValidator):
message = ungettext_lazy(
message = ngettext_lazy(
'Ensure this value has at most %(limit_value)d character (it has %(show_value)d).',
'Ensure this value has at most %(limit_value)d characters (it has %(show_value)d).',
'limit_value')
@ -394,17 +394,17 @@ class DecimalValidator:
expected, otherwise raise ValidationError.
"""
messages = {
'max_digits': ungettext_lazy(
'max_digits': ngettext_lazy(
'Ensure that there are no more than %(max)s digit in total.',
'Ensure that there are no more than %(max)s digits in total.',
'max'
),
'max_decimal_places': ungettext_lazy(
'max_decimal_places': ngettext_lazy(
'Ensure that there are no more than %(max)s decimal place.',
'Ensure that there are no more than %(max)s decimal places.',
'max'
),
'max_whole_digits': ungettext_lazy(
'max_whole_digits': ngettext_lazy(
'Ensure that there are no more than %(max)s digit before the decimal point.',
'Ensure that there are no more than %(max)s digits before the decimal point.',
'max'

View File

@ -29,7 +29,7 @@ from django.db.models.utils import make_model_tuple
from django.utils.encoding import force_text
from django.utils.functional import curry
from django.utils.text import capfirst, get_text_list
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
from django.utils.version import get_version

View File

@ -30,7 +30,7 @@ from django.utils.functional import Promise, cached_property, curry
from django.utils.ipv6 import clean_ipv6_address
from django.utils.itercompat import is_iterable
from django.utils.text import capfirst
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
__all__ = [
'AutoField', 'BLANK_CHOICE_DASH', 'BigAutoField', 'BigIntegerField',

View File

@ -10,7 +10,7 @@ from django.core.validators import validate_image_file_extension
from django.db.models import signals
from django.db.models.fields import Field
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class FieldFile(File):

View File

@ -14,7 +14,7 @@ from django.db.models.query_utils import PathInfo
from django.db.models.utils import make_model_tuple
from django.utils.encoding import force_text
from django.utils.functional import cached_property, curry
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
from . import Field
from .related_descriptors import (

View File

@ -9,7 +9,7 @@ from django.utils.functional import cached_property
from django.utils.html import conditional_escape, format_html, html_safe
from django.utils.inspect import func_supports_parameter
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
__all__ = ('BoundField',)

View File

@ -30,7 +30,7 @@ from django.utils.dateparse import parse_duration
from django.utils.duration import duration_string
from django.utils.encoding import force_text
from django.utils.ipv6 import clean_ipv6_address
from django.utils.translation import ugettext_lazy as _, ungettext_lazy
from django.utils.translation import gettext_lazy as _, ngettext_lazy
__all__ = (
'Field', 'CharField', 'IntegerField',
@ -534,7 +534,7 @@ class FileField(Field):
'invalid': _("No file was submitted. Check the encoding type on the form."),
'missing': _("No file was submitted."),
'empty': _("The submitted file is empty."),
'max_length': ungettext_lazy(
'max_length': ngettext_lazy(
'Ensure this filename has at most %(max)d character (it has %(length)d).',
'Ensure this filename has at most %(max)d characters (it has %(length)d).',
'max'),

View File

@ -16,7 +16,7 @@ from django.utils.encoding import force_text
from django.utils.functional import cached_property
from django.utils.html import conditional_escape, html_safe
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from django.utils.translation import gettext as _
from .renderers import get_default_renderer

View File

@ -6,7 +6,7 @@ from django.forms.widgets import HiddenInput
from django.utils.functional import cached_property
from django.utils.html import html_safe
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _, ungettext
from django.utils.translation import gettext as _, ngettext
__all__ = ('BaseFormSet', 'formset_factory', 'all_valid')
@ -341,14 +341,14 @@ class BaseFormSet:
if (self.validate_max and
self.total_form_count() - len(self.deleted_forms) > self.max_num) or \
self.management_form.cleaned_data[TOTAL_FORM_COUNT] > self.absolute_max:
raise ValidationError(ungettext(
raise ValidationError(ngettext(
"Please submit %d or fewer forms.",
"Please submit %d or fewer forms.", self.max_num) % self.max_num,
code='too_many_forms',
)
if (self.validate_min and
self.total_form_count() - len(self.deleted_forms) - empty_forms_count < self.min_num):
raise ValidationError(ungettext(
raise ValidationError(ngettext(
"Please submit %d or more forms.",
"Please submit %d or more forms.", self.min_num) % self.min_num,
code='too_few_forms')

View File

@ -18,7 +18,7 @@ from django.forms.widgets import (
)
from django.utils.encoding import force_text
from django.utils.text import capfirst, get_text_list
from django.utils.translation import ugettext, ugettext_lazy as _
from django.utils.translation import gettext, gettext_lazy as _
__all__ = (
'ModelForm', 'BaseModelForm', 'model_to_dict', 'fields_for_model',
@ -719,16 +719,16 @@ class BaseModelFormSet(BaseFormSet):
def get_unique_error_message(self, unique_check):
if len(unique_check) == 1:
return ugettext("Please correct the duplicate data for %(field)s.") % {
return gettext("Please correct the duplicate data for %(field)s.") % {
"field": unique_check[0],
}
else:
return ugettext("Please correct the duplicate data for %(field)s, which must be unique.") % {
return gettext("Please correct the duplicate data for %(field)s, which must be unique.") % {
"field": get_text_list(unique_check, _("and")),
}
def get_date_error_message(self, date_check):
return ugettext(
return gettext(
"Please correct the duplicate data for %(field_name)s "
"which must be unique for the %(lookup)s in %(date_field)s."
) % {
@ -738,7 +738,7 @@ class BaseModelFormSet(BaseFormSet):
}
def get_form_error(self):
return ugettext("Please correct the duplicate values below.")
return gettext("Please correct the duplicate values below.")
def save_existing_objects(self, commit=True):
self.changed_objects = []

View File

@ -6,7 +6,7 @@ from django.core.exceptions import ValidationError # backwards compatibility
from django.utils import timezone
from django.utils.encoding import force_text
from django.utils.html import escape, format_html, format_html_join, html_safe
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
def pretty_name(name):

View File

@ -17,7 +17,7 @@ from django.utils.encoding import force_text
from django.utils.formats import get_format
from django.utils.html import format_html, html_safe
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy
from django.utils.translation import gettext_lazy as _
from .renderers import get_default_renderer
@ -358,9 +358,9 @@ FILE_INPUT_CONTRADICTION = object()
class ClearableFileInput(FileInput):
clear_checkbox_label = ugettext_lazy('Clear')
initial_text = ugettext_lazy('Currently')
input_text = ugettext_lazy('Change')
clear_checkbox_label = _('Clear')
initial_text = _('Currently')
input_text = _('Change')
template_name = 'django/forms/widgets/clearable_file_input.html'
def clear_checkbox_name(self, name):
@ -690,9 +690,9 @@ class NullBooleanSelect(Select):
"""
def __init__(self, attrs=None):
choices = (
('1', ugettext_lazy('Unknown')),
('2', ugettext_lazy('Yes')),
('3', ugettext_lazy('No')),
('1', _('Unknown')),
('2', _('Yes')),
('3', _('No')),
)
super().__init__(attrs, choices)

View File

@ -65,7 +65,7 @@ from django.utils.text import (
get_text_list, smart_split, unescape_string_literal,
)
from django.utils.timezone import template_localtime
from django.utils.translation import pgettext_lazy, ugettext_lazy
from django.utils.translation import gettext_lazy, pgettext_lazy
from .exceptions import TemplateSyntaxError
@ -824,7 +824,7 @@ class Variable:
if self.message_context:
return pgettext_lazy(self.message_context, msgid)
else:
return ugettext_lazy(msgid)
return gettext_lazy(msgid)
return value
def __repr__(self):

View File

@ -19,7 +19,7 @@ from django.utils.text import (
Truncator, normalize_newlines, phone2numeric, slugify as _slugify, wrap,
)
from django.utils.timesince import timesince, timeuntil
from django.utils.translation import ugettext, ungettext
from django.utils.translation import gettext, ngettext
from .base import Variable, VariableDoesNotExist
from .library import Library
@ -817,7 +817,7 @@ def yesno(value, arg=None):
========== ====================== ==================================
"""
if arg is None:
arg = ugettext('yes,no,maybe')
arg = gettext('yes,no,maybe')
bits = arg.split(',')
if len(bits) < 2:
return value # Invalid arg.
@ -846,7 +846,7 @@ def filesizeformat(bytes_):
try:
bytes_ = float(bytes_)
except (TypeError, ValueError, UnicodeDecodeError):
value = ungettext("%(size)d byte", "%(size)d bytes", 0) % {'size': 0}
value = ngettext("%(size)d byte", "%(size)d bytes", 0) % {'size': 0}
return avoid_wrapping(value)
def filesize_number_format(value):
@ -863,17 +863,17 @@ def filesizeformat(bytes_):
bytes_ = -bytes_ # Allow formatting of negative numbers.
if bytes_ < KB:
value = ungettext("%(size)d byte", "%(size)d bytes", bytes_) % {'size': bytes_}
value = ngettext("%(size)d byte", "%(size)d bytes", bytes_) % {'size': bytes_}
elif bytes_ < MB:
value = ugettext("%s KB") % filesize_number_format(bytes_ / KB)
value = gettext("%s KB") % filesize_number_format(bytes_ / KB)
elif bytes_ < GB:
value = ugettext("%s MB") % filesize_number_format(bytes_ / MB)
value = gettext("%s MB") % filesize_number_format(bytes_ / MB)
elif bytes_ < TB:
value = ugettext("%s GB") % filesize_number_format(bytes_ / GB)
value = gettext("%s GB") % filesize_number_format(bytes_ / GB)
elif bytes_ < PB:
value = ugettext("%s TB") % filesize_number_format(bytes_ / TB)
value = gettext("%s TB") % filesize_number_format(bytes_ / TB)
else:
value = ugettext("%s PB") % filesize_number_format(bytes_ / PB)
value = gettext("%s PB") % filesize_number_format(bytes_ / PB)
if negative:
value = "-%s" % value

View File

@ -13,7 +13,7 @@ class GetAvailableLanguagesNode(Node):
self.variable = variable
def render(self, context):
context[self.variable] = [(k, translation.ugettext(v)) for k, v in settings.LANGUAGES]
context[self.variable] = [(k, translation.gettext(v)) for k, v in settings.LANGUAGES]
return ''
@ -142,13 +142,13 @@ class BlockTranslateNode(Node):
result = translation.npgettext(message_context, singular,
plural, count)
else:
result = translation.ungettext(singular, plural, count)
result = translation.ngettext(singular, plural, count)
vars.extend(plural_vars)
else:
if message_context:
result = translation.pgettext(message_context, singular)
else:
result = translation.ugettext(singular)
result = translation.gettext(singular)
default_value = context.template.engine.string_if_invalid
def render_value(key):
@ -267,7 +267,7 @@ def language_name(lang_code):
@register.filter
def language_name_translated(lang_code):
english_name = translation.get_language_info(lang_code)['name']
return translation.ugettext(english_name)
return translation.gettext(english_name)
@register.filter

View File

@ -114,7 +114,7 @@ class LocaleRegexProvider:
"""
def __init__(self, regex):
# regex is either a string representing a regular expression, or a
# translatable string (using ugettext_lazy) representing a regular
# translatable string (using gettext_lazy) representing a regular
# expression.
self._regex = regex
self._regex_dict = {}

View File

@ -20,7 +20,7 @@ from django.utils.dates import (
)
from django.utils.encoding import force_text
from django.utils.timezone import get_default_timezone, is_aware, is_naive
from django.utils.translation import ugettext as _
from django.utils.translation import gettext as _
re_formatchars = re.compile(r'(?<!\\)([aAbBcdDeEfFgGhHiIjlLmMnNoOPrsStTUuwWyYzZ])')
re_escaped = re.compile(r'\\(.)')

View File

@ -1,6 +1,6 @@
"Commonly-used date structures"
from django.utils.translation import pgettext_lazy, ugettext_lazy as _
from django.utils.translation import gettext_lazy as _, pgettext_lazy
WEEKDAYS = {
0: _('Monday'), 1: _('Tuesday'), 2: _('Wednesday'), 3: _('Thursday'), 4: _('Friday'),

View File

@ -1,7 +1,7 @@
import ipaddress
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
def clean_ipv6_address(ip_str, unpack_ipv4=False,

View File

@ -9,7 +9,7 @@ from django.utils.functional import (
SimpleLazyObject, keep_lazy, keep_lazy_text, lazy,
)
from django.utils.safestring import SafeText, mark_safe
from django.utils.translation import pgettext, ugettext as _, ugettext_lazy
from django.utils.translation import gettext as _, gettext_lazy, pgettext
@keep_lazy_text
@ -240,7 +240,7 @@ def get_valid_filename(s):
@keep_lazy_text
def get_text_list(list_, last_word=ugettext_lazy('or')):
def get_text_list(list_, last_word=gettext_lazy('or')):
"""
>>> get_text_list(['a', 'b', 'c', 'd'])
'a, b, c or d'

View File

@ -3,15 +3,15 @@ import datetime
from django.utils.html import avoid_wrapping
from django.utils.timezone import is_aware, utc
from django.utils.translation import ugettext, ungettext_lazy
from django.utils.translation import gettext, ngettext_lazy
TIMESINCE_CHUNKS = (
(60 * 60 * 24 * 365, ungettext_lazy('%d year', '%d years')),
(60 * 60 * 24 * 30, ungettext_lazy('%d month', '%d months')),
(60 * 60 * 24 * 7, ungettext_lazy('%d week', '%d weeks')),
(60 * 60 * 24, ungettext_lazy('%d day', '%d days')),
(60 * 60, ungettext_lazy('%d hour', '%d hours')),
(60, ungettext_lazy('%d minute', '%d minutes'))
(60 * 60 * 24 * 365, ngettext_lazy('%d year', '%d years')),
(60 * 60 * 24 * 30, ngettext_lazy('%d month', '%d months')),
(60 * 60 * 24 * 7, ngettext_lazy('%d week', '%d weeks')),
(60 * 60 * 24, ngettext_lazy('%d day', '%d days')),
(60 * 60, ngettext_lazy('%d hour', '%d hours')),
(60, ngettext_lazy('%d minute', '%d minutes'))
)
@ -55,7 +55,7 @@ def timesince(d, now=None, reversed=False):
since = delta.days * 24 * 60 * 60 + delta.seconds
if since <= 0:
# d is in the future compared to now, stop processing.
return avoid_wrapping(ugettext('0 minutes'))
return avoid_wrapping(gettext('0 minutes'))
for i, (seconds, name) in enumerate(TIMESINCE_CHUNKS):
count = since // seconds
if count != 0:
@ -66,7 +66,7 @@ def timesince(d, now=None, reversed=False):
seconds2, name2 = TIMESINCE_CHUNKS[i + 1]
count2 = (since - (seconds * count)) // seconds2
if count2 != 0:
result += ugettext(', ') + avoid_wrapping(name2 % count2)
result += gettext(', ') + avoid_wrapping(name2 % count2)
return result

View File

@ -250,7 +250,7 @@ def get_language_info(lang_code):
raise KeyError("Unknown language code %s and %s." % (lang_code, generic_lang_code))
if info:
info['name_translated'] = ugettext_lazy(info['name'])
info['name_translated'] = gettext_lazy(info['name'])
return info

View File

@ -1,7 +1,7 @@
from django.conf import settings
from django.http import HttpResponseForbidden
from django.template import Context, Engine, TemplateDoesNotExist, loader
from django.utils.translation import ugettext as _
from django.utils.translation import gettext as _
from django.utils.version import get_docs_version
# We include the template inline since we need to be able to reliably display

View File

@ -12,7 +12,7 @@ from django.utils import timezone
from django.utils.datastructures import MultiValueDict
from django.utils.encoding import force_text
from django.utils.module_loading import import_string
from django.utils.translation import ugettext as _
from django.utils.translation import gettext as _
# Minimal Django templates engine to render the error templates
# regardless of the project's TEMPLATES setting.

View File

@ -7,7 +7,7 @@ from django.http import Http404
from django.utils import timezone
from django.utils.encoding import force_text
from django.utils.functional import cached_property
from django.utils.translation import ugettext as _
from django.utils.translation import gettext as _
from django.views.generic.base import View
from django.views.generic.detail import (
BaseDetailView, SingleObjectTemplateResponseMixin,

View File

@ -1,7 +1,7 @@
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.http import Http404
from django.utils.translation import ugettext as _
from django.utils.translation import gettext as _
from django.views.generic.base import ContextMixin, TemplateResponseMixin, View

View File

@ -2,7 +2,7 @@ from django.core.exceptions import ImproperlyConfigured
from django.core.paginator import InvalidPage, Paginator
from django.db.models.query import QuerySet
from django.http import Http404
from django.utils.translation import ugettext as _
from django.utils.translation import gettext as _
from django.views.generic.base import ContextMixin, TemplateResponseMixin, View

View File

@ -15,7 +15,7 @@ from django.http import (
)
from django.template import Context, Engine, TemplateDoesNotExist, loader
from django.utils.http import http_date, parse_http_date
from django.utils.translation import ugettext as _, ugettext_lazy
from django.utils.translation import gettext as _, gettext_lazy
def serve(request, path, document_root=None, show_indexes=False):
@ -95,7 +95,7 @@ DEFAULT_DIRECTORY_INDEX_TEMPLATE = """
</body>
</html>
"""
template_translatable = ugettext_lazy("Index of %(directory)s")
template_translatable = gettext_lazy("Index of %(directory)s")
def directory_index(path, fullpath):

View File

@ -498,7 +498,7 @@ instances::
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
def parse_hand(hand_string):
"""Takes a string of cards and splits into a full hand."""

View File

@ -457,10 +457,10 @@ Here are some common problems that you may encounter during initialization:
importing an application configuration or a models module triggers code that
depends on the app registry.
For example, :func:`~django.utils.translation.ugettext()` uses the app
For example, :func:`~django.utils.translation.gettext()` uses the app
registry to look up translation catalogs in applications. To translate at
import time, you need :func:`~django.utils.translation.ugettext_lazy()`
instead. (Using :func:`~django.utils.translation.ugettext()` would be a bug,
import time, you need :func:`~django.utils.translation.gettext_lazy()`
instead. (Using :func:`~django.utils.translation.gettext()` would be a bug,
because the translation would happen at import time, rather than at each
request depending on the active language.)

View File

@ -860,7 +860,7 @@ subclass::
from datetime import date
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class DecadeBornListFilter(admin.SimpleListFilter):
# Human-readable title which will be displayed in the

View File

@ -186,7 +186,7 @@ registering a custom ``ModelAdmin`` for ``FlatPage``::
from django.contrib import admin
from django.contrib.flatpages.admin import FlatPageAdmin
from django.contrib.flatpages.models import FlatPage
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
# Define a new FlatPageAdmin
class FlatPageAdmin(FlatPageAdmin):

View File

@ -261,7 +261,7 @@ access to more than a single field::
import datetime
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class Article(models.Model):
...

View File

@ -1748,11 +1748,11 @@ to restrict language selection to a subset of the Django-provided languages.
If you define a custom :setting:`LANGUAGES` setting, you can mark the
language names as translation strings using the
:func:`~django.utils.translation.ugettext_lazy` function.
:func:`~django.utils.translation.gettext_lazy` function.
Here's a sample settings file::
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
LANGUAGES = [
('de', _('German')),

View File

@ -34,7 +34,7 @@ Helper function to return a URL pattern for serving files in debug mode::
]
The ``regex`` parameter should be a string or
:func:`~django.utils.translation.ugettext_lazy()` (see
:func:`~django.utils.translation.gettext_lazy()` (see
:ref:`translating-urlpatterns`) that contains a regular expression compatible
with Python's :py:mod:`re` module. Strings typically use raw string syntax
(``r''``) so that they can contain sequences like ``\d`` without the need to

View File

@ -16,7 +16,7 @@ different types of fields.
For example, here's a validator that only allows even numbers::
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
def validate_even(value):
if value % 2 != 0:

View File

@ -646,7 +646,7 @@ have a default value.
Here's a basic example of a validator, with one optional setting::
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
from django.utils.translation import gettext as _
class MinimumLengthValidator(object):
def __init__(self, min_length=8):

View File

@ -521,7 +521,7 @@ attributes of the inner ``Meta`` class if you want to further customize a field.
For example if you wanted to customize the wording of all user facing strings for
the ``name`` field::
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class AuthorForm(ModelForm):
class Meta:

View File

@ -49,7 +49,7 @@ Standard translation
--------------------
Specify a translation string by using the function
:func:`~django.utils.translation.ugettext`. It's convention to import this
:func:`~django.utils.translation.gettext`. It's convention to import this
as a shorter alias, ``_``, to save typing.
.. note::
@ -63,7 +63,7 @@ as a shorter alias, ``_``, to save typing.
global namespace, as an alias for ``gettext()``. In Django, we have chosen
not to follow this practice, for a couple of reasons:
1. Sometimes, you should use :func:`~django.utils.translation.ugettext_lazy`
1. Sometimes, you should use :func:`~django.utils.translation.gettext_lazy`
as the default translation method for a particular file. Without ``_()``
in the global namespace, the developer has to think about which is the
most appropriate translation function.
@ -71,7 +71,7 @@ as a shorter alias, ``_``, to save typing.
2. The underscore character (``_``) is used to represent "the previous
result" in Python's interactive shell and doctest tests. Installing a
global ``_()`` function causes interference. Explicitly importing
``ugettext()`` as ``_()`` avoids this problem.
``gettext()`` as ``_()`` avoids this problem.
.. admonition:: What functions may be aliased as ``_``?
@ -80,13 +80,11 @@ as a shorter alias, ``_``, to save typing.
* :func:`~django.utils.translation.gettext`
* :func:`~django.utils.translation.gettext_lazy`
* :func:`~django.utils.translation.ugettext`
* :func:`~django.utils.translation.ugettext_lazy`
In this example, the text ``"Welcome to my site."`` is marked as a translation
string::
from django.utils.translation import ugettext as _
from django.utils.translation import gettext as _
from django.http import HttpResponse
def my_view(request):
@ -96,11 +94,11 @@ string::
Obviously, you could code this without using the alias. This example is
identical to the previous one::
from django.utils.translation import ugettext
from django.utils.translation import gettext
from django.http import HttpResponse
def my_view(request):
output = ugettext("Welcome to my site.")
output = gettext("Welcome to my site.")
return HttpResponse(output)
Translation works on computed values. This example is identical to the previous
@ -123,7 +121,7 @@ examples, is that Django's translation-string-detecting utility,
:djadmin:`django-admin makemessages <makemessages>`, won't be able to find
these strings. More on :djadmin:`makemessages` later.)
The strings you pass to ``_()`` or ``ugettext()`` can take placeholders,
The strings you pass to ``_()`` or ``gettext()`` can take placeholders,
specified with Python's standard named-string interpolation syntax. Example::
def my_view(request, m, d):
@ -151,7 +149,7 @@ preceding the string, e.g.::
def my_view(request):
# Translators: This message appears on the home page only
output = ugettext("Welcome to my site.")
output = gettext("Welcome to my site.")
The comment will then appear in the resulting ``.po`` file associated with the
translatable construct located below it and should also be displayed by most
@ -173,7 +171,7 @@ more details.
Marking strings as no-op
------------------------
Use the function :func:`django.utils.translation.ugettext_noop()` to mark a
Use the function :func:`django.utils.translation.gettext_noop()` to mark a
string as a translation string without translating it. The string is later
translated from a variable.
@ -185,11 +183,11 @@ such as when the string is presented to the user.
Pluralization
-------------
Use the function :func:`django.utils.translation.ungettext()` to specify
Use the function :func:`django.utils.translation.ngettext()` to specify
pluralized messages.
``ungettext`` takes three arguments: the singular translation string, the plural
translation string and the number of objects.
``ngettext()`` takes three arguments: the singular translation string, the
plural translation string and the number of objects.
This function is useful when you need your Django application to be localizable
to languages where the number and complexity of `plural forms
@ -200,11 +198,11 @@ of its value.)
For example::
from django.utils.translation import ungettext
from django.utils.translation import ngettext
from django.http import HttpResponse
def hello_world(request, count):
page = ungettext(
page = ngettext(
'there is %(count)d object',
'there are %(count)d objects',
count) % {
@ -219,7 +217,7 @@ Note that pluralization is complicated and works differently in each language.
Comparing ``count`` to 1 isn't always the correct rule. This code looks
sophisticated, but will produce incorrect results for some languages::
from django.utils.translation import ungettext
from django.utils.translation import ngettext
from myapp.models import Report
count = Report.objects.count()
@ -228,7 +226,7 @@ sophisticated, but will produce incorrect results for some languages::
else:
name = Report._meta.verbose_name_plural
text = ungettext(
text = ngettext(
'There is %(count)d %(name)s available.',
'There are %(count)d %(name)s available.',
count
@ -240,7 +238,7 @@ sophisticated, but will produce incorrect results for some languages::
Don't try to implement your own singular-or-plural logic, it won't be correct.
In a case like this, consider something like the following::
text = ungettext(
text = ngettext(
'There is %(count)d %(name)s object available.',
'There are %(count)d %(name)s objects available.',
count
@ -253,13 +251,13 @@ In a case like this, consider something like the following::
.. note::
When using ``ungettext()``, make sure you use a single name for every
When using ``ngettext()``, make sure you use a single name for every
extrapolated variable included in the literal. In the examples above, note
how we used the ``name`` Python variable in both translation strings. This
example, besides being incorrect in some languages as noted above, would
fail::
text = ungettext(
text = ngettext(
'There is %(count)d %(name)s available.',
'There are %(count)d %(plural_name)s available.',
count
@ -355,7 +353,7 @@ For example, to translate the help text of the *name* field in the following
model, do the following::
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class MyThing(models.Model):
name = models.CharField(help_text=_('This is the help text'))
@ -387,7 +385,7 @@ relying on the fallback English-centric and somewhat naïve determination of
verbose names Django performs by looking at the model's class name::
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class MyThing(models.Model):
name = models.CharField(_('name'), help_text=_('This is the help text'))
@ -403,7 +401,7 @@ For model methods, you can provide translations to Django and the admin site
with the ``short_description`` attribute::
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class MyThing(models.Model):
kind = models.ForeignKey(
@ -420,30 +418,30 @@ with the ``short_description`` attribute::
Working with lazy translation objects
-------------------------------------
The result of a ``ugettext_lazy()`` call can be used wherever you would use a
string (a :class:`str` object) in other Django code, but it may not
work with arbitrary Python code. For example, the following won't work because
the `requests <https://pypi.python.org/pypi/requests/>`_ library doesn't handle
``ugettext_lazy`` objects::
The result of a ``gettext_lazy()`` call can be used wherever you would use a
string (a :class:`str` object) in other Django code, but it may not work with
arbitrary Python code. For example, the following won't work because the
`requests <https://pypi.python.org/pypi/requests/>`_ library doesn't handle
``gettext_lazy`` objects::
body = ugettext_lazy("I \u2764 Django") # (unicode :heart:)
body = gettext_lazy("I \u2764 Django") # (unicode :heart:)
requests.post('https://example.com/send', data={'body': body})
You can avoid such problems by casting ``ugettext_lazy()`` objects to text
You can avoid such problems by casting ``gettext_lazy()`` objects to text
strings before passing them to non-Django code::
requests.post('https://example.com/send', data={'body': str(body)})
If you don't like the long ``ugettext_lazy`` name, you can just alias it as
If you don't like the long ``gettext_lazy`` name, you can just alias it as
``_`` (underscore), like so::
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class MyThing(models.Model):
name = models.CharField(help_text=_('This is the help text'))
Using ``ugettext_lazy()`` and ``ungettext_lazy()`` to mark strings in models
Using ``gettext_lazy()`` and ``ngettext_lazy()`` to mark strings in models
and utility functions is a common operation. When you're working with these
objects elsewhere in your code, you should ensure that you don't accidentally
convert them to strings, because they should be converted as late as possible
@ -462,10 +460,10 @@ integer as the ``number`` argument. Then ``number`` will be looked up in the
dictionary under that key during string interpolation. Here's example::
from django import forms
from django.utils.translation import ungettext_lazy
from django.utils.translation import ngettext_lazy
class MyForm(forms.Form):
error_message = ungettext_lazy("You only provided %(num)d argument",
error_message = ngettext_lazy("You only provided %(num)d argument",
"You only provided %(num)d arguments", 'num')
def clean(self):
@ -477,7 +475,7 @@ If the string contains exactly one unnamed placeholder, you can interpolate
directly with the ``number`` argument::
class MyForm(forms.Form):
error_message = ungettext_lazy(
error_message = ngettext_lazy(
"You provided %d argument",
"You provided %d arguments",
)
@ -499,10 +497,10 @@ that runs the ``str.format()`` method only when the result is included
in a string. For example::
from django.utils.text import format_lazy
from django.utils.translation import ugettext_lazy
from django.utils.translation import gettext_lazy
...
name = ugettext_lazy('John Lennon')
instrument = ugettext_lazy('guitar')
name = gettext_lazy('John Lennon')
instrument = gettext_lazy('guitar')
result = format_lazy('{name}: {instrument}', name=name, instrument=instrument)
In this case, the lazy translations in ``result`` will only be converted to
@ -518,7 +516,7 @@ this function inside a lazy call yourself. For example::
from django.utils.functional import lazy
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
mark_safe_lazy = lazy(mark_safe, str)
@ -580,7 +578,7 @@ require translation in the future::
<title>{% trans "myvar" noop %}</title>
Internally, inline translations use an
:func:`~django.utils.translation.ugettext` call.
:func:`~django.utils.translation.gettext` call.
In case a template var (``myvar`` above) is passed to the tag, the tag will
first resolve such variable to a string at run-time and then look up that
@ -690,8 +688,8 @@ A more complex example::
When you use both the pluralization feature and bind values to local variables
in addition to the counter value, keep in mind that the ``blocktrans``
construct is internally converted to an ``ungettext`` call. This means the
same :ref:`notes regarding ungettext variables <pluralization-var-notes>`
construct is internally converted to an ``ngettext`` call. This means the
same :ref:`notes regarding ngettext variables <pluralization-var-notes>`
apply.
Reverse URL lookups cannot be carried out within the ``blocktrans`` and should
@ -1282,7 +1280,7 @@ Django provides two mechanisms to internationalize URL patterns:
the language to activate from the requested URL.
* Making URL patterns themselves translatable via the
:func:`django.utils.translation.ugettext_lazy()` function.
:func:`django.utils.translation.gettext_lazy()` function.
.. warning::
@ -1373,11 +1371,11 @@ Translating URL patterns
------------------------
URL patterns can also be marked translatable using the
:func:`~django.utils.translation.ugettext_lazy` function. Example::
:func:`~django.utils.translation.gettext_lazy` function. Example::
from django.conf.urls import include, url
from django.conf.urls.i18n import i18n_patterns
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
from about import views as about_views
from news import views as news_views
@ -1639,12 +1637,12 @@ That's it. Your translations are ready for use.
(Byte Order Mark) so if your text editor adds such marks to the beginning of
files by default then you will need to reconfigure it.
Troubleshooting: ``ugettext()`` incorrectly detects ``python-format`` in strings with percent signs
Troubleshooting: ``gettext()`` incorrectly detects ``python-format`` in strings with percent signs
---------------------------------------------------------------------------------------------------
In some cases, such as strings with a percent sign followed by a space and a
:ref:`string conversion type <old-string-formatting>` (e.g.
``_("10% interest")``), :func:`~django.utils.translation.ugettext` incorrectly
``_("10% interest")``), :func:`~django.utils.translation.gettext` incorrectly
flags strings with ``python-format``.
If you try to compile message files with incorrectly flagged strings, you'll
@ -1655,7 +1653,7 @@ unlike 'msgid'``.
To workaround this, you can escape percent signs by adding a second percent
sign::
from django.utils.translation import ugettext as _
from django.utils.translation import gettext as _
output = _("10%% interest)
Or you can use ``no-python-format`` so that all percent signs are treated as
@ -1859,7 +1857,7 @@ For example::
cur_language = translation.get_language()
try:
translation.activate(language)
text = translation.ugettext('welcome')
text = translation.gettext('welcome')
finally:
translation.activate(cur_language)
return text
@ -1882,7 +1880,7 @@ enter and restores it on exit. With it, the above example becomes::
def welcome_translated(language):
with translation.override(language):
return translation.ugettext('welcome')
return translation.gettext('welcome')
Language cookie
---------------
@ -2016,12 +2014,12 @@ Notes:
* If you define a custom :setting:`LANGUAGES` setting, as explained in the
previous bullet, you can mark the language names as translation strings
-- but use :func:`~django.utils.translation.ugettext_lazy` instead of
:func:`~django.utils.translation.ugettext` to avoid a circular import.
-- but use :func:`~django.utils.translation.gettext_lazy` instead of
:func:`~django.utils.translation.gettext` to avoid a circular import.
Here's a sample settings file::
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
LANGUAGES = [
('de', _('German')),

View File

@ -1,5 +1,5 @@
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
class Site(models.Model):

View File

@ -17,7 +17,7 @@ from django.forms.fields import CharField, Field, IntegerField
from django.test import SimpleTestCase, TestCase, override_settings
from django.utils import translation
from django.utils.text import capfirst
from django.utils.translation import ugettext as _
from django.utils.translation import gettext as _
from .models.custom_user import (
CustomUser, CustomUserWithoutIsActiveField, ExtensionUser,

View File

@ -16,7 +16,7 @@ from django.core.management import call_command
from django.core.management.base import CommandError
from django.db import migrations
from django.test import TestCase, override_settings
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import gettext_lazy as _
from .models import (
CustomUser, CustomUserNonUniqueUsername, CustomUserWithFK, Email,

Some files were not shown because too many files have changed in this diff Show More