utils.txt 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  1. ============
  2. Django Utils
  3. ============
  4. .. module:: django.utils
  5. :synopsis: Django's built-in utilities.
  6. This document covers all stable modules in ``django.utils``. Most of the
  7. modules in ``django.utils`` are designed for internal use and only the
  8. following parts can be considered stable and thus backwards compatible as per
  9. the :ref:`internal release deprecation policy <internal-release-deprecation-policy>`.
  10. ``django.utils.cache``
  11. ======================
  12. .. module:: django.utils.cache
  13. :synopsis: Helper functions for controlling caching.
  14. This module contains helper functions for controlling HTTP caching. It does so
  15. by managing the ``Vary`` header of responses. It includes functions to patch
  16. the header of response objects directly and decorators that change functions to
  17. do that header-patching themselves.
  18. For information on the ``Vary`` header, see :rfc:`7231#section-7.1.4`.
  19. Essentially, the ``Vary`` HTTP header defines which headers a cache should take
  20. into account when building its cache key. Requests with the same path but
  21. different header content for headers named in ``Vary`` need to get different
  22. cache keys to prevent delivery of wrong content.
  23. For example, :doc:`internationalization </topics/i18n/index>` middleware would
  24. need to distinguish caches by the ``Accept-language`` header.
  25. .. function:: patch_cache_control(response, **kwargs)
  26. This function patches the ``Cache-Control`` header by adding all keyword
  27. arguments to it. The transformation is as follows:
  28. * All keyword parameter names are turned to lowercase, and underscores
  29. are converted to hyphens.
  30. * If the value of a parameter is ``True`` (exactly ``True``, not just a
  31. true value), only the parameter name is added to the header.
  32. * All other parameters are added with their value, after applying
  33. ``str()`` to it.
  34. .. versionchanged:: 3.1
  35. Support for multiple field names in the ``no-cache`` directive was
  36. added.
  37. .. function:: get_max_age(response)
  38. Returns the max-age from the response Cache-Control header as an integer
  39. (or ``None`` if it wasn't found or wasn't an integer).
  40. .. function:: patch_response_headers(response, cache_timeout=None)
  41. Adds some useful headers to the given ``HttpResponse`` object:
  42. * ``Expires``
  43. * ``Cache-Control``
  44. Each header is only added if it isn't already set.
  45. ``cache_timeout`` is in seconds. The :setting:`CACHE_MIDDLEWARE_SECONDS`
  46. setting is used by default.
  47. .. function:: add_never_cache_headers(response)
  48. Adds a ``Cache-Control: max-age=0, no-cache, no-store, must-revalidate,
  49. private`` header to a response to indicate that a page should never be
  50. cached.
  51. .. versionchanged:: 3.0
  52. ``private`` directive was added.
  53. .. function:: patch_vary_headers(response, newheaders)
  54. Adds (or updates) the ``Vary`` header in the given ``HttpResponse`` object.
  55. ``newheaders`` is a list of header names that should be in ``Vary``. If
  56. headers contains an asterisk, then ``Vary`` header will consist of a single
  57. asterisk ``'*'``. Otherwise, existing headers in ``Vary`` aren't removed.
  58. .. versionchanged:: 3.0
  59. Handling an asterisk ``'*'`` according to :rfc:`7231#section-7.1.4` was
  60. added.
  61. .. function:: get_cache_key(request, key_prefix=None)
  62. Returns a cache key based on the request path. It can be used in the
  63. request phase because it pulls the list of headers to take into account
  64. from the global path registry and uses those to build a cache key to
  65. check against.
  66. If there is no headerlist stored, the page needs to be rebuilt, so this
  67. function returns ``None``.
  68. .. function:: learn_cache_key(request, response, cache_timeout=None, key_prefix=None)
  69. Learns what headers to take into account for some request path from the
  70. response object. It stores those headers in a global path registry so that
  71. later access to that path will know what headers to take into account
  72. without building the response object itself. The headers are named in
  73. the ``Vary`` header of the response, but we want to prevent response
  74. generation.
  75. The list of headers to use for cache key generation is stored in the same
  76. cache as the pages themselves. If the cache ages some data out of the
  77. cache, this means that we have to build the response once to get at the
  78. Vary header and so at the list of headers to use for the cache key.
  79. ``django.utils.dateparse``
  80. ==========================
  81. .. module:: django.utils.dateparse
  82. :synopsis: Functions to parse strings to datetime objects.
  83. The functions defined in this module share the following properties:
  84. - They accept strings in ISO 8601 date/time formats (or some close
  85. alternatives) and return objects from the corresponding classes in Python's
  86. :mod:`datetime` module.
  87. - They raise :exc:`ValueError` if their input is well formatted but isn't a
  88. valid date or time.
  89. - They return ``None`` if it isn't well formatted at all.
  90. - They accept up to picosecond resolution in input, but they truncate it to
  91. microseconds, since that's what Python supports.
  92. .. function:: parse_date(value)
  93. Parses a string and returns a :class:`datetime.date`.
  94. .. function:: parse_time(value)
  95. Parses a string and returns a :class:`datetime.time`.
  96. UTC offsets aren't supported; if ``value`` describes one, the result is
  97. ``None``.
  98. .. function:: parse_datetime(value)
  99. Parses a string and returns a :class:`datetime.datetime`.
  100. UTC offsets are supported; if ``value`` describes one, the result's
  101. ``tzinfo`` attribute is a :class:`datetime.timezone` instance.
  102. .. function:: parse_duration(value)
  103. Parses a string and returns a :class:`datetime.timedelta`.
  104. Expects data in the format ``"DD HH:MM:SS.uuuuuu"`` or as specified by ISO
  105. 8601 (e.g. ``P4DT1H15M20S`` which is equivalent to ``4 1:15:20``) or
  106. PostgreSQL's day-time interval format (e.g. ``3 days 04:05:06``).
  107. ``django.utils.decorators``
  108. ===========================
  109. .. module:: django.utils.decorators
  110. :synopsis: Functions that help with creating decorators for views.
  111. .. function:: method_decorator(decorator, name='')
  112. Converts a function decorator into a method decorator. It can be used to
  113. decorate methods or classes; in the latter case, ``name`` is the name
  114. of the method to be decorated and is required.
  115. ``decorator`` may also be a list or tuple of functions. They are wrapped
  116. in reverse order so that the call order is the order in which the functions
  117. appear in the list/tuple.
  118. See :ref:`decorating class based views <decorating-class-based-views>` for
  119. example usage.
  120. .. function:: decorator_from_middleware(middleware_class)
  121. Given a middleware class, returns a view decorator. This lets you use
  122. middleware functionality on a per-view basis. The middleware is created
  123. with no params passed.
  124. It assumes middleware that's compatible with the old style of Django 1.9
  125. and earlier (having methods like ``process_request()``,
  126. ``process_exception()``, and ``process_response()``).
  127. .. function:: decorator_from_middleware_with_args(middleware_class)
  128. Like ``decorator_from_middleware``, but returns a function
  129. that accepts the arguments to be passed to the middleware_class.
  130. For example, the :func:`~django.views.decorators.cache.cache_page`
  131. decorator is created from the ``CacheMiddleware`` like this::
  132. cache_page = decorator_from_middleware_with_args(CacheMiddleware)
  133. @cache_page(3600)
  134. def my_view(request):
  135. pass
  136. ``django.utils.encoding``
  137. =========================
  138. .. module:: django.utils.encoding
  139. :synopsis: A series of helper functions to manage character encoding.
  140. .. function:: smart_str(s, encoding='utf-8', strings_only=False, errors='strict')
  141. Returns a ``str`` object representing arbitrary object ``s``. Treats
  142. bytestrings using the ``encoding`` codec.
  143. If ``strings_only`` is ``True``, don't convert (some) non-string-like
  144. objects.
  145. .. function:: is_protected_type(obj)
  146. Determine if the object instance is of a protected type.
  147. Objects of protected types are preserved as-is when passed to
  148. ``force_str(strings_only=True)``.
  149. .. function:: force_str(s, encoding='utf-8', strings_only=False, errors='strict')
  150. Similar to ``smart_str()``, except that lazy instances are resolved to
  151. strings, rather than kept as lazy objects.
  152. If ``strings_only`` is ``True``, don't convert (some) non-string-like
  153. objects.
  154. .. function:: smart_bytes(s, encoding='utf-8', strings_only=False, errors='strict')
  155. Returns a bytestring version of arbitrary object ``s``, encoded as
  156. specified in ``encoding``.
  157. If ``strings_only`` is ``True``, don't convert (some) non-string-like
  158. objects.
  159. .. function:: force_bytes(s, encoding='utf-8', strings_only=False, errors='strict')
  160. Similar to ``smart_bytes``, except that lazy instances are resolved to
  161. bytestrings, rather than kept as lazy objects.
  162. If ``strings_only`` is ``True``, don't convert (some) non-string-like
  163. objects.
  164. .. function:: smart_text(s, encoding='utf-8', strings_only=False, errors='strict')
  165. .. deprecated:: 3.0
  166. Alias of :func:`force_str` for backwards compatibility, especially in code
  167. that supports Python 2.
  168. .. function:: force_text(s, encoding='utf-8', strings_only=False, errors='strict')
  169. .. deprecated:: 3.0
  170. Alias of :func:`force_str` for backwards compatibility, especially in code
  171. that supports Python 2.
  172. .. function:: iri_to_uri(iri)
  173. Convert an Internationalized Resource Identifier (IRI) portion to a URI
  174. portion that is suitable for inclusion in a URL.
  175. This is the algorithm from section 3.1 of :rfc:`3987#section-3.1`, slightly
  176. simplified since the input is assumed to be a string rather than an
  177. arbitrary byte stream.
  178. Takes an IRI (string or UTF-8 bytes) and returns a string containing the
  179. encoded result.
  180. .. function:: uri_to_iri(uri)
  181. Converts a Uniform Resource Identifier into an Internationalized Resource
  182. Identifier.
  183. This is an algorithm from section 3.2 of :rfc:`3987#section-3.2`.
  184. Takes a URI in ASCII bytes and returns a string containing the encoded
  185. result.
  186. .. function:: filepath_to_uri(path)
  187. Convert a file system path to a URI portion that is suitable for inclusion
  188. in a URL. The path is assumed to be either UTF-8 bytes, string, or a
  189. :class:`~pathlib.Path`.
  190. This method will encode certain characters that would normally be
  191. recognized as special characters for URIs. Note that this method does not
  192. encode the ' character, as it is a valid character within URIs. See
  193. ``encodeURIComponent()`` JavaScript function for more details.
  194. Returns an ASCII string containing the encoded result.
  195. .. versionchanged:: 3.1
  196. Support for :class:`pathlib.Path` ``path`` was added.
  197. .. function:: escape_uri_path(path)
  198. Escapes the unsafe characters from the path portion of a Uniform Resource
  199. Identifier (URI).
  200. ``django.utils.feedgenerator``
  201. ==============================
  202. .. module:: django.utils.feedgenerator
  203. :synopsis: Syndication feed generation library -- used for generating RSS, etc.
  204. Sample usage::
  205. >>> from django.utils import feedgenerator
  206. >>> feed = feedgenerator.Rss201rev2Feed(
  207. ... title="Poynter E-Media Tidbits",
  208. ... link="http://www.poynter.org/column.asp?id=31",
  209. ... description="A group Weblog by the sharpest minds in online media/journalism/publishing.",
  210. ... language="en",
  211. ... )
  212. >>> feed.add_item(
  213. ... title="Hello",
  214. ... link="http://www.holovaty.com/test/",
  215. ... description="Testing.",
  216. ... )
  217. >>> with open('test.rss', 'w') as fp:
  218. ... feed.write(fp, 'utf-8')
  219. For simplifying the selection of a generator use ``feedgenerator.DefaultFeed``
  220. which is currently ``Rss201rev2Feed``
  221. For definitions of the different versions of RSS, see:
  222. https://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004/02/04/incompatible-rss
  223. .. function:: get_tag_uri(url, date)
  224. Creates a TagURI.
  225. See https://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
  226. ``SyndicationFeed``
  227. -------------------
  228. .. class:: SyndicationFeed
  229. Base class for all syndication feeds. Subclasses should provide write().
  230. .. 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, **kwargs)
  231. Initialize the feed with the given dictionary of metadata, which applies
  232. to the entire feed.
  233. Any extra keyword arguments you pass to ``__init__`` will be stored in
  234. ``self.feed``.
  235. All parameters should be strings, except ``categories``, which should
  236. be a sequence of strings.
  237. .. 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)
  238. Adds an item to the feed. All args are expected to be strings except
  239. ``pubdate`` and ``updateddate``, which are ``datetime.datetime``
  240. objects, and ``enclosures``, which is a list of ``Enclosure`` instances.
  241. .. method:: num_items()
  242. .. method:: root_attributes()
  243. Return extra attributes to place on the root (i.e. feed/channel)
  244. element. Called from ``write()``.
  245. .. method:: add_root_elements(handler)
  246. Add elements in the root (i.e. feed/channel) element.
  247. Called from ``write()``.
  248. .. method:: item_attributes(item)
  249. Return extra attributes to place on each item (i.e. item/entry)
  250. element.
  251. .. method:: add_item_elements(handler, item)
  252. Add elements on each item (i.e. item/entry) element.
  253. .. method:: write(outfile, encoding)
  254. Outputs the feed in the given encoding to ``outfile``, which is a
  255. file-like object. Subclasses should override this.
  256. .. method:: writeString(encoding)
  257. Returns the feed in the given encoding as a string.
  258. .. method:: latest_post_date()
  259. Returns the latest ``pubdate`` or ``updateddate`` for all items in the
  260. feed. If no items have either of these attributes this returns the
  261. current UTC date/time.
  262. ``Enclosure``
  263. -------------
  264. .. class:: Enclosure
  265. Represents an RSS enclosure
  266. ``RssFeed``
  267. -----------
  268. .. class:: RssFeed(SyndicationFeed)
  269. ``Rss201rev2Feed``
  270. ------------------
  271. .. class:: Rss201rev2Feed(RssFeed)
  272. Spec: https://cyber.harvard.edu/rss/rss.html
  273. ``RssUserland091Feed``
  274. ----------------------
  275. .. class:: RssUserland091Feed(RssFeed)
  276. Spec: http://backend.userland.com/rss091
  277. ``Atom1Feed``
  278. -------------
  279. .. class:: Atom1Feed(SyndicationFeed)
  280. Spec: https://tools.ietf.org/html/rfc4287
  281. ``django.utils.functional``
  282. ===========================
  283. .. module:: django.utils.functional
  284. :synopsis: Functional programming tools.
  285. .. class:: cached_property(func, name=None)
  286. The ``@cached_property`` decorator caches the result of a method with a
  287. single ``self`` argument as a property. The cached result will persist
  288. as long as the instance does, so if the instance is passed around and the
  289. function subsequently invoked, the cached result will be returned.
  290. Consider a typical case, where a view might need to call a model's method
  291. to perform some computation, before placing the model instance into the
  292. context, where the template might invoke the method once more::
  293. # the model
  294. class Person(models.Model):
  295. def friends(self):
  296. # expensive computation
  297. ...
  298. return friends
  299. # in the view:
  300. if person.friends():
  301. ...
  302. And in the template you would have:
  303. .. code-block:: html+django
  304. {% for friend in person.friends %}
  305. Here, ``friends()`` will be called twice. Since the instance ``person`` in
  306. the view and the template are the same, decorating the ``friends()`` method
  307. with ``@cached_property`` can avoid that::
  308. from django.utils.functional import cached_property
  309. class Person(models.Model):
  310. @cached_property
  311. def friends(self):
  312. ...
  313. Note that as the method is now a property, in Python code it will need to
  314. be accessed appropriately::
  315. # in the view:
  316. if person.friends:
  317. ...
  318. The cached value can be treated like an ordinary attribute of the instance::
  319. # clear it, requiring re-computation next time it's called
  320. del person.friends # or delattr(person, "friends")
  321. # set a value manually, that will persist on the instance until cleared
  322. person.friends = ["Huckleberry Finn", "Tom Sawyer"]
  323. Because of the way the :py:ref:`descriptor protocol
  324. <descriptor-invocation>` works, using ``del`` (or ``delattr``) on a
  325. ``cached_property`` that hasn't been accessed raises ``AttributeError``.
  326. As well as offering potential performance advantages, ``@cached_property``
  327. can ensure that an attribute's value does not change unexpectedly over the
  328. life of an instance. This could occur with a method whose computation is
  329. based on ``datetime.now()``, or if a change were saved to the database by
  330. some other process in the brief interval between subsequent invocations of
  331. a method on the same instance.
  332. You can make cached properties of methods. For example, if you had an
  333. expensive ``get_friends()`` method and wanted to allow calling it without
  334. retrieving the cached value, you could write::
  335. friends = cached_property(get_friends, name='friends')
  336. You only need the ``name`` argument for Python < 3.6 support.
  337. While ``person.get_friends()`` will recompute the friends on each call, the
  338. value of the cached property will persist until you delete it as described
  339. above::
  340. x = person.friends # calls first time
  341. y = person.get_friends() # calls again
  342. z = person.friends # does not call
  343. x is z # is True
  344. .. function:: keep_lazy(func, *resultclasses)
  345. Django offers many utility functions (particularly in ``django.utils``)
  346. that take a string as their first argument and do something to that string.
  347. These functions are used by template filters as well as directly in other
  348. code.
  349. If you write your own similar functions and deal with translations, you'll
  350. face the problem of what to do when the first argument is a lazy
  351. translation object. You don't want to convert it to a string immediately,
  352. because you might be using this function outside of a view (and hence the
  353. current thread's locale setting will not be correct).
  354. For cases like this, use the ``django.utils.functional.keep_lazy()``
  355. decorator. It modifies the function so that *if* it's called with a lazy
  356. translation as one of its arguments, the function evaluation is delayed
  357. until it needs to be converted to a string.
  358. For example::
  359. from django.utils.functional import keep_lazy, keep_lazy_text
  360. def fancy_utility_function(s, ...):
  361. # Do some conversion on string 's'
  362. ...
  363. fancy_utility_function = keep_lazy(str)(fancy_utility_function)
  364. # Or more succinctly:
  365. @keep_lazy(str)
  366. def fancy_utility_function(s, ...):
  367. ...
  368. The ``keep_lazy()`` decorator takes a number of extra arguments (``*args``)
  369. specifying the type(s) that the original function can return. A common
  370. use case is to have functions that return text. For these, you can pass the
  371. ``str`` type to ``keep_lazy`` (or use the :func:`keep_lazy_text` decorator
  372. described in the next section).
  373. Using this decorator means you can write your function and assume that the
  374. input is a proper string, then add support for lazy translation objects at
  375. the end.
  376. .. function:: keep_lazy_text(func)
  377. A shortcut for ``keep_lazy(str)(func)``.
  378. If you have a function that returns text and you want to be able to take
  379. lazy arguments while delaying their evaluation, you can use this
  380. decorator::
  381. from django.utils.functional import keep_lazy, keep_lazy_text
  382. # Our previous example was:
  383. @keep_lazy(str)
  384. def fancy_utility_function(s, ...):
  385. ...
  386. # Which can be rewritten as:
  387. @keep_lazy_text
  388. def fancy_utility_function(s, ...):
  389. ...
  390. ``django.utils.html``
  391. =====================
  392. .. module:: django.utils.html
  393. :synopsis: HTML helper functions
  394. Usually you should build up HTML using Django's templates to make use of its
  395. autoescape mechanism, using the utilities in :mod:`django.utils.safestring`
  396. where appropriate. This module provides some additional low level utilities for
  397. escaping HTML.
  398. .. function:: escape(text)
  399. Returns the given text with ampersands, quotes and angle brackets encoded
  400. for use in HTML. The input is first coerced to a string and the output has
  401. :func:`~django.utils.safestring.mark_safe` applied.
  402. .. versionchanged:: 3.0
  403. In older versions, ``'`` is converted to its decimal code ``&#39;``
  404. instead of the equivalent hex code ``&#x27;``.
  405. .. function:: conditional_escape(text)
  406. Similar to ``escape()``, except that it doesn't operate on pre-escaped
  407. strings, so it will not double escape.
  408. .. function:: format_html(format_string, *args, **kwargs)
  409. This is similar to :meth:`str.format`, except that it is appropriate for
  410. building up HTML fragments. All args and kwargs are passed through
  411. :func:`conditional_escape` before being passed to ``str.format()``.
  412. For the case of building up small HTML fragments, this function is to be
  413. preferred over string interpolation using ``%`` or ``str.format()``
  414. directly, because it applies escaping to all arguments - just like the
  415. template system applies escaping by default.
  416. So, instead of writing::
  417. mark_safe("%s <b>%s</b> %s" % (
  418. some_html,
  419. escape(some_text),
  420. escape(some_other_text),
  421. ))
  422. You should instead use::
  423. format_html("{} <b>{}</b> {}",
  424. mark_safe(some_html),
  425. some_text,
  426. some_other_text,
  427. )
  428. This has the advantage that you don't need to apply :func:`escape` to each
  429. argument and risk a bug and an XSS vulnerability if you forget one.
  430. Note that although this function uses ``str.format()`` to do the
  431. interpolation, some of the formatting options provided by ``str.format()``
  432. (e.g. number formatting) will not work, since all arguments are passed
  433. through :func:`conditional_escape` which (ultimately) calls
  434. :func:`~django.utils.encoding.force_str` on the values.
  435. .. function:: format_html_join(sep, format_string, args_generator)
  436. A wrapper of :func:`format_html`, for the common case of a group of
  437. arguments that need to be formatted using the same format string, and then
  438. joined using ``sep``. ``sep`` is also passed through
  439. :func:`conditional_escape`.
  440. ``args_generator`` should be an iterator that returns the sequence of
  441. ``args`` that will be passed to :func:`format_html`. For example::
  442. format_html_join(
  443. '\n', "<li>{} {}</li>",
  444. ((u.first_name, u.last_name) for u in users)
  445. )
  446. .. function:: strip_tags(value)
  447. Tries to remove anything that looks like an HTML tag from the string, that
  448. is anything contained within ``<>``.
  449. Absolutely NO guarantee is provided about the resulting string being
  450. HTML safe. So NEVER mark safe the result of a ``strip_tag`` call without
  451. escaping it first, for example with :func:`~django.utils.html.escape`.
  452. For example::
  453. strip_tags(value)
  454. If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"``
  455. the return value will be ``"Joel is a slug"``.
  456. If you are looking for a more robust solution, take a look at the `bleach
  457. <https://pypi.org/project/bleach/>`_ Python library.
  458. .. function:: html_safe()
  459. The ``__html__()`` method on a class helps non-Django templates detect
  460. classes whose output doesn't require HTML escaping.
  461. This decorator defines the ``__html__()`` method on the decorated class
  462. by wrapping ``__str__()`` in :meth:`~django.utils.safestring.mark_safe`.
  463. Ensure the ``__str__()`` method does indeed return text that doesn't
  464. require HTML escaping.
  465. ``django.utils.http``
  466. =====================
  467. .. module:: django.utils.http
  468. :synopsis: HTTP helper functions. (URL encoding, cookie handling, ...)
  469. .. function:: urlencode(query, doseq=False)
  470. A version of Python's :func:`urllib.parse.urlencode` function that can
  471. operate on ``MultiValueDict`` and non-string values.
  472. .. function:: http_date(epoch_seconds=None)
  473. Formats the time to match the :rfc:`1123` date format as specified by HTTP
  474. :rfc:`7231#section-7.1.1.1`.
  475. Accepts a floating point number expressed in seconds since the epoch in
  476. UTC--such as that outputted by ``time.time()``. If set to ``None``,
  477. defaults to the current time.
  478. Outputs a string in the format ``Wdy, DD Mon YYYY HH:MM:SS GMT``.
  479. .. function:: base36_to_int(s)
  480. Converts a base 36 string to an integer.
  481. .. function:: int_to_base36(i)
  482. Converts a positive integer to a base 36 string.
  483. .. function:: urlsafe_base64_encode(s)
  484. Encodes a bytestring to a base64 string for use in URLs, stripping any
  485. trailing equal signs.
  486. .. function:: urlsafe_base64_decode(s)
  487. Decodes a base64 encoded string, adding back any trailing equal signs that
  488. might have been stripped.
  489. ``django.utils.module_loading``
  490. ===============================
  491. .. module:: django.utils.module_loading
  492. :synopsis: Functions for working with Python modules.
  493. Functions for working with Python modules.
  494. .. function:: import_string(dotted_path)
  495. Imports a dotted module path and returns the attribute/class designated by
  496. the last name in the path. Raises ``ImportError`` if the import failed. For
  497. example::
  498. from django.utils.module_loading import import_string
  499. ValidationError = import_string('django.core.exceptions.ValidationError')
  500. is equivalent to::
  501. from django.core.exceptions import ValidationError
  502. ``django.utils.safestring``
  503. ===========================
  504. .. module:: django.utils.safestring
  505. :synopsis: Functions and classes for working with strings that can be displayed safely without further escaping in HTML.
  506. Functions and classes for working with "safe strings": strings that can be
  507. displayed safely without further escaping in HTML. Marking something as a "safe
  508. string" means that the producer of the string has already turned characters
  509. that should not be interpreted by the HTML engine (e.g. '<') into the
  510. appropriate entities.
  511. .. class:: SafeString
  512. A ``str`` subclass that has been specifically marked as "safe" (requires no
  513. further escaping) for HTML output purposes.
  514. .. function:: mark_safe(s)
  515. Explicitly mark a string as safe for (HTML) output purposes. The returned
  516. object can be used everywhere a string is appropriate.
  517. Can be called multiple times on a single string.
  518. Can also be used as a decorator.
  519. For building up fragments of HTML, you should normally be using
  520. :func:`django.utils.html.format_html` instead.
  521. String marked safe will become unsafe again if modified. For example::
  522. >>> mystr = '<b>Hello World</b> '
  523. >>> mystr = mark_safe(mystr)
  524. >>> type(mystr)
  525. <class 'django.utils.safestring.SafeString'>
  526. >>> mystr = mystr.strip() # removing whitespace
  527. >>> type(mystr)
  528. <type 'str'>
  529. ``django.utils.text``
  530. =====================
  531. .. module:: django.utils.text
  532. :synopsis: Text manipulation.
  533. .. function:: format_lazy(format_string, *args, **kwargs)
  534. A version of :meth:`str.format` for when ``format_string``, ``args``,
  535. and/or ``kwargs`` contain lazy objects. The first argument is the string to
  536. be formatted. For example::
  537. from django.utils.text import format_lazy
  538. from django.utils.translation import pgettext_lazy
  539. urlpatterns = [
  540. path(format_lazy('{person}/<int:pk>/', person=pgettext_lazy('URL', 'person')),
  541. PersonDetailView.as_view()),
  542. ]
  543. This example allows translators to translate part of the URL. If "person"
  544. is translated to "persona", the regular expression will match
  545. ``persona/(?P<pk>\d+)/$``, e.g. ``persona/5/``.
  546. .. function:: slugify(value, allow_unicode=False)
  547. Converts a string to a URL slug by:
  548. #. Converting to ASCII if ``allow_unicode`` is ``False`` (the default).
  549. #. Removing characters that aren't alphanumerics, underscores, hyphens, or
  550. whitespace.
  551. #. Removing leading and trailing whitespace.
  552. #. Converting to lowercase.
  553. #. Replacing any whitespace or repeated dashes with single dashes.
  554. For example::
  555. >>> slugify(' Joel is a slug ')
  556. 'joel-is-a-slug'
  557. If you want to allow Unicode characters, pass ``allow_unicode=True``. For
  558. example::
  559. >>> slugify('你好 World', allow_unicode=True)
  560. '你好-world'
  561. .. _time-zone-selection-functions:
  562. ``django.utils.timezone``
  563. =========================
  564. .. module:: django.utils.timezone
  565. :synopsis: Timezone support.
  566. .. data:: utc
  567. :class:`~datetime.tzinfo` instance that represents UTC.
  568. .. function:: get_fixed_timezone(offset)
  569. Returns a :class:`~datetime.tzinfo` instance that represents a time zone
  570. with a fixed offset from UTC.
  571. ``offset`` is a :class:`datetime.timedelta` or an integer number of
  572. minutes. Use positive values for time zones east of UTC and negative
  573. values for west of UTC.
  574. .. function:: get_default_timezone()
  575. Returns a :class:`~datetime.tzinfo` instance that represents the
  576. :ref:`default time zone <default-current-time-zone>`.
  577. .. function:: get_default_timezone_name()
  578. Returns the name of the :ref:`default time zone
  579. <default-current-time-zone>`.
  580. .. function:: get_current_timezone()
  581. Returns a :class:`~datetime.tzinfo` instance that represents the
  582. :ref:`current time zone <default-current-time-zone>`.
  583. .. function:: get_current_timezone_name()
  584. Returns the name of the :ref:`current time zone
  585. <default-current-time-zone>`.
  586. .. function:: activate(timezone)
  587. Sets the :ref:`current time zone <default-current-time-zone>`. The
  588. ``timezone`` argument must be an instance of a :class:`~datetime.tzinfo`
  589. subclass or a time zone name.
  590. .. function:: deactivate()
  591. Unsets the :ref:`current time zone <default-current-time-zone>`.
  592. .. function:: override(timezone)
  593. This is a Python context manager that sets the :ref:`current time zone
  594. <default-current-time-zone>` on entry with :func:`activate()`, and restores
  595. the previously active time zone on exit. If the ``timezone`` argument is
  596. ``None``, the :ref:`current time zone <default-current-time-zone>` is unset
  597. on entry with :func:`deactivate()` instead.
  598. ``override`` is also usable as a function decorator.
  599. .. function:: localtime(value=None, timezone=None)
  600. Converts an aware :class:`~datetime.datetime` to a different time zone,
  601. by default the :ref:`current time zone <default-current-time-zone>`.
  602. When ``value`` is omitted, it defaults to :func:`now`.
  603. This function doesn't work on naive datetimes; use :func:`make_aware`
  604. instead.
  605. .. function:: localdate(value=None, timezone=None)
  606. Uses :func:`localtime` to convert an aware :class:`~datetime.datetime` to a
  607. :meth:`~datetime.datetime.date` in a different time zone, by default the
  608. :ref:`current time zone <default-current-time-zone>`.
  609. When ``value`` is omitted, it defaults to :func:`now`.
  610. This function doesn't work on naive datetimes.
  611. .. function:: now()
  612. Returns a :class:`~datetime.datetime` that represents the
  613. current point in time. Exactly what's returned depends on the value of
  614. :setting:`USE_TZ`:
  615. * If :setting:`USE_TZ` is ``False``, this will be a
  616. :ref:`naive <naive_vs_aware_datetimes>` datetime (i.e. a datetime
  617. without an associated timezone) that represents the current time
  618. in the system's local timezone.
  619. * If :setting:`USE_TZ` is ``True``, this will be an
  620. :ref:`aware <naive_vs_aware_datetimes>` datetime representing the
  621. current time in UTC. Note that :func:`now` will always return
  622. times in UTC regardless of the value of :setting:`TIME_ZONE`;
  623. you can use :func:`localtime` to get the time in the current time zone.
  624. .. function:: is_aware(value)
  625. Returns ``True`` if ``value`` is aware, ``False`` if it is naive. This
  626. function assumes that ``value`` is a :class:`~datetime.datetime`.
  627. .. function:: is_naive(value)
  628. Returns ``True`` if ``value`` is naive, ``False`` if it is aware. This
  629. function assumes that ``value`` is a :class:`~datetime.datetime`.
  630. .. function:: make_aware(value, timezone=None, is_dst=None)
  631. Returns an aware :class:`~datetime.datetime` that represents the same
  632. point in time as ``value`` in ``timezone``, ``value`` being a naive
  633. :class:`~datetime.datetime`. If ``timezone`` is set to ``None``, it
  634. defaults to the :ref:`current time zone <default-current-time-zone>`.
  635. The ``pytz.AmbiguousTimeError`` exception is raised if you try to make
  636. ``value`` aware during a DST transition where the same time occurs twice
  637. (when reverting from DST). Setting ``is_dst`` to ``True`` or ``False`` will
  638. avoid the exception by choosing if the time is pre-transition or
  639. post-transition respectively.
  640. The ``pytz.NonExistentTimeError`` exception is raised if you try to make
  641. ``value`` aware during a DST transition such that the time never occurred.
  642. For example, if the 2:00 hour is skipped during a DST transition, trying to
  643. make 2:30 aware in that time zone will raise an exception. To avoid that
  644. you can use ``is_dst`` to specify how ``make_aware()`` should interpret
  645. such a nonexistent time. If ``is_dst=True`` then the above time would be
  646. interpreted as 2:30 DST time (equivalent to 1:30 local time). Conversely,
  647. if ``is_dst=False`` the time would be interpreted as 2:30 standard time
  648. (equivalent to 3:30 local time).
  649. .. function:: make_naive(value, timezone=None)
  650. Returns a naive :class:`~datetime.datetime` that represents in
  651. ``timezone`` the same point in time as ``value``, ``value`` being an
  652. aware :class:`~datetime.datetime`. If ``timezone`` is set to ``None``, it
  653. defaults to the :ref:`current time zone <default-current-time-zone>`.
  654. ``django.utils.translation``
  655. ============================
  656. .. module:: django.utils.translation
  657. :synopsis: Internationalization support.
  658. For a complete discussion on the usage of the following see the
  659. :doc:`translation documentation </topics/i18n/translation>`.
  660. The ``u`` prefix on the functions below comes from a difference in Python 2
  661. between unicode and bytestrings. If your code doesn't support Python 2, use the
  662. functions without the ``u``.
  663. .. function:: gettext(message)
  664. Translates ``message`` and returns it as a string.
  665. .. function:: pgettext(context, message)
  666. Translates ``message`` given the ``context`` and returns it as a string.
  667. For more information, see :ref:`contextual-markers`.
  668. .. function:: gettext_lazy(message)
  669. .. function:: pgettext_lazy(context, message)
  670. Same as the non-lazy versions above, but using lazy execution.
  671. See :ref:`lazy translations documentation <lazy-translations>`.
  672. .. function:: gettext_noop(message)
  673. Marks strings for translation but doesn't translate them now. This can be
  674. used to store strings in global variables that should stay in the base
  675. language (because they might be used externally) and will be translated
  676. later.
  677. .. function:: ngettext(singular, plural, number)
  678. Translates ``singular`` and ``plural`` and returns the appropriate string
  679. based on ``number``.
  680. .. function:: npgettext(context, singular, plural, number)
  681. Translates ``singular`` and ``plural`` and returns the appropriate string
  682. based on ``number`` and the ``context``.
  683. .. function:: ngettext_lazy(singular, plural, number)
  684. .. function:: npgettext_lazy(context, singular, plural, number)
  685. Same as the non-lazy versions above, but using lazy execution.
  686. See :ref:`lazy translations documentation <lazy-translations>`.
  687. .. function:: activate(language)
  688. Fetches the translation object for a given language and activates it as
  689. the current translation object for the current thread.
  690. .. function:: deactivate()
  691. Deactivates the currently active translation object so that further _ calls
  692. will resolve against the default translation object, again.
  693. .. function:: deactivate_all()
  694. Makes the active translation object a ``NullTranslations()`` instance.
  695. This is useful when we want delayed translations to appear as the original
  696. string for some reason.
  697. .. function:: override(language, deactivate=False)
  698. A Python context manager that uses
  699. :func:`django.utils.translation.activate` to fetch the translation object
  700. for a given language, activates it as the translation object for the
  701. current thread and reactivates the previous active language on exit.
  702. Optionally, it can deactivate the temporary translation on exit with
  703. :func:`django.utils.translation.deactivate` if the ``deactivate`` argument
  704. is ``True``. If you pass ``None`` as the language argument, a
  705. ``NullTranslations()`` instance is activated within the context.
  706. ``override`` is also usable as a function decorator.
  707. .. function:: check_for_language(lang_code)
  708. Checks whether there is a global language file for the given language
  709. code (e.g. 'fr', 'pt_BR'). This is used to decide whether a user-provided
  710. language is available.
  711. .. function:: get_language()
  712. Returns the currently selected language code. Returns ``None`` if
  713. translations are temporarily deactivated (by :func:`deactivate_all()` or
  714. when ``None`` is passed to :func:`override()`).
  715. .. function:: get_language_bidi()
  716. Returns selected language's BiDi layout:
  717. * ``False`` = left-to-right layout
  718. * ``True`` = right-to-left layout
  719. .. function:: get_language_from_request(request, check_path=False)
  720. Analyzes the request to find what language the user wants the system to
  721. show. Only languages listed in settings.LANGUAGES are taken into account.
  722. If the user requests a sublanguage where we have a main language, we send
  723. out the main language.
  724. If ``check_path`` is ``True``, the function first checks the requested URL
  725. for whether its path begins with a language code listed in the
  726. :setting:`LANGUAGES` setting.
  727. .. function:: get_supported_language_variant(lang_code, strict=False)
  728. Returns ``lang_code`` if it's in the :setting:`LANGUAGES` setting, possibly
  729. selecting a more generic variant. For example, ``'es'`` is returned if
  730. ``lang_code`` is ``'es-ar'`` and ``'es'`` is in :setting:`LANGUAGES` but
  731. ``'es-ar'`` isn't.
  732. If ``strict`` is ``False`` (the default), a country-specific variant may
  733. be returned when neither the language code nor its generic variant is found.
  734. For example, if only ``'es-co'`` is in :setting:`LANGUAGES`, that's
  735. returned for ``lang_code``\s like ``'es'`` and ``'es-ar'``. Those matches
  736. aren't returned if ``strict=True``.
  737. Raises :exc:`LookupError` if nothing is found.
  738. .. function:: to_locale(language)
  739. Turns a language name (en-us) into a locale name (en_US).
  740. .. function:: templatize(src)
  741. Turns a Django template into something that is understood by ``xgettext``.
  742. It does so by translating the Django translation tags into standard
  743. ``gettext`` function invocations.
  744. .. data:: LANGUAGE_SESSION_KEY
  745. Session key under which the active language for the current session is
  746. stored.
  747. .. deprecated:: 3.0
  748. The language won't be stored in the session in Django 4.0. Use the
  749. :setting:`LANGUAGE_COOKIE_NAME` cookie instead.