| 1 |
============ |
| 2 |
Django Utils |
| 3 |
============ |
| 4 |
|
| 5 |
.. module:: django.utils |
| 6 |
:synopsis: Django's built-in utilities. |
| 7 |
|
| 8 |
This document covers all stable modules in ``django.utils``. Most of the |
| 9 |
modules in ``django.utils`` are designed for internal use and only the |
| 10 |
following parts can be considered stable and thus backwards compatible as per |
| 11 |
the :ref:`internal release deprecation policy <internal-release-deprecation-policy>`. |
| 12 |
|
| 13 |
``django.utils.cache`` |
| 14 |
====================== |
| 15 |
|
| 16 |
.. module:: django.utils.cache |
| 17 |
:synopsis: Helper functions for controlling caching. |
| 18 |
|
| 19 |
This module contains helper functions for controlling HTTP caching. It does so |
| 20 |
by managing the ``Vary`` header of responses. It includes functions to patch |
| 21 |
the header of response objects directly and decorators that change functions to |
| 22 |
do that header-patching themselves. |
| 23 |
|
| 24 |
For information on the ``Vary`` header, see :rfc:`9110#section-12.5.5`. |
| 25 |
|
| 26 |
Essentially, the ``Vary`` HTTP header defines which headers a cache should take |
| 27 |
into account when building its cache key. Requests with the same path but |
| 28 |
different header content for headers named in ``Vary`` need to get different |
| 29 |
cache keys to prevent delivery of wrong content. |
| 30 |
|
| 31 |
For example, :doc:`internationalization </topics/i18n/index>` middleware would |
| 32 |
need to distinguish caches by the ``Accept-language`` header. |
| 33 |
|
| 34 |
.. function:: patch_cache_control(response, **kwargs) |
| 35 |
|
| 36 |
This function patches the ``Cache-Control`` header by adding all keyword |
| 37 |
arguments to it. The transformation is as follows: |
| 38 |
|
| 39 |
* All keyword parameter names are turned to lowercase, and underscores |
| 40 |
are converted to hyphens. |
| 41 |
* If the value of a parameter is ``True`` (exactly ``True``, not just a |
| 42 |
true value), only the parameter name is added to the header. |
| 43 |
* All other parameters are added with their value, after applying |
| 44 |
``str()`` to it. |
| 45 |
|
| 46 |
.. function:: get_max_age(response) |
| 47 |
|
| 48 |
Returns the max-age from the response Cache-Control header as an integer |
| 49 |
(or ``None`` if it wasn't found or wasn't an integer). |
| 50 |
|
| 51 |
.. function:: patch_response_headers(response, cache_timeout=None) |
| 52 |
|
| 53 |
Adds some useful headers to the given ``HttpResponse`` object: |
| 54 |
|
| 55 |
* ``Expires`` |
| 56 |
* ``Cache-Control`` |
| 57 |
|
| 58 |
Each header is only added if it isn't already set. |
| 59 |
|
| 60 |
``cache_timeout`` is in seconds. The :setting:`CACHE_MIDDLEWARE_SECONDS` |
| 61 |
setting is used by default. |
| 62 |
|
| 63 |
.. function:: add_never_cache_headers(response) |
| 64 |
|
| 65 |
Adds an ``Expires`` header to the current date/time. |
| 66 |
|
| 67 |
Adds a ``Cache-Control: max-age=0, no-cache, no-store, must-revalidate, |
| 68 |
private`` header to a response to indicate that a page should never be |
| 69 |
cached. |
| 70 |
|
| 71 |
Each header is only added if it isn't already set. |
| 72 |
|
| 73 |
.. function:: patch_vary_headers(response, newheaders) |
| 74 |
|
| 75 |
Adds (or updates) the ``Vary`` header in the given ``HttpResponse`` object. |
| 76 |
``newheaders`` is a list of header names that should be in ``Vary``. If |
| 77 |
headers contains an asterisk, then ``Vary`` header will consist of a single |
| 78 |
asterisk ``'*'``, according to :rfc:`9110#section-12.5.5`. Otherwise, |
| 79 |
existing headers in ``Vary`` aren't removed. |
| 80 |
|
| 81 |
.. function:: get_cache_key(request, key_prefix=None, method='GET', cache=None) |
| 82 |
|
| 83 |
Returns a cache key based on the request path. It can be used in the |
| 84 |
request phase because it pulls the list of headers to take into account |
| 85 |
from the global path registry and uses those to build a cache key to |
| 86 |
check against. |
| 87 |
|
| 88 |
If there is no headerlist stored, the page needs to be rebuilt, so this |
| 89 |
function returns ``None``. |
| 90 |
|
| 91 |
.. function:: learn_cache_key(request, response, cache_timeout=None, key_prefix=None, cache=None) |
| 92 |
|
| 93 |
Learns what headers to take into account for some request path from the |
| 94 |
response object. It stores those headers in a global path registry so that |
| 95 |
later access to that path will know what headers to take into account |
| 96 |
without building the response object itself. The headers are named in |
| 97 |
the ``Vary`` header of the response, but we want to prevent response |
| 98 |
generation. |
| 99 |
|
| 100 |
The list of headers to use for cache key generation is stored in the same |
| 101 |
cache as the pages themselves. If the cache ages some data out of the |
| 102 |
cache, this means that we have to build the response once to get at the |
| 103 |
Vary header and so at the list of headers to use for the cache key. |
| 104 |
|
| 105 |
``django.utils.dateparse`` |
| 106 |
========================== |
| 107 |
|
| 108 |
.. module:: django.utils.dateparse |
| 109 |
:synopsis: Functions to parse strings to datetime objects. |
| 110 |
|
| 111 |
The functions defined in this module share the following properties: |
| 112 |
|
| 113 |
- They accept strings in ISO 8601 date/time formats (or some close |
| 114 |
alternatives) and return objects from the corresponding classes in Python's |
| 115 |
:mod:`datetime` module. |
| 116 |
- They raise :exc:`ValueError` if their input is well formatted but isn't a |
| 117 |
valid date or time. |
| 118 |
- They return ``None`` if it isn't well formatted at all. |
| 119 |
- They accept up to picosecond resolution in input, but they truncate it to |
| 120 |
microseconds, since that's what Python supports. |
| 121 |
|
| 122 |
.. function:: parse_date(value) |
| 123 |
|
| 124 |
Parses a string and returns a :class:`datetime.date`. |
| 125 |
|
| 126 |
.. function:: parse_time(value) |
| 127 |
|
| 128 |
Parses a string and returns a :class:`datetime.time`. |
| 129 |
|
| 130 |
UTC offsets aren't supported; if ``value`` describes one, the result is |
| 131 |
``None``. |
| 132 |
|
| 133 |
.. function:: parse_datetime(value) |
| 134 |
|
| 135 |
Parses a string and returns a :class:`datetime.datetime`. |
| 136 |
|
| 137 |
UTC offsets are supported; if ``value`` describes one, the result's |
| 138 |
``tzinfo`` attribute is a :class:`datetime.timezone` instance. |
| 139 |
|
| 140 |
.. function:: parse_duration(value) |
| 141 |
|
| 142 |
Parses a string and returns a :class:`datetime.timedelta`. |
| 143 |
|
| 144 |
Expects data in the format ``"DD HH:MM:SS.uuuuuu"``, |
| 145 |
``"DD HH:MM:SS,uuuuuu"``, or as specified by ISO 8601 (e.g. |
| 146 |
``P4DT1H15M20S`` which is equivalent to ``4 1:15:20``) or PostgreSQL's |
| 147 |
day-time interval format (e.g. ``3 days 04:05:06``). |
| 148 |
|
| 149 |
``django.utils.decorators`` |
| 150 |
=========================== |
| 151 |
|
| 152 |
.. module:: django.utils.decorators |
| 153 |
:synopsis: Functions that help with creating decorators for views. |
| 154 |
|
| 155 |
.. function:: method_decorator(decorator, name='') |
| 156 |
|
| 157 |
Converts a function decorator into a method decorator. It can be used to |
| 158 |
decorate methods or classes; in the latter case, ``name`` is the name |
| 159 |
of the method to be decorated and is required. |
| 160 |
|
| 161 |
``decorator`` may also be a list or tuple of functions. They are wrapped |
| 162 |
in reverse order so that the call order is the order in which the functions |
| 163 |
appear in the list/tuple. |
| 164 |
|
| 165 |
See :ref:`decorating class based views <decorating-class-based-views>` for |
| 166 |
example usage. |
| 167 |
|
| 168 |
.. function:: decorator_from_middleware(middleware_class) |
| 169 |
|
| 170 |
Given a middleware class, returns a view decorator. This lets you use |
| 171 |
middleware functionality on a per-view basis. The middleware is created |
| 172 |
with no params passed. |
| 173 |
|
| 174 |
It assumes middleware that's compatible with the old style of Django 1.9 |
| 175 |
and earlier (having methods like ``process_request()``, |
| 176 |
``process_exception()``, and ``process_response()``). |
| 177 |
|
| 178 |
.. function:: decorator_from_middleware_with_args(middleware_class) |
| 179 |
|
| 180 |
Like ``decorator_from_middleware``, but returns a function |
| 181 |
that accepts the arguments to be passed to the middleware_class. |
| 182 |
For example, the :func:`~django.views.decorators.cache.cache_page` |
| 183 |
decorator is created from the ``CacheMiddleware`` like this:: |
| 184 |
|
| 185 |
cache_page = decorator_from_middleware_with_args(CacheMiddleware) |
| 186 |
|
| 187 |
|
| 188 |
@cache_page(3600) |
| 189 |
def my_view(request): |
| 190 |
pass |
| 191 |
|
| 192 |
.. function:: sync_only_middleware(middleware) |
| 193 |
|
| 194 |
Marks a middleware as :ref:`synchronous-only <async-middleware>`. (The |
| 195 |
default in Django, but this allows you to future-proof if the default ever |
| 196 |
changes in a future release.) |
| 197 |
|
| 198 |
.. function:: async_only_middleware(middleware) |
| 199 |
|
| 200 |
Marks a middleware as :ref:`asynchronous-only <async-middleware>`. Django |
| 201 |
will wrap it in an asynchronous event loop when it is called from the WSGI |
| 202 |
request path. |
| 203 |
|
| 204 |
.. function:: sync_and_async_middleware(middleware) |
| 205 |
|
| 206 |
Marks a middleware as :ref:`sync and async compatible <async-middleware>`, |
| 207 |
this allows to avoid converting requests. You must implement detection of |
| 208 |
the current request type to use this decorator. See :ref:`asynchronous |
| 209 |
middleware documentation <async-middleware>` for details. |
| 210 |
|
| 211 |
``django.utils.encoding`` |
| 212 |
========================= |
| 213 |
|
| 214 |
.. module:: django.utils.encoding |
| 215 |
:synopsis: A series of helper functions to manage character encoding. |
| 216 |
|
| 217 |
.. function:: smart_str(s, encoding='utf-8', strings_only=False, errors='strict') |
| 218 |
|
| 219 |
Returns a ``str`` object representing arbitrary object ``s``. Treats |
| 220 |
bytestrings using the ``encoding`` codec. |
| 221 |
|
| 222 |
If ``strings_only`` is ``True``, don't convert (some) non-string-like |
| 223 |
objects. |
| 224 |
|
| 225 |
.. function:: is_protected_type(obj) |
| 226 |
|
| 227 |
Determine if the object instance is of a protected type. |
| 228 |
|
| 229 |
Objects of protected types are preserved as-is when passed to |
| 230 |
``force_str(strings_only=True)``. |
| 231 |
|
| 232 |
.. function:: force_str(s, encoding='utf-8', strings_only=False, errors='strict') |
| 233 |
|
| 234 |
Similar to ``smart_str()``, except that lazy instances are resolved to |
| 235 |
strings, rather than kept as lazy objects. |
| 236 |
|
| 237 |
If ``strings_only`` is ``True``, don't convert (some) non-string-like |
| 238 |
objects. |
| 239 |
|
| 240 |
.. function:: smart_bytes(s, encoding='utf-8', strings_only=False, errors='strict') |
| 241 |
|
| 242 |
Returns a bytestring version of arbitrary object ``s``, encoded as |
| 243 |
specified in ``encoding``. |
| 244 |
|
| 245 |
If ``strings_only`` is ``True``, don't convert (some) non-string-like |
| 246 |
objects. |
| 247 |
|
| 248 |
.. function:: force_bytes(s, encoding='utf-8', strings_only=False, errors='strict') |
| 249 |
|
| 250 |
Similar to ``smart_bytes``, except that lazy instances are resolved to |
| 251 |
bytestrings, rather than kept as lazy objects. |
| 252 |
|
| 253 |
If ``strings_only`` is ``True``, don't convert (some) non-string-like |
| 254 |
objects. |
| 255 |
|
| 256 |
.. function:: iri_to_uri(iri) |
| 257 |
|
| 258 |
Convert an Internationalized Resource Identifier (IRI) portion to a URI |
| 259 |
portion that is suitable for inclusion in a URL. |
| 260 |
|
| 261 |
This is the algorithm from section 3.1 of :rfc:`3987#section-3.1`, slightly |
| 262 |
simplified since the input is assumed to be a string rather than an |
| 263 |
arbitrary byte stream. |
| 264 |
|
| 265 |
Takes an IRI (string or UTF-8 bytes) and returns a string containing the |
| 266 |
encoded result. |
| 267 |
|
| 268 |
.. function:: uri_to_iri(uri) |
| 269 |
|
| 270 |
Converts a Uniform Resource Identifier into an Internationalized Resource |
| 271 |
Identifier. |
| 272 |
|
| 273 |
This is an algorithm from section 3.2 of :rfc:`3987#section-3.2`. |
| 274 |
|
| 275 |
Takes a URI in ASCII bytes and returns a string containing the encoded |
| 276 |
result. |
| 277 |
|
| 278 |
.. function:: filepath_to_uri(path) |
| 279 |
|
| 280 |
Convert a file system path to a URI portion that is suitable for inclusion |
| 281 |
in a URL. The path is assumed to be either UTF-8 bytes, string, or a |
| 282 |
:class:`~pathlib.Path`. |
| 283 |
|
| 284 |
This method will encode certain characters that would normally be |
| 285 |
recognized as special characters for URIs. Note that this method does not |
| 286 |
encode the ' character, as it is a valid character within URIs. See |
| 287 |
``encodeURIComponent()`` JavaScript function for more details. |
| 288 |
|
| 289 |
Returns an ASCII string containing the encoded result. |
| 290 |
|
| 291 |
.. function:: escape_uri_path(path) |
| 292 |
|
| 293 |
Escapes the unsafe characters from the path portion of a Uniform Resource |
| 294 |
Identifier (URI). |
| 295 |
|
| 296 |
``django.utils.feedgenerator`` |
| 297 |
============================== |
| 298 |
|
| 299 |
.. module:: django.utils.feedgenerator |
| 300 |
:synopsis: Syndication feed generation library -- used for generating RSS, etc. |
| 301 |
|
| 302 |
Sample usage: |
| 303 |
|
| 304 |
.. code-block:: pycon |
| 305 |
|
| 306 |
>>> from django.utils import feedgenerator |
| 307 |
>>> feed = feedgenerator.Rss201rev2Feed( |
| 308 |
... title="Poynter E-Media Tidbits", |
| 309 |
... link="https://www.poynter.org/tag/e-media-tidbits/", |
| 310 |
... description="A group blog by the sharpest minds in online media/journalism/publishing.", |
| 311 |
... language="en", |
| 312 |
... ) |
| 313 |
>>> feed.add_item( |
| 314 |
... title="Hello", |
| 315 |
... link="https://www.holovaty.com/test/", |
| 316 |
... description="Testing.", |
| 317 |
... ) |
| 318 |
>>> with open("test.rss", "w") as fp: |
| 319 |
... feed.write(fp, "utf-8") |
| 320 |
... |
| 321 |
|
| 322 |
For simplifying the selection of a generator use ``feedgenerator.DefaultFeed`` |
| 323 |
which is currently ``Rss201rev2Feed`` |
| 324 |
|
| 325 |
For definitions of the different versions of RSS, see: |
| 326 |
https://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004/02/04/incompatible-rss |
| 327 |
|
| 328 |
.. function:: get_tag_uri(url, date) |
| 329 |
|
| 330 |
Creates a TagURI. |
| 331 |
|
| 332 |
See https://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id |
| 333 |
|
| 334 |
``Stylesheet`` |
| 335 |
-------------- |
| 336 |
|
| 337 |
.. versionadded:: 5.2 |
| 338 |
|
| 339 |
.. class:: Stylesheet(url, mimetype="", media="screen") |
| 340 |
|
| 341 |
Represents an RSS stylesheet. |
| 342 |
|
| 343 |
.. attribute:: url |
| 344 |
|
| 345 |
Required argument. The URL where the stylesheet is located. |
| 346 |
|
| 347 |
.. attribute:: mimetype |
| 348 |
|
| 349 |
An optional string containing the MIME type of the stylesheet. If not |
| 350 |
specified, Django will attempt to guess it by using Python's |
| 351 |
:py:func:`mimetypes.guess_type()`. Use ``mimetype=None`` if you don't |
| 352 |
want your stylesheet to have a MIME type specified. |
| 353 |
|
| 354 |
.. attribute:: media |
| 355 |
|
| 356 |
An optional string which will be used as the ``media`` attribute of |
| 357 |
the stylesheet. Defaults to ``"screen"``. Use ``media=None`` if you |
| 358 |
don't want your stylesheet to have a ``media`` attribute. |
| 359 |
|
| 360 |
``SyndicationFeed`` |
| 361 |
------------------- |
| 362 |
|
| 363 |
.. class:: SyndicationFeed |
| 364 |
|
| 365 |
Base class for all syndication feeds. Subclasses should provide |
| 366 |
``write()``. |
| 367 |
|
| 368 |
.. method:: __init__(title, link, description, language=None, author_email=None, author_name=None, author_link=None, subtitle=None, categories=None, feed_url=None, feed_copyright=None, feed_guid=None, ttl=None, stylesheets=None, **kwargs) |
| 369 |
|
| 370 |
Initialize the feed with the given dictionary of metadata, which applies |
| 371 |
to the entire feed. |
| 372 |
|
| 373 |
Any extra keyword arguments you pass to ``__init__`` will be stored in |
| 374 |
``self.feed``. |
| 375 |
|
| 376 |
All parameters should be strings, except for two: |
| 377 |
|
| 378 |
* ``categories`` should be a sequence of strings. |
| 379 |
* ``stylesheets`` should be a sequence of either strings or |
| 380 |
:class:`Stylesheet` instances. |
| 381 |
|
| 382 |
.. versionchanged:: 5.2 |
| 383 |
|
| 384 |
The ``stylesheets`` argument was added. |
| 385 |
|
| 386 |
.. method:: add_item(title, link, description, author_email=None, author_name=None, author_link=None, pubdate=None, comments=None, unique_id=None, categories=(), item_copyright=None, ttl=None, updateddate=None, enclosures=None, **kwargs) |
| 387 |
|
| 388 |
Adds an item to the feed. All args are expected to be strings except |
| 389 |
``pubdate`` and ``updateddate``, which are ``datetime.datetime`` |
| 390 |
objects, and ``enclosures``, which is a list of ``Enclosure`` instances. |
| 391 |
|
| 392 |
.. method:: num_items() |
| 393 |
|
| 394 |
.. method:: root_attributes() |
| 395 |
|
| 396 |
Return extra attributes to place on the root (i.e. feed/channel) |
| 397 |
element. Called from ``write()``. |
| 398 |
|
| 399 |
.. method:: add_root_elements(handler) |
| 400 |
|
| 401 |
Add elements in the root (i.e. feed/channel) element. |
| 402 |
Called from ``write()``. |
| 403 |
|
| 404 |
.. method:: add_stylesheets(self, handler) |
| 405 |
|
| 406 |
.. versionadded:: 5.2 |
| 407 |
|
| 408 |
Add stylesheet information to the document. |
| 409 |
Called from ``write()``. |
| 410 |
|
| 411 |
.. method:: item_attributes(item) |
| 412 |
|
| 413 |
Return extra attributes to place on each item (i.e. item/entry) |
| 414 |
element. |
| 415 |
|
| 416 |
.. method:: add_item_elements(handler, item) |
| 417 |
|
| 418 |
Add elements on each item (i.e. item/entry) element. |
| 419 |
|
| 420 |
.. method:: write(outfile, encoding) |
| 421 |
|
| 422 |
Outputs the feed in the given encoding to ``outfile``, which is a |
| 423 |
file-like object. Subclasses should override this. |
| 424 |
|
| 425 |
.. method:: writeString(encoding) |
| 426 |
|
| 427 |
Returns the feed in the given encoding as a string. |
| 428 |
|
| 429 |
.. method:: latest_post_date() |
| 430 |
|
| 431 |
Returns the latest ``pubdate`` or ``updateddate`` for all items in the |
| 432 |
feed. If no items have either of these attributes this returns the |
| 433 |
current UTC date/time. |
| 434 |
|
| 435 |
``Enclosure`` |
| 436 |
------------- |
| 437 |
|
| 438 |
.. class:: Enclosure |
| 439 |
|
| 440 |
Represents an RSS enclosure |
| 441 |
|
| 442 |
``RssFeed`` |
| 443 |
----------- |
| 444 |
|
| 445 |
.. class:: RssFeed(SyndicationFeed) |
| 446 |
|
| 447 |
``Rss201rev2Feed`` |
| 448 |
------------------ |
| 449 |
|
| 450 |
.. class:: Rss201rev2Feed(RssFeed) |
| 451 |
|
| 452 |
Spec: https://cyber.harvard.edu/rss/rss.html |
| 453 |
|
| 454 |
``RssUserland091Feed`` |
| 455 |
---------------------- |
| 456 |
|
| 457 |
.. class:: RssUserland091Feed(RssFeed) |
| 458 |
|
| 459 |
Spec: http://backend.userland.com/rss091 |
| 460 |
|
| 461 |
``Atom1Feed`` |
| 462 |
------------- |
| 463 |
|
| 464 |
.. class:: Atom1Feed(SyndicationFeed) |
| 465 |
|
| 466 |
Spec: :rfc:`4287` |
| 467 |
|
| 468 |
``django.utils.functional`` |
| 469 |
=========================== |
| 470 |
|
| 471 |
.. module:: django.utils.functional |
| 472 |
:synopsis: Functional programming tools. |
| 473 |
|
| 474 |
.. class:: cached_property(func) |
| 475 |
|
| 476 |
The ``@cached_property`` decorator caches the result of a method with a |
| 477 |
single ``self`` argument as a property. The cached result will persist |
| 478 |
as long as the instance does, so if the instance is passed around and the |
| 479 |
function subsequently invoked, the cached result will be returned. |
| 480 |
|
| 481 |
Consider a typical case, where a view might need to call a model's method |
| 482 |
to perform some computation, before placing the model instance into the |
| 483 |
context, where the template might invoke the method once more:: |
| 484 |
|
| 485 |
# the model |
| 486 |
class Person(models.Model): |
| 487 |
def friends(self): |
| 488 |
# expensive computation |
| 489 |
... |
| 490 |
return friends |
| 491 |
|
| 492 |
|
| 493 |
# in the view: |
| 494 |
if person.friends(): |
| 495 |
... |
| 496 |
|
| 497 |
And in the template you would have: |
| 498 |
|
| 499 |
.. code-block:: html+django |
| 500 |
|
| 501 |
{% for friend in person.friends %} |
| 502 |
|
| 503 |
Here, ``friends()`` will be called twice. Since the instance ``person`` in |
| 504 |
the view and the template are the same, decorating the ``friends()`` method |
| 505 |
with ``@cached_property`` can avoid that:: |
| 506 |
|
| 507 |
from django.utils.functional import cached_property |
| 508 |
|
| 509 |
|
| 510 |
class Person(models.Model): |
| 511 |
@cached_property |
| 512 |
def friends(self): ... |
| 513 |
|
| 514 |
Note that as the method is now a property, in Python code it will need to |
| 515 |
be accessed appropriately:: |
| 516 |
|
| 517 |
# in the view: |
| 518 |
if person.friends: |
| 519 |
... |
| 520 |
|
| 521 |
The cached value can be treated like an ordinary attribute of the instance:: |
| 522 |
|
| 523 |
# clear it, requiring re-computation next time it's called |
| 524 |
person.__dict__.pop("friends", None) |
| 525 |
|
| 526 |
# set a value manually, that will persist on the instance until cleared |
| 527 |
person.friends = ["Huckleberry Finn", "Tom Sawyer"] |
| 528 |
|
| 529 |
Because of the way the :py:ref:`descriptor protocol |
| 530 |
<descriptor-invocation>` works, using ``del`` (or ``delattr``) on a |
| 531 |
``cached_property`` that hasn't been accessed raises ``AttributeError``. |
| 532 |
|
| 533 |
As well as offering potential performance advantages, ``@cached_property`` |
| 534 |
can ensure that an attribute's value does not change unexpectedly over the |
| 535 |
life of an instance. This could occur with a method whose computation is |
| 536 |
based on ``datetime.now()``, or if a change were saved to the database by |
| 537 |
some other process in the brief interval between subsequent invocations of |
| 538 |
a method on the same instance. |
| 539 |
|
| 540 |
You can make cached properties of methods. For example, if you had an |
| 541 |
expensive ``get_friends()`` method and wanted to allow calling it without |
| 542 |
retrieving the cached value, you could write:: |
| 543 |
|
| 544 |
friends = cached_property(get_friends) |
| 545 |
|
| 546 |
While ``person.get_friends()`` will recompute the friends on each call, the |
| 547 |
value of the cached property will persist until you delete it as described |
| 548 |
above:: |
| 549 |
|
| 550 |
x = person.friends # calls first time |
| 551 |
y = person.get_friends() # calls again |
| 552 |
z = person.friends # does not call |
| 553 |
x is z # is True |
| 554 |
|
| 555 |
.. class:: classproperty(method=None) |
| 556 |
|
| 557 |
Similar to :py:func:`@classmethod <classmethod>`, the ``@classproperty`` |
| 558 |
decorator converts the result of a method with a single ``cls`` argument |
| 559 |
into a property that can be accessed directly from the class. |
| 560 |
|
| 561 |
.. function:: keep_lazy(func, *resultclasses) |
| 562 |
|
| 563 |
Django offers many utility functions (particularly in ``django.utils``) |
| 564 |
that take a string as their first argument and do something to that string. |
| 565 |
These functions are used by template filters as well as directly in other |
| 566 |
code. |
| 567 |
|
| 568 |
If you write your own similar functions and deal with translations, you'll |
| 569 |
face the problem of what to do when the first argument is a lazy |
| 570 |
translation object. You don't want to convert it to a string immediately, |
| 571 |
because you might be using this function outside of a view (and hence the |
| 572 |
current thread's locale setting will not be correct). |
| 573 |
|
| 574 |
For cases like this, use the ``django.utils.functional.keep_lazy()`` |
| 575 |
decorator. It modifies the function so that *if* it's called with a lazy |
| 576 |
translation as one of its arguments, the function evaluation is delayed |
| 577 |
until it needs to be converted to a string. |
| 578 |
|
| 579 |
For example:: |
| 580 |
|
| 581 |
from django.utils.functional import keep_lazy, keep_lazy_text |
| 582 |
|
| 583 |
|
| 584 |
def fancy_utility_function(s, *args, **kwargs): |
| 585 |
# Do some conversion on string 's' |
| 586 |
... |
| 587 |
|
| 588 |
|
| 589 |
fancy_utility_function = keep_lazy(str)(fancy_utility_function) |
| 590 |
|
| 591 |
|
| 592 |
# Or more succinctly: |
| 593 |
@keep_lazy(str) |
| 594 |
def fancy_utility_function(s, *args, **kwargs): ... |
| 595 |
|
| 596 |
The ``keep_lazy()`` decorator takes a number of extra arguments (``*args``) |
| 597 |
specifying the type(s) that the original function can return. A common |
| 598 |
use case is to have functions that return text. For these, you can pass the |
| 599 |
``str`` type to ``keep_lazy`` (or use the :func:`keep_lazy_text` decorator |
| 600 |
described in the next section). |
| 601 |
|
| 602 |
Using this decorator means you can write your function and assume that the |
| 603 |
input is a proper string, then add support for lazy translation objects at |
| 604 |
the end. |
| 605 |
|
| 606 |
.. function:: keep_lazy_text(func) |
| 607 |
|
| 608 |
A shortcut for ``keep_lazy(str)(func)``. |
| 609 |
|
| 610 |
If you have a function that returns text and you want to be able to take |
| 611 |
lazy arguments while delaying their evaluation, you can use this |
| 612 |
decorator:: |
| 613 |
|
| 614 |
from django.utils.functional import keep_lazy, keep_lazy_text |
| 615 |
|
| 616 |
|
| 617 |
# Our previous example was: |
| 618 |
@keep_lazy(str) |
| 619 |
def fancy_utility_function(s, *args, **kwargs): ... |
| 620 |
|
| 621 |
|
| 622 |
# Which can be rewritten as: |
| 623 |
@keep_lazy_text |
| 624 |
def fancy_utility_function(s, *args, **kwargs): ... |
| 625 |
|
| 626 |
``django.utils.html`` |
| 627 |
===================== |
| 628 |
|
| 629 |
.. module:: django.utils.html |
| 630 |
:synopsis: HTML helper functions |
| 631 |
|
| 632 |
Usually you should build up HTML using Django's templates to make use of its |
| 633 |
autoescape mechanism, using the utilities in :mod:`django.utils.safestring` |
| 634 |
where appropriate. This module provides some additional low level utilities for |
| 635 |
escaping HTML. |
| 636 |
|
| 637 |
.. function:: escape(text) |
| 638 |
|
| 639 |
Returns the given text with ampersands, quotes and angle brackets encoded |
| 640 |
for use in HTML. The input is first coerced to a string and the output has |
| 641 |
:func:`~django.utils.safestring.mark_safe` applied. |
| 642 |
|
| 643 |
.. function:: conditional_escape(text) |
| 644 |
|
| 645 |
Similar to ``escape()``, except that it doesn't operate on preescaped |
| 646 |
strings, so it will not double escape. |
| 647 |
|
| 648 |
.. function:: format_html(format_string, *args, **kwargs) |
| 649 |
|
| 650 |
This is similar to :meth:`str.format`, except that it is appropriate for |
| 651 |
building up HTML fragments. The first argument ``format_string`` is not |
| 652 |
escaped but all other args and kwargs are passed through |
| 653 |
:func:`conditional_escape` before being passed to ``str.format()``. |
| 654 |
Finally, the output has :func:`~django.utils.safestring.mark_safe` applied. |
| 655 |
|
| 656 |
For the case of building up small HTML fragments, this function is to be |
| 657 |
preferred over string interpolation using ``%`` or ``str.format()`` |
| 658 |
directly, because it applies escaping to all arguments - just like the |
| 659 |
template system applies escaping by default. |
| 660 |
|
| 661 |
So, instead of writing:: |
| 662 |
|
| 663 |
mark_safe( |
| 664 |
"%s <b>%s</b> %s" |
| 665 |
% ( |
| 666 |
some_html, |
| 667 |
escape(some_text), |
| 668 |
escape(some_other_text), |
| 669 |
) |
| 670 |
) |
| 671 |
|
| 672 |
You should instead use:: |
| 673 |
|
| 674 |
format_html( |
| 675 |
"{} <b>{}</b> {}", |
| 676 |
mark_safe(some_html), |
| 677 |
some_text, |
| 678 |
some_other_text, |
| 679 |
) |
| 680 |
|
| 681 |
This has the advantage that you don't need to apply :func:`escape` to each |
| 682 |
argument and risk a bug and an XSS vulnerability if you forget one. |
| 683 |
|
| 684 |
Note that although this function uses ``str.format()`` to do the |
| 685 |
interpolation, some of the formatting options provided by ``str.format()`` |
| 686 |
(e.g. number formatting) will not work, since all arguments are passed |
| 687 |
through :func:`conditional_escape` which (ultimately) calls |
| 688 |
:func:`~django.utils.encoding.force_str` on the values. |
| 689 |
|
| 690 |
.. deprecated:: 5.0 |
| 691 |
|
| 692 |
Support for calling ``format_html()`` without passing args or kwargs is |
| 693 |
deprecated. |
| 694 |
|
| 695 |
.. function:: format_html_join(sep, format_string, args_generator) |
| 696 |
|
| 697 |
A wrapper of :func:`format_html`, for the common case of a group of |
| 698 |
arguments that need to be formatted using the same format string, and then |
| 699 |
joined using ``sep``. ``sep`` is also passed through |
| 700 |
:func:`conditional_escape`. |
| 701 |
|
| 702 |
``args_generator`` should be an iterator that yields arguments to pass to |
| 703 |
:func:`format_html`, either sequences of positional arguments or mappings of |
| 704 |
keyword arguments. |
| 705 |
|
| 706 |
For example, tuples can be used for positional arguments:: |
| 707 |
|
| 708 |
format_html_join( |
| 709 |
"\n", |
| 710 |
"<li>{} {}</li>", |
| 711 |
((u.first_name, u.last_name) for u in users), |
| 712 |
) |
| 713 |
|
| 714 |
Or dictionaries can be used for keyword arguments:: |
| 715 |
|
| 716 |
format_html_join( |
| 717 |
"\n", |
| 718 |
'<li data-id="{id}">{id} {title}</li>', |
| 719 |
({"id": b.id, "title": b.title} for b in books), |
| 720 |
) |
| 721 |
|
| 722 |
.. versionchanged:: 5.2 |
| 723 |
|
| 724 |
Support for mappings in ``args_generator`` was added. |
| 725 |
|
| 726 |
.. function:: json_script(value, element_id=None, encoder=None) |
| 727 |
|
| 728 |
Escapes all HTML/XML special characters with their Unicode escapes, so |
| 729 |
value is safe for use with JavaScript. Also wraps the escaped JSON in a |
| 730 |
``<script>`` tag. If the ``element_id`` parameter is not ``None``, the |
| 731 |
``<script>`` tag is given the passed id. For example: |
| 732 |
|
| 733 |
.. code-block:: pycon |
| 734 |
|
| 735 |
>>> json_script({"hello": "world"}, element_id="hello-data") |
| 736 |
'<script id="hello-data" type="application/json">{"hello": "world"}</script>' |
| 737 |
|
| 738 |
The ``encoder``, which defaults to |
| 739 |
:class:`django.core.serializers.json.DjangoJSONEncoder`, will be used to |
| 740 |
serialize the data. See :ref:`JSON serialization |
| 741 |
<serialization-formats-json>` for more details about this serializer. |
| 742 |
|
| 743 |
.. function:: strip_tags(value) |
| 744 |
|
| 745 |
Tries to remove anything that looks like an HTML tag from the string, that |
| 746 |
is anything contained within ``<>``. |
| 747 |
|
| 748 |
Absolutely NO guarantee is provided about the resulting string being |
| 749 |
HTML safe. So NEVER mark safe the result of a ``strip_tags`` call without |
| 750 |
escaping it first, for example with :func:`~django.utils.html.escape`. |
| 751 |
|
| 752 |
For example:: |
| 753 |
|
| 754 |
strip_tags(value) |
| 755 |
|
| 756 |
If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"`` |
| 757 |
the return value will be ``"Joel is a slug"``. |
| 758 |
|
| 759 |
If you are looking for a more robust solution, consider using a third-party |
| 760 |
HTML sanitizing tool. |
| 761 |
|
| 762 |
.. function:: html_safe() |
| 763 |
|
| 764 |
The ``__html__()`` method on a class helps non-Django templates detect |
| 765 |
classes whose output doesn't require HTML escaping. |
| 766 |
|
| 767 |
This decorator defines the ``__html__()`` method on the decorated class |
| 768 |
by wrapping ``__str__()`` in :meth:`~django.utils.safestring.mark_safe`. |
| 769 |
Ensure the ``__str__()`` method does indeed return text that doesn't |
| 770 |
require HTML escaping. |
| 771 |
|
| 772 |
``django.utils.http`` |
| 773 |
===================== |
| 774 |
|
| 775 |
.. module:: django.utils.http |
| 776 |
:synopsis: HTTP helper functions. (URL encoding, cookie handling, ...) |
| 777 |
|
| 778 |
.. function:: urlencode(query, doseq=False) |
| 779 |
|
| 780 |
A version of Python's :func:`urllib.parse.urlencode` function that can |
| 781 |
operate on ``MultiValueDict`` and non-string values. |
| 782 |
|
| 783 |
.. function:: http_date(epoch_seconds=None) |
| 784 |
|
| 785 |
Formats the time to match the :rfc:`1123#section-5.2.14` date format as |
| 786 |
specified by HTTP :rfc:`9110#section-5.6.7`. |
| 787 |
|
| 788 |
Accepts a floating point number expressed in seconds since the epoch in |
| 789 |
UTC--such as that outputted by ``time.time()``. If set to ``None``, |
| 790 |
defaults to the current time. |
| 791 |
|
| 792 |
Outputs a string in the format ``Wdy, DD Mon YYYY HH:MM:SS GMT``. |
| 793 |
|
| 794 |
.. function:: content_disposition_header(as_attachment, filename) |
| 795 |
|
| 796 |
Constructs a ``Content-Disposition`` HTTP header value from the given |
| 797 |
``filename`` as specified by :rfc:`6266`. Returns ``None`` if |
| 798 |
``as_attachment`` is ``False`` and ``filename`` is ``None``, otherwise |
| 799 |
returns a string suitable for the ``Content-Disposition`` HTTP header. |
| 800 |
|
| 801 |
.. function:: base36_to_int(s) |
| 802 |
|
| 803 |
Converts a base 36 string to an integer. |
| 804 |
|
| 805 |
.. function:: int_to_base36(i) |
| 806 |
|
| 807 |
Converts a positive integer to a base 36 string. |
| 808 |
|
| 809 |
.. function:: urlsafe_base64_encode(s) |
| 810 |
|
| 811 |
Encodes a bytestring to a base64 string for use in URLs, stripping any |
| 812 |
trailing equal signs. |
| 813 |
|
| 814 |
.. function:: urlsafe_base64_decode(s) |
| 815 |
|
| 816 |
Decodes a base64 encoded string, adding back any trailing equal signs that |
| 817 |
might have been stripped. |
| 818 |
|
| 819 |
``django.utils.module_loading`` |
| 820 |
=============================== |
| 821 |
|
| 822 |
.. module:: django.utils.module_loading |
| 823 |
:synopsis: Functions for working with Python modules. |
| 824 |
|
| 825 |
Functions for working with Python modules. |
| 826 |
|
| 827 |
.. function:: import_string(dotted_path) |
| 828 |
|
| 829 |
Imports a dotted module path and returns the attribute/class designated by |
| 830 |
the last name in the path. Raises ``ImportError`` if the import failed. For |
| 831 |
example:: |
| 832 |
|
| 833 |
from django.utils.module_loading import import_string |
| 834 |
|
| 835 |
ValidationError = import_string("django.core.exceptions.ValidationError") |
| 836 |
|
| 837 |
is equivalent to:: |
| 838 |
|
| 839 |
from django.core.exceptions import ValidationError |
| 840 |
|
| 841 |
``django.utils.safestring`` |
| 842 |
=========================== |
| 843 |
|
| 844 |
.. module:: django.utils.safestring |
| 845 |
:synopsis: Functions and classes for working with strings that can be displayed safely without further escaping in HTML. |
| 846 |
|
| 847 |
Functions and classes for working with "safe strings": strings that can be |
| 848 |
displayed safely without further escaping in HTML. Marking something as a "safe |
| 849 |
string" means that the producer of the string has already turned characters |
| 850 |
that should not be interpreted by the HTML engine (e.g. '<') into the |
| 851 |
appropriate entities. |
| 852 |
|
| 853 |
.. class:: SafeString |
| 854 |
|
| 855 |
A ``str`` subclass that has been specifically marked as "safe" (requires no |
| 856 |
further escaping) for HTML output purposes. |
| 857 |
|
| 858 |
.. function:: mark_safe(s) |
| 859 |
|
| 860 |
Explicitly mark a string as safe for (HTML) output purposes. The returned |
| 861 |
object can be used everywhere a string is appropriate. |
| 862 |
|
| 863 |
Can be called multiple times on a single string. |
| 864 |
|
| 865 |
Can also be used as a decorator. |
| 866 |
|
| 867 |
For building up fragments of HTML, you should normally be using |
| 868 |
:func:`django.utils.html.format_html` instead. |
| 869 |
|
| 870 |
String marked safe will become unsafe again if modified. For example: |
| 871 |
|
| 872 |
.. code-block:: pycon |
| 873 |
|
| 874 |
>>> mystr = "<b>Hello World</b> " |
| 875 |
>>> mystr = mark_safe(mystr) |
| 876 |
>>> type(mystr) |
| 877 |
<class 'django.utils.safestring.SafeString'> |
| 878 |
|
| 879 |
>>> mystr = mystr.strip() # removing whitespace |
| 880 |
>>> type(mystr) |
| 881 |
<type 'str'> |
| 882 |
|
| 883 |
``django.utils.text`` |
| 884 |
===================== |
| 885 |
|
| 886 |
.. module:: django.utils.text |
| 887 |
:synopsis: Text manipulation. |
| 888 |
|
| 889 |
.. function:: format_lazy(format_string, *args, **kwargs) |
| 890 |
|
| 891 |
A version of :meth:`str.format` for when ``format_string``, ``args``, |
| 892 |
and/or ``kwargs`` contain lazy objects. The first argument is the string to |
| 893 |
be formatted. For example:: |
| 894 |
|
| 895 |
from django.utils.text import format_lazy |
| 896 |
from django.utils.translation import pgettext_lazy |
| 897 |
|
| 898 |
urlpatterns = [ |
| 899 |
path( |
| 900 |
format_lazy("{person}/<int:pk>/", person=pgettext_lazy("URL", "person")), |
| 901 |
PersonDetailView.as_view(), |
| 902 |
), |
| 903 |
] |
| 904 |
|
| 905 |
This example allows translators to translate part of the URL. If "person" |
| 906 |
is translated to "persona", the regular expression will match |
| 907 |
``persona/(?P<pk>\d+)/$``, e.g. ``persona/5/``. |
| 908 |
|
| 909 |
.. function:: slugify(value, allow_unicode=False) |
| 910 |
|
| 911 |
Converts a string to a URL slug by: |
| 912 |
|
| 913 |
#. Converting to ASCII if ``allow_unicode`` is ``False`` (the default). |
| 914 |
#. Converting to lowercase. |
| 915 |
#. Removing characters that aren't alphanumerics, underscores, hyphens, or |
| 916 |
whitespace. |
| 917 |
#. Replacing any whitespace or repeated dashes with single dashes. |
| 918 |
#. Removing leading and trailing whitespace, dashes, and underscores. |
| 919 |
|
| 920 |
For example: |
| 921 |
|
| 922 |
.. code-block:: pycon |
| 923 |
|
| 924 |
>>> slugify(" Joel is a slug ") |
| 925 |
'joel-is-a-slug' |
| 926 |
|
| 927 |
If you want to allow Unicode characters, pass ``allow_unicode=True``. For |
| 928 |
example: |
| 929 |
|
| 930 |
.. code-block:: pycon |
| 931 |
|
| 932 |
>>> slugify("你好 World", allow_unicode=True) |
| 933 |
'你好-world' |
| 934 |
|
| 935 |
.. _time-zone-selection-functions: |
| 936 |
|
| 937 |
``django.utils.timezone`` |
| 938 |
========================= |
| 939 |
|
| 940 |
.. module:: django.utils.timezone |
| 941 |
:synopsis: Timezone support. |
| 942 |
|
| 943 |
.. function:: get_fixed_timezone(offset) |
| 944 |
|
| 945 |
Returns a :class:`~datetime.tzinfo` instance that represents a time zone |
| 946 |
with a fixed offset from UTC. |
| 947 |
|
| 948 |
``offset`` is a :class:`datetime.timedelta` or an integer number of |
| 949 |
minutes. Use positive values for time zones east of UTC and negative |
| 950 |
values for west of UTC. |
| 951 |
|
| 952 |
.. function:: get_default_timezone() |
| 953 |
|
| 954 |
Returns a :class:`~datetime.tzinfo` instance that represents the |
| 955 |
:ref:`default time zone <default-current-time-zone>`. |
| 956 |
|
| 957 |
.. function:: get_default_timezone_name() |
| 958 |
|
| 959 |
Returns the name of the :ref:`default time zone |
| 960 |
<default-current-time-zone>`. |
| 961 |
|
| 962 |
.. function:: get_current_timezone() |
| 963 |
|
| 964 |
Returns a :class:`~datetime.tzinfo` instance that represents the |
| 965 |
:ref:`current time zone <default-current-time-zone>`. |
| 966 |
|
| 967 |
.. function:: get_current_timezone_name() |
| 968 |
|
| 969 |
Returns the name of the :ref:`current time zone |
| 970 |
<default-current-time-zone>`. |
| 971 |
|
| 972 |
.. function:: activate(timezone) |
| 973 |
|
| 974 |
Sets the :ref:`current time zone <default-current-time-zone>`. The |
| 975 |
``timezone`` argument must be an instance of a :class:`~datetime.tzinfo` |
| 976 |
subclass or a time zone name. |
| 977 |
|
| 978 |
.. function:: deactivate() |
| 979 |
|
| 980 |
Unsets the :ref:`current time zone <default-current-time-zone>`. |
| 981 |
|
| 982 |
.. function:: override(timezone) |
| 983 |
|
| 984 |
This is a Python context manager that sets the :ref:`current time zone |
| 985 |
<default-current-time-zone>` on entry with :func:`activate()`, and restores |
| 986 |
the previously active time zone on exit. If the ``timezone`` argument is |
| 987 |
``None``, the :ref:`current time zone <default-current-time-zone>` is unset |
| 988 |
on entry with :func:`deactivate()` instead. |
| 989 |
|
| 990 |
``override`` is also usable as a function decorator. |
| 991 |
|
| 992 |
.. function:: localtime(value=None, timezone=None) |
| 993 |
|
| 994 |
Converts an aware :class:`~datetime.datetime` to a different time zone, |
| 995 |
by default the :ref:`current time zone <default-current-time-zone>`. |
| 996 |
|
| 997 |
When ``value`` is omitted, it defaults to :func:`now`. |
| 998 |
|
| 999 |
This function doesn't work on naive datetimes; use :func:`make_aware` |
| 1000 |
instead. |
| 1001 |
|
| 1002 |
.. function:: localdate(value=None, timezone=None) |
| 1003 |
|
| 1004 |
Uses :func:`localtime` to convert an aware :class:`~datetime.datetime` to a |
| 1005 |
:meth:`~datetime.datetime.date` in a different time zone, by default the |
| 1006 |
:ref:`current time zone <default-current-time-zone>`. |
| 1007 |
|
| 1008 |
When ``value`` is omitted, it defaults to :func:`now`. |
| 1009 |
|
| 1010 |
This function doesn't work on naive datetimes. |
| 1011 |
|
| 1012 |
.. function:: now() |
| 1013 |
|
| 1014 |
Returns a :class:`~datetime.datetime` that represents the |
| 1015 |
current point in time. Exactly what's returned depends on the value of |
| 1016 |
:setting:`USE_TZ`: |
| 1017 |
|
| 1018 |
* If :setting:`USE_TZ` is ``False``, this will be a |
| 1019 |
:ref:`naive <naive_vs_aware_datetimes>` datetime (i.e. a datetime |
| 1020 |
without an associated timezone) that represents the current time |
| 1021 |
in the system's local timezone. |
| 1022 |
|
| 1023 |
* If :setting:`USE_TZ` is ``True``, this will be an |
| 1024 |
:ref:`aware <naive_vs_aware_datetimes>` datetime representing the |
| 1025 |
current time in UTC. Note that :func:`now` will always return |
| 1026 |
times in UTC regardless of the value of :setting:`TIME_ZONE`; |
| 1027 |
you can use :func:`localtime` to get the time in the current time zone. |
| 1028 |
|
| 1029 |
.. function:: is_aware(value) |
| 1030 |
|
| 1031 |
Returns ``True`` if ``value`` is aware, ``False`` if it is naive. This |
| 1032 |
function assumes that ``value`` is a :class:`~datetime.datetime`. |
| 1033 |
|
| 1034 |
.. function:: is_naive(value) |
| 1035 |
|
| 1036 |
Returns ``True`` if ``value`` is naive, ``False`` if it is aware. This |
| 1037 |
function assumes that ``value`` is a :class:`~datetime.datetime`. |
| 1038 |
|
| 1039 |
.. function:: make_aware(value, timezone=None) |
| 1040 |
|
| 1041 |
Returns an aware :class:`~datetime.datetime` that represents the same |
| 1042 |
point in time as ``value`` in ``timezone``, ``value`` being a naive |
| 1043 |
:class:`~datetime.datetime`. If ``timezone`` is set to ``None``, it |
| 1044 |
defaults to the :ref:`current time zone <default-current-time-zone>`. |
| 1045 |
|
| 1046 |
.. function:: make_naive(value, timezone=None) |
| 1047 |
|
| 1048 |
Returns a naive :class:`~datetime.datetime` that represents in |
| 1049 |
``timezone`` the same point in time as ``value``, ``value`` being an |
| 1050 |
aware :class:`~datetime.datetime`. If ``timezone`` is set to ``None``, it |
| 1051 |
defaults to the :ref:`current time zone <default-current-time-zone>`. |
| 1052 |
|
| 1053 |
``django.utils.translation`` |
| 1054 |
============================ |
| 1055 |
|
| 1056 |
.. module:: django.utils.translation |
| 1057 |
:synopsis: Internationalization support. |
| 1058 |
|
| 1059 |
For a complete discussion on the usage of the following see the |
| 1060 |
:doc:`translation documentation </topics/i18n/translation>`. |
| 1061 |
|
| 1062 |
.. function:: gettext(message) |
| 1063 |
|
| 1064 |
Translates ``message`` and returns it as a string. |
| 1065 |
|
| 1066 |
.. function:: pgettext(context, message) |
| 1067 |
|
| 1068 |
Translates ``message`` given the ``context`` and returns it as a string. |
| 1069 |
|
| 1070 |
For more information, see :ref:`contextual-markers`. |
| 1071 |
|
| 1072 |
.. function:: gettext_lazy(message) |
| 1073 |
.. function:: pgettext_lazy(context, message) |
| 1074 |
|
| 1075 |
Same as the non-lazy versions above, but using lazy execution. |
| 1076 |
|
| 1077 |
See :ref:`lazy translations documentation <lazy-translations>`. |
| 1078 |
|
| 1079 |
.. function:: gettext_noop(message) |
| 1080 |
|
| 1081 |
Marks strings for translation but doesn't translate them now. This can be |
| 1082 |
used to store strings in global variables that should stay in the base |
| 1083 |
language (because they might be used externally) and will be translated |
| 1084 |
later. |
| 1085 |
|
| 1086 |
.. function:: ngettext(singular, plural, number) |
| 1087 |
|
| 1088 |
Translates ``singular`` and ``plural`` and returns the appropriate string |
| 1089 |
based on ``number``. |
| 1090 |
|
| 1091 |
.. function:: npgettext(context, singular, plural, number) |
| 1092 |
|
| 1093 |
Translates ``singular`` and ``plural`` and returns the appropriate string |
| 1094 |
based on ``number`` and the ``context``. |
| 1095 |
|
| 1096 |
.. function:: ngettext_lazy(singular, plural, number) |
| 1097 |
.. function:: npgettext_lazy(context, singular, plural, number) |
| 1098 |
|
| 1099 |
Same as the non-lazy versions above, but using lazy execution. |
| 1100 |
|
| 1101 |
See :ref:`lazy translations documentation <lazy-translations>`. |
| 1102 |
|
| 1103 |
.. function:: activate(language) |
| 1104 |
|
| 1105 |
Fetches the translation object for a given language and activates it as |
| 1106 |
the current translation object for the current thread. |
| 1107 |
|
| 1108 |
.. function:: deactivate() |
| 1109 |
|
| 1110 |
Deactivates the currently active translation object so that further _ calls |
| 1111 |
will resolve against the default translation object, again. |
| 1112 |
|
| 1113 |
.. function:: deactivate_all() |
| 1114 |
|
| 1115 |
Makes the active translation object a ``NullTranslations()`` instance. |
| 1116 |
This is useful when we want delayed translations to appear as the original |
| 1117 |
string for some reason. |
| 1118 |
|
| 1119 |
.. function:: override(language, deactivate=False) |
| 1120 |
|
| 1121 |
A Python context manager that uses |
| 1122 |
:func:`django.utils.translation.activate` to fetch the translation object |
| 1123 |
for a given language, activates it as the translation object for the |
| 1124 |
current thread and reactivates the previous active language on exit. |
| 1125 |
Optionally, it can deactivate the temporary translation on exit with |
| 1126 |
:func:`django.utils.translation.deactivate` if the ``deactivate`` argument |
| 1127 |
is ``True``. If you pass ``None`` as the language argument, a |
| 1128 |
``NullTranslations()`` instance is activated within the context. |
| 1129 |
|
| 1130 |
``override`` is also usable as a function decorator. |
| 1131 |
|
| 1132 |
.. function:: check_for_language(lang_code) |
| 1133 |
|
| 1134 |
Checks whether there is a global language file for the given language |
| 1135 |
code (e.g. 'fr', 'pt_BR'). This is used to decide whether a user-provided |
| 1136 |
language is available. |
| 1137 |
|
| 1138 |
.. function:: get_language() |
| 1139 |
|
| 1140 |
Returns the currently selected language code. Returns ``None`` if |
| 1141 |
translations are temporarily deactivated (by :func:`deactivate_all()` or |
| 1142 |
when ``None`` is passed to :func:`override()`). |
| 1143 |
|
| 1144 |
.. function:: get_language_bidi() |
| 1145 |
|
| 1146 |
Returns selected language's BiDi layout: |
| 1147 |
|
| 1148 |
* ``False`` = left-to-right layout |
| 1149 |
* ``True`` = right-to-left layout |
| 1150 |
|
| 1151 |
.. function:: get_language_from_request(request, check_path=False) |
| 1152 |
|
| 1153 |
Analyzes the request to find what language the user wants the system to |
| 1154 |
show. Only languages listed in settings.LANGUAGES are taken into account. |
| 1155 |
If the user requests a sublanguage where we have a main language, we send |
| 1156 |
out the main language. |
| 1157 |
|
| 1158 |
If ``check_path`` is ``True``, the function first checks the requested URL |
| 1159 |
for whether its path begins with a language code listed in the |
| 1160 |
:setting:`LANGUAGES` setting. |
| 1161 |
|
| 1162 |
.. function:: get_supported_language_variant(lang_code, strict=False) |
| 1163 |
|
| 1164 |
Returns ``lang_code`` if it's in the :setting:`LANGUAGES` setting, possibly |
| 1165 |
selecting a more generic variant. For example, ``'es'`` is returned if |
| 1166 |
``lang_code`` is ``'es-ar'`` and ``'es'`` is in :setting:`LANGUAGES` but |
| 1167 |
``'es-ar'`` isn't. |
| 1168 |
|
| 1169 |
``lang_code`` has a maximum accepted length of 500 characters. A |
| 1170 |
:exc:`LookupError` is raised if ``lang_code`` exceeds this limit and |
| 1171 |
``strict`` is ``True``, or if there is no generic variant and ``strict`` |
| 1172 |
is ``False``. |
| 1173 |
|
| 1174 |
If ``strict`` is ``False`` (the default), a country-specific variant may |
| 1175 |
be returned when neither the language code nor its generic variant is found. |
| 1176 |
For example, if only ``'es-co'`` is in :setting:`LANGUAGES`, that's |
| 1177 |
returned for ``lang_code``\s like ``'es'`` and ``'es-ar'``. Those matches |
| 1178 |
aren't returned if ``strict=True``. |
| 1179 |
|
| 1180 |
Raises :exc:`LookupError` if nothing is found. |
| 1181 |
|
| 1182 |
.. versionchanged:: 4.2.15 |
| 1183 |
|
| 1184 |
In older versions, ``lang_code`` values over 500 characters were |
| 1185 |
processed without raising a :exc:`LookupError`. |
| 1186 |
|
| 1187 |
.. function:: to_locale(language) |
| 1188 |
|
| 1189 |
Turns a language name (en-us) into a locale name (en_US). |
| 1190 |
|
| 1191 |
.. function:: templatize(src) |
| 1192 |
|
| 1193 |
Turns a Django template into something that is understood by ``xgettext``. |
| 1194 |
It does so by translating the Django translation tags into standard |
| 1195 |
``gettext`` function invocations. |