2
0

utils.txt 42 KB

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