1
0
mirror of https://github.com/django/django.git synced 2025-11-07 07:15:35 +00:00

Fixed #34140 -- Reformatted code blocks in docs with blacken-docs.

This commit is contained in:
django-bot
2023-02-28 20:53:28 +01:00
committed by Mariusz Felisiak
parent 6015bab80e
commit 14459f80ee
193 changed files with 5797 additions and 4481 deletions

View File

@@ -75,6 +75,7 @@ string::
from django.http import HttpResponse
from django.utils.translation import gettext as _
def my_view(request):
output = _("Welcome to my site.")
return HttpResponse(output)
@@ -85,6 +86,7 @@ previous one::
from django.http import HttpResponse
from django.utils.translation import gettext
def my_view(request):
output = gettext("Welcome to my site.")
return HttpResponse(output)
@@ -93,14 +95,14 @@ Translation works on computed values. This example is identical to the previous
two::
def my_view(request):
words = ['Welcome', 'to', 'my', 'site.']
output = _(' '.join(words))
words = ["Welcome", "to", "my", "site."]
output = _(" ".join(words))
return HttpResponse(output)
Translation works on variables. Again, here's an identical example::
def my_view(request):
sentence = 'Welcome to my site.'
sentence = "Welcome to my site."
output = _(sentence)
return HttpResponse(output)
@@ -113,7 +115,7 @@ 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):
output = _('Today is %(month)s %(day)s.') % {'month': m, 'day': d}
output = _("Today is %(month)s %(day)s.") % {"month": m, "day": d}
return HttpResponse(output)
This technique lets language-specific translations reorder the placeholder
@@ -194,13 +196,14 @@ For example::
from django.http import HttpResponse
from django.utils.translation import ngettext
def hello_world(request, count):
page = ngettext(
'there is %(count)d object',
'there are %(count)d objects',
"there is %(count)d object",
"there are %(count)d objects",
count,
) % {
'count': count,
"count": count,
}
return HttpResponse(page)
@@ -221,24 +224,21 @@ sophisticated, but will produce incorrect results for some languages::
name = Report._meta.verbose_name_plural
text = ngettext(
'There is %(count)d %(name)s available.',
'There are %(count)d %(name)s available.',
"There is %(count)d %(name)s available.",
"There are %(count)d %(name)s available.",
count,
) % {
'count': count,
'name': name
}
) % {"count": count, "name": name}
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 = ngettext(
'There is %(count)d %(name)s object available.',
'There are %(count)d %(name)s objects available.',
"There is %(count)d %(name)s object available.",
"There are %(count)d %(name)s objects available.",
count,
) % {
'count': count,
'name': Report._meta.verbose_name,
"count": count,
"name": Report._meta.verbose_name,
}
.. _pluralization-var-notes:
@@ -252,13 +252,13 @@ In a case like this, consider something like the following::
fail::
text = ngettext(
'There is %(count)d %(name)s available.',
'There are %(count)d %(plural_name)s available.',
"There is %(count)d %(name)s available.",
"There are %(count)d %(plural_name)s available.",
count,
) % {
'count': Report.objects.count(),
'name': Report._meta.verbose_name,
'plural_name': Report._meta.verbose_name_plural,
"count": Report.objects.count(),
"name": Report._meta.verbose_name,
"plural_name": Report._meta.verbose_name_plural,
}
You would get an error when running :djadmin:`django-admin
@@ -296,9 +296,11 @@ or::
from django.db import models
from django.utils.translation import pgettext_lazy
class MyThing(models.Model):
name = models.CharField(help_text=pgettext_lazy(
'help text for MyThing model', 'This is the help text'))
name = models.CharField(
help_text=pgettext_lazy("help text for MyThing model", "This is the help text")
)
will appear in the ``.po`` file as:
@@ -342,8 +344,9 @@ model, do the following::
from django.db import models
from django.utils.translation import gettext_lazy as _
class MyThing(models.Model):
name = models.CharField(help_text=_('This is the help text'))
name = models.CharField(help_text=_("This is the help text"))
You can mark names of :class:`~django.db.models.ForeignKey`,
:class:`~django.db.models.ManyToManyField` or
@@ -354,8 +357,8 @@ their :attr:`~django.db.models.Options.verbose_name` options::
kind = models.ForeignKey(
ThingKind,
on_delete=models.CASCADE,
related_name='kinds',
verbose_name=_('kind'),
related_name="kinds",
verbose_name=_("kind"),
)
Just like you would do in :attr:`~django.db.models.Options.verbose_name` you
@@ -374,12 +377,13 @@ verbose names Django performs by looking at the model's class name::
from django.db import models
from django.utils.translation import gettext_lazy as _
class MyThing(models.Model):
name = models.CharField(_('name'), help_text=_('This is the help text'))
name = models.CharField(_("name"), help_text=_("This is the help text"))
class Meta:
verbose_name = _('my thing')
verbose_name_plural = _('my things')
verbose_name = _("my thing")
verbose_name_plural = _("my things")
Model methods ``description`` argument to the ``@display`` decorator
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -392,15 +396,16 @@ decorator::
from django.db import models
from django.utils.translation import gettext_lazy as _
class MyThing(models.Model):
kind = models.ForeignKey(
ThingKind,
on_delete=models.CASCADE,
related_name='kinds',
verbose_name=_('kind'),
related_name="kinds",
verbose_name=_("kind"),
)
@admin.display(description=_('Is it a mouse?'))
@admin.display(description=_("Is it a mouse?"))
def is_mouse(self):
return self.kind.type == MOUSE_TYPE
@@ -414,12 +419,12 @@ arbitrary Python code. For example, the following won't work because the
``gettext_lazy`` objects::
body = gettext_lazy("I \u2764 Django") # (Unicode :heart:)
requests.post('https://example.com/send', data={'body': body})
requests.post("https://example.com/send", data={"body": body})
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)})
requests.post("https://example.com/send", data={"body": str(body)})
If you don't like the long ``gettext_lazy`` name, you can alias it as ``_``
(underscore), like so::
@@ -427,8 +432,9 @@ If you don't like the long ``gettext_lazy`` name, you can alias it as ``_``
from django.db import models
from django.utils.translation import gettext_lazy as _
class MyThing(models.Model):
name = models.CharField(help_text=_('This is the help text'))
name = models.CharField(help_text=_("This is the help text"))
Using ``gettext_lazy()`` and ``ngettext_lazy()`` to mark strings in models
and utility functions is a common operation. When you're working with these
@@ -452,14 +458,18 @@ dictionary under that key during string interpolation. Here's example::
from django.core.exceptions import ValidationError
from django.utils.translation import ngettext_lazy
class MyForm(forms.Form):
error_message = ngettext_lazy("You only provided %(num)d argument",
"You only provided %(num)d arguments", 'num')
error_message = ngettext_lazy(
"You only provided %(num)d argument",
"You only provided %(num)d arguments",
"num",
)
def clean(self):
# ...
if error:
raise ValidationError(self.error_message % {'num': number})
raise ValidationError(self.error_message % {"num": number})
If the string contains exactly one unnamed placeholder, you can interpolate
directly with the ``number`` argument::
@@ -488,10 +498,11 @@ in a string. For example::
from django.utils.text import format_lazy
from django.utils.translation import gettext_lazy
...
name = gettext_lazy('John Lennon')
instrument = gettext_lazy('guitar')
result = format_lazy('{name}: {instrument}', name=name, instrument=instrument)
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
strings when ``result`` itself is used in a string (usually at template
@@ -525,9 +536,9 @@ languages:
.. code-block:: pycon
>>> from django.utils.translation import activate, get_language_info
>>> activate('fr')
>>> li = get_language_info('de')
>>> print(li['name'], li['name_local'], li['name_translated'], li['bidi'])
>>> activate("fr")
>>> li = get_language_info("de")
>>> print(li["name"], li["name_local"], li["name_translated"], li["bidi"])
German Deutsch Allemand False
The ``name``, ``name_local``, and ``name_translated`` attributes of the
@@ -953,8 +964,8 @@ If you do this in your view:
.. code-block:: python
context = {'available_languages': ['en', 'es', 'fr']}
return render(request, 'mytemplate.html', context)
context = {"available_languages": ["en", "es", "fr"]}
return render(request, "mytemplate.html", context)
you can iterate over those languages in the template:
@@ -1031,15 +1042,17 @@ The ``JavaScriptCatalog`` view
from django.views.i18n import JavaScriptCatalog
urlpatterns = [
path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'),
path("jsi18n/", JavaScriptCatalog.as_view(), name="javascript-catalog"),
]
**Example with custom packages**::
urlpatterns = [
path('jsi18n/myapp/',
JavaScriptCatalog.as_view(packages=['your.app.label']),
name='javascript-catalog'),
path(
"jsi18n/myapp/",
JavaScriptCatalog.as_view(packages=["your.app.label"]),
name="javascript-catalog",
),
]
If your root URLconf uses :func:`~django.conf.urls.i18n.i18n_patterns`,
@@ -1051,7 +1064,7 @@ The ``JavaScriptCatalog`` view
from django.conf.urls.i18n import i18n_patterns
urlpatterns = i18n_patterns(
path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'),
path("jsi18n/", JavaScriptCatalog.as_view(), name="javascript-catalog"),
)
The precedence of translations is such that the packages appearing later in the
@@ -1090,7 +1103,7 @@ When the catalog is loaded, your JavaScript code can use the following methods:
The ``gettext`` function behaves similarly to the standard ``gettext``
interface within your Python code::
document.write(gettext('this is to be translated'));
document.write(gettext("this is to be translated"))
``ngettext``
~~~~~~~~~~~~
@@ -1190,7 +1203,7 @@ values.
This emulates the ``gettext`` function but does nothing, returning whatever
is passed to it::
document.write(gettext_noop('this will not be translated'));
document.write(gettext_noop("this will not be translated"))
This is useful for stubbing out portions of the code that will need translation
in the future.
@@ -1202,7 +1215,7 @@ The ``pgettext`` function behaves like the Python variant
(:func:`~django.utils.translation.pgettext()`), providing a contextually
translated word::
document.write(pgettext('month name', 'May'));
document.write(pgettext("month name", "May"))
``npgettext``
~~~~~~~~~~~~~
@@ -1291,9 +1304,13 @@ URL::
# The value returned by get_version() must change when translations change.
urlpatterns = [
path('jsi18n/',
cache_page(86400, key_prefix='jsi18n-%s' % get_version())(JavaScriptCatalog.as_view()),
name='javascript-catalog'),
path(
"jsi18n/",
cache_page(86400, key_prefix="jsi18n-%s" % get_version())(
JavaScriptCatalog.as_view()
),
name="javascript-catalog",
),
]
Client-side caching will save bandwidth and make your site load faster. If
@@ -1309,9 +1326,13 @@ whenever you restart your application server::
last_modified_date = timezone.now()
urlpatterns = [
path('jsi18n/',
last_modified(lambda req, **kw: last_modified_date)(JavaScriptCatalog.as_view()),
name='javascript-catalog'),
path(
"jsi18n/",
last_modified(lambda req, **kw: last_modified_date)(
JavaScriptCatalog.as_view()
),
name="javascript-catalog",
),
]
You can even pre-generate the JavaScript catalog as part of your deployment
@@ -1366,18 +1387,21 @@ Example URL patterns::
from sitemap.views import sitemap
urlpatterns = [
path('sitemap.xml', sitemap, name='sitemap-xml'),
path("sitemap.xml", sitemap, name="sitemap-xml"),
]
news_patterns = ([
path('', news_views.index, name='index'),
path('category/<slug:slug>/', news_views.category, name='category'),
path('<slug:slug>/', news_views.details, name='detail'),
], 'news')
news_patterns = (
[
path("", news_views.index, name="index"),
path("category/<slug:slug>/", news_views.category, name="category"),
path("<slug:slug>/", news_views.details, name="detail"),
],
"news",
)
urlpatterns += i18n_patterns(
path('about/', about_views.main, name='about'),
path('news/', include(news_patterns, namespace='news')),
path("about/", about_views.main, name="about"),
path("news/", include(news_patterns, namespace="news")),
)
After defining these URL patterns, Django will automatically add the
@@ -1389,14 +1413,14 @@ function. Example:
>>> from django.urls import reverse
>>> from django.utils.translation import activate
>>> activate('en')
>>> reverse('sitemap-xml')
>>> activate("en")
>>> reverse("sitemap-xml")
'/sitemap.xml'
>>> reverse('news:index')
>>> reverse("news:index")
'/en/news/'
>>> activate('nl')
>>> reverse('news:detail', kwargs={'slug': 'news-slug'})
>>> activate("nl")
>>> reverse("news:detail", kwargs={"slug": "news-slug"})
'/nl/news/news-slug/'
With ``prefix_default_language=False`` and ``LANGUAGE_CODE='en'``, the URLs
@@ -1404,12 +1428,12 @@ will be:
.. code-block:: pycon
>>> activate('en')
>>> reverse('news:index')
>>> activate("en")
>>> reverse("news:index")
'/news/'
>>> activate('nl')
>>> reverse('news:index')
>>> activate("nl")
>>> reverse("news:index")
'/nl/news/'
.. warning::
@@ -1440,18 +1464,21 @@ URL patterns can also be marked translatable using the
from sitemaps.views import sitemap
urlpatterns = [
path('sitemap.xml', sitemap, name='sitemap-xml'),
path("sitemap.xml", sitemap, name="sitemap-xml"),
]
news_patterns = ([
path('', news_views.index, name='index'),
path(_('category/<slug:slug>/'), news_views.category, name='category'),
path('<slug:slug>/', news_views.details, name='detail'),
], 'news')
news_patterns = (
[
path("", news_views.index, name="index"),
path(_("category/<slug:slug>/"), news_views.category, name="category"),
path("<slug:slug>/", news_views.details, name="detail"),
],
"news",
)
urlpatterns += i18n_patterns(
path(_('about/'), about_views.main, name='about'),
path(_('news/'), include(news_patterns, namespace='news')),
path(_("about/"), about_views.main, name="about"),
path(_("news/"), include(news_patterns, namespace="news")),
)
After you've created the translations, the :func:`~django.urls.reverse`
@@ -1462,12 +1489,12 @@ function will return the URL in the active language. Example:
>>> from django.urls import reverse
>>> from django.utils.translation import activate
>>> activate('en')
>>> reverse('news:category', kwargs={'slug': 'recent'})
>>> activate("en")
>>> reverse("news:category", kwargs={"slug": "recent"})
'/en/news/category/recent/'
>>> activate('nl')
>>> reverse('news:category', kwargs={'slug': 'recent'})
>>> activate("nl")
>>> reverse("news:category", kwargs={"slug": "recent"})
'/nl/nieuws/categorie/recent/'
.. warning::
@@ -1732,6 +1759,7 @@ To workaround this, you can escape percent signs by adding a second percent
sign::
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
@@ -1787,31 +1815,31 @@ attribute::
from django.core.management.commands import makemessages
class Command(makemessages.Command):
xgettext_options = makemessages.Command.xgettext_options + ['--keyword=mytrans']
xgettext_options = makemessages.Command.xgettext_options + ["--keyword=mytrans"]
If you need more flexibility, you could also add a new argument to your custom
:djadmin:`makemessages` command::
from django.core.management.commands import makemessages
class Command(makemessages.Command):
class Command(makemessages.Command):
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument(
'--extra-keyword',
dest='xgettext_keywords',
action='append',
"--extra-keyword",
dest="xgettext_keywords",
action="append",
)
def handle(self, *args, **options):
xgettext_keywords = options.pop('xgettext_keywords')
xgettext_keywords = options.pop("xgettext_keywords")
if xgettext_keywords:
self.xgettext_options = (
makemessages.Command.xgettext_options[:] +
['--keyword=%s' % kwd for kwd in xgettext_keywords]
)
self.xgettext_options = makemessages.Command.xgettext_options[:] + [
"--keyword=%s" % kwd for kwd in xgettext_keywords
]
super().handle(*args, **options)
Miscellaneous
@@ -1832,7 +1860,7 @@ back to the previous page.
Activate this view by adding the following line to your URLconf::
path('i18n/', include('django.conf.urls.i18n')),
path("i18n/", include("django.conf.urls.i18n")),
(Note that this example makes the view available at ``/i18n/setlang/``.)
@@ -1901,7 +1929,8 @@ response::
from django.conf import settings
from django.http import HttpResponse
from django.utils import translation
user_language = 'fr'
user_language = "fr"
translation.activate(user_language)
response = HttpResponse(...)
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, user_language)
@@ -1926,11 +1955,12 @@ For example::
from django.utils import translation
def welcome_translated(language):
cur_language = translation.get_language()
try:
translation.activate(language)
text = translation.gettext('welcome')
text = translation.gettext("welcome")
finally:
translation.activate(cur_language)
return text
@@ -1951,9 +1981,10 @@ enter and restores it on exit. With it, the above example becomes::
from django.utils import translation
def welcome_translated(language):
with translation.override(language):
return translation.gettext('welcome')
return translation.gettext("welcome")
Language cookie
---------------
@@ -2030,9 +2061,9 @@ these guidelines:
For example, your :setting:`MIDDLEWARE` might look like this::
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.locale.LocaleMiddleware",
"django.middleware.common.CommonMiddleware",
]
(For more on middleware, see the :doc:`middleware documentation
@@ -2077,8 +2108,8 @@ Notes:
set :setting:`LANGUAGES` to a list of languages. For example::
LANGUAGES = [
('de', _('German')),
('en', _('English')),
("de", _("German")),
("en", _("English")),
]
This example restricts languages that are available for automatic
@@ -2095,8 +2126,8 @@ Notes:
from django.utils.translation import gettext_lazy as _
LANGUAGES = [
('de', _('German')),
('en', _('English')),
("de", _("German")),
("en", _("English")),
]
Once ``LocaleMiddleware`` determines the user's preference, it makes this
@@ -2106,8 +2137,9 @@ code. Here's an example::
from django.http import HttpResponse
def hello_world(request, count):
if request.LANGUAGE_CODE == 'de-at':
if request.LANGUAGE_CODE == "de-at":
return HttpResponse("You prefer to read Austrian German.")
else:
return HttpResponse("You prefer to read another language.")