utils.txt 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  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="http://www.poynter.org/column.asp?id=31",
  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="http://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. ``SyndicationFeed``
  228. -------------------
  229. .. class:: SyndicationFeed
  230. Base class for all syndication feeds. Subclasses should provide
  231. ``write()``.
  232. .. 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)
  233. Initialize the feed with the given dictionary of metadata, which applies
  234. to the entire feed.
  235. Any extra keyword arguments you pass to ``__init__`` will be stored in
  236. ``self.feed``.
  237. All parameters should be strings, except ``categories``, which should
  238. be a sequence of strings.
  239. .. 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)
  240. Adds an item to the feed. All args are expected to be strings except
  241. ``pubdate`` and ``updateddate``, which are ``datetime.datetime``
  242. objects, and ``enclosures``, which is a list of ``Enclosure`` instances.
  243. .. method:: num_items()
  244. .. method:: root_attributes()
  245. Return extra attributes to place on the root (i.e. feed/channel)
  246. element. Called from ``write()``.
  247. .. method:: add_root_elements(handler)
  248. Add elements in the root (i.e. feed/channel) element.
  249. Called from ``write()``.
  250. .. method:: item_attributes(item)
  251. Return extra attributes to place on each item (i.e. item/entry)
  252. element.
  253. .. method:: add_item_elements(handler, item)
  254. Add elements on each item (i.e. item/entry) element.
  255. .. method:: write(outfile, encoding)
  256. Outputs the feed in the given encoding to ``outfile``, which is a
  257. file-like object. Subclasses should override this.
  258. .. method:: writeString(encoding)
  259. Returns the feed in the given encoding as a string.
  260. .. method:: latest_post_date()
  261. Returns the latest ``pubdate`` or ``updateddate`` for all items in the
  262. feed. If no items have either of these attributes this returns the
  263. current UTC date/time.
  264. ``Enclosure``
  265. -------------
  266. .. class:: Enclosure
  267. Represents an RSS enclosure
  268. ``RssFeed``
  269. -----------
  270. .. class:: RssFeed(SyndicationFeed)
  271. ``Rss201rev2Feed``
  272. ------------------
  273. .. class:: Rss201rev2Feed(RssFeed)
  274. Spec: https://cyber.harvard.edu/rss/rss.html
  275. ``RssUserland091Feed``
  276. ----------------------
  277. .. class:: RssUserland091Feed(RssFeed)
  278. Spec: http://backend.userland.com/rss091
  279. ``Atom1Feed``
  280. -------------
  281. .. class:: Atom1Feed(SyndicationFeed)
  282. Spec: :rfc:`4287`
  283. ``django.utils.functional``
  284. ===========================
  285. .. module:: django.utils.functional
  286. :synopsis: Functional programming tools.
  287. .. class:: cached_property(func)
  288. The ``@cached_property`` decorator caches the result of a method with a
  289. single ``self`` argument as a property. The cached result will persist
  290. as long as the instance does, so if the instance is passed around and the
  291. function subsequently invoked, the cached result will be returned.
  292. Consider a typical case, where a view might need to call a model's method
  293. to perform some computation, before placing the model instance into the
  294. context, where the template might invoke the method once more::
  295. # the model
  296. class Person(models.Model):
  297. def friends(self):
  298. # expensive computation
  299. ...
  300. return friends
  301. # in the view:
  302. if person.friends():
  303. ...
  304. And in the template you would have:
  305. .. code-block:: html+django
  306. {% for friend in person.friends %}
  307. Here, ``friends()`` will be called twice. Since the instance ``person`` in
  308. the view and the template are the same, decorating the ``friends()`` method
  309. with ``@cached_property`` can avoid that::
  310. from django.utils.functional import cached_property
  311. class Person(models.Model):
  312. @cached_property
  313. def friends(self): ...
  314. Note that as the method is now a property, in Python code it will need to
  315. be accessed appropriately::
  316. # in the view:
  317. if person.friends:
  318. ...
  319. The cached value can be treated like an ordinary attribute of the instance::
  320. # clear it, requiring re-computation next time it's called
  321. del person.friends # or delattr(person, "friends")
  322. # set a value manually, that will persist on the instance until cleared
  323. person.friends = ["Huckleberry Finn", "Tom Sawyer"]
  324. Because of the way the :py:ref:`descriptor protocol
  325. <descriptor-invocation>` works, using ``del`` (or ``delattr``) on a
  326. ``cached_property`` that hasn't been accessed raises ``AttributeError``.
  327. As well as offering potential performance advantages, ``@cached_property``
  328. can ensure that an attribute's value does not change unexpectedly over the
  329. life of an instance. This could occur with a method whose computation is
  330. based on ``datetime.now()``, or if a change were saved to the database by
  331. some other process in the brief interval between subsequent invocations of
  332. a method on the same instance.
  333. You can make cached properties of methods. For example, if you had an
  334. expensive ``get_friends()`` method and wanted to allow calling it without
  335. retrieving the cached value, you could write::
  336. friends = cached_property(get_friends)
  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. .. class:: classproperty(method=None)
  345. Similar to :py:func:`@classmethod <classmethod>`, the ``@classproperty``
  346. decorator converts the result of a method with a single ``cls`` argument
  347. into a property that can be accessed directly from the class.
  348. .. function:: keep_lazy(func, *resultclasses)
  349. Django offers many utility functions (particularly in ``django.utils``)
  350. that take a string as their first argument and do something to that string.
  351. These functions are used by template filters as well as directly in other
  352. code.
  353. If you write your own similar functions and deal with translations, you'll
  354. face the problem of what to do when the first argument is a lazy
  355. translation object. You don't want to convert it to a string immediately,
  356. because you might be using this function outside of a view (and hence the
  357. current thread's locale setting will not be correct).
  358. For cases like this, use the ``django.utils.functional.keep_lazy()``
  359. decorator. It modifies the function so that *if* it's called with a lazy
  360. translation as one of its arguments, the function evaluation is delayed
  361. until it needs to be converted to a string.
  362. For example::
  363. from django.utils.functional import keep_lazy, keep_lazy_text
  364. def fancy_utility_function(s, *args, **kwargs):
  365. # Do some conversion on string 's'
  366. ...
  367. fancy_utility_function = keep_lazy(str)(fancy_utility_function)
  368. # Or more succinctly:
  369. @keep_lazy(str)
  370. def fancy_utility_function(s, *args, **kwargs): ...
  371. The ``keep_lazy()`` decorator takes a number of extra arguments (``*args``)
  372. specifying the type(s) that the original function can return. A common
  373. use case is to have functions that return text. For these, you can pass the
  374. ``str`` type to ``keep_lazy`` (or use the :func:`keep_lazy_text` decorator
  375. described in the next section).
  376. Using this decorator means you can write your function and assume that the
  377. input is a proper string, then add support for lazy translation objects at
  378. the end.
  379. .. function:: keep_lazy_text(func)
  380. A shortcut for ``keep_lazy(str)(func)``.
  381. If you have a function that returns text and you want to be able to take
  382. lazy arguments while delaying their evaluation, you can use this
  383. decorator::
  384. from django.utils.functional import keep_lazy, keep_lazy_text
  385. # Our previous example was:
  386. @keep_lazy(str)
  387. def fancy_utility_function(s, *args, **kwargs): ...
  388. # Which can be rewritten as:
  389. @keep_lazy_text
  390. def fancy_utility_function(s, *args, **kwargs): ...
  391. ``django.utils.html``
  392. =====================
  393. .. module:: django.utils.html
  394. :synopsis: HTML helper functions
  395. Usually you should build up HTML using Django's templates to make use of its
  396. autoescape mechanism, using the utilities in :mod:`django.utils.safestring`
  397. where appropriate. This module provides some additional low level utilities for
  398. escaping HTML.
  399. .. function:: escape(text)
  400. Returns the given text with ampersands, quotes and angle brackets encoded
  401. for use in HTML. The input is first coerced to a string and the output has
  402. :func:`~django.utils.safestring.mark_safe` applied.
  403. .. function:: conditional_escape(text)
  404. Similar to ``escape()``, except that it doesn't operate on preescaped
  405. strings, so it will not double escape.
  406. .. function:: format_html(format_string, *args, **kwargs)
  407. This is similar to :meth:`str.format`, except that it is appropriate for
  408. building up HTML fragments. The first argument ``format_string`` is not
  409. escaped but all other args and kwargs are passed through
  410. :func:`conditional_escape` before being passed to ``str.format()``.
  411. Finally, the output has :func:`~django.utils.safestring.mark_safe` applied.
  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(
  418. "%s <b>%s</b> %s"
  419. % (
  420. some_html,
  421. escape(some_text),
  422. escape(some_other_text),
  423. )
  424. )
  425. You should instead use::
  426. format_html(
  427. "{} <b>{}</b> {}",
  428. mark_safe(some_html),
  429. some_text,
  430. some_other_text,
  431. )
  432. This has the advantage that you don't need to apply :func:`escape` to each
  433. argument and risk a bug and an XSS vulnerability if you forget one.
  434. Note that although this function uses ``str.format()`` to do the
  435. interpolation, some of the formatting options provided by ``str.format()``
  436. (e.g. number formatting) will not work, since all arguments are passed
  437. through :func:`conditional_escape` which (ultimately) calls
  438. :func:`~django.utils.encoding.force_str` on the values.
  439. .. deprecated:: 5.0
  440. Support for calling ``format_html()`` without passing args or kwargs is
  441. deprecated.
  442. .. function:: format_html_join(sep, format_string, args_generator)
  443. A wrapper of :func:`format_html`, for the common case of a group of
  444. arguments that need to be formatted using the same format string, and then
  445. joined using ``sep``. ``sep`` is also passed through
  446. :func:`conditional_escape`.
  447. ``args_generator`` should be an iterator that returns the sequence of
  448. ``args`` that will be passed to :func:`format_html`. For example::
  449. format_html_join("\n", "<li>{} {}</li>", ((u.first_name, u.last_name) for u in users))
  450. .. function:: json_script(value, element_id=None, encoder=None)
  451. Escapes all HTML/XML special characters with their Unicode escapes, so
  452. value is safe for use with JavaScript. Also wraps the escaped JSON in a
  453. ``<script>`` tag. If the ``element_id`` parameter is not ``None``, the
  454. ``<script>`` tag is given the passed id. For example:
  455. .. code-block:: pycon
  456. >>> json_script({"hello": "world"}, element_id="hello-data")
  457. '<script id="hello-data" type="application/json">{"hello": "world"}</script>'
  458. The ``encoder``, which defaults to
  459. :class:`django.core.serializers.json.DjangoJSONEncoder`, will be used to
  460. serialize the data. See :ref:`JSON serialization
  461. <serialization-formats-json>` for more details about this serializer.
  462. .. versionchanged:: 4.2
  463. The ``encoder`` argument was added.
  464. .. function:: strip_tags(value)
  465. Tries to remove anything that looks like an HTML tag from the string, that
  466. is anything contained within ``<>``.
  467. Absolutely NO guarantee is provided about the resulting string being
  468. HTML safe. So NEVER mark safe the result of a ``strip_tag`` call without
  469. escaping it first, for example with :func:`~django.utils.html.escape`.
  470. For example::
  471. strip_tags(value)
  472. If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"``
  473. the return value will be ``"Joel is a slug"``.
  474. If you are looking for a more robust solution, consider using a third-party
  475. HTML sanitizing tool.
  476. .. function:: html_safe()
  477. The ``__html__()`` method on a class helps non-Django templates detect
  478. classes whose output doesn't require HTML escaping.
  479. This decorator defines the ``__html__()`` method on the decorated class
  480. by wrapping ``__str__()`` in :meth:`~django.utils.safestring.mark_safe`.
  481. Ensure the ``__str__()`` method does indeed return text that doesn't
  482. require HTML escaping.
  483. ``django.utils.http``
  484. =====================
  485. .. module:: django.utils.http
  486. :synopsis: HTTP helper functions. (URL encoding, cookie handling, ...)
  487. .. function:: urlencode(query, doseq=False)
  488. A version of Python's :func:`urllib.parse.urlencode` function that can
  489. operate on ``MultiValueDict`` and non-string values.
  490. .. function:: http_date(epoch_seconds=None)
  491. Formats the time to match the :rfc:`1123#section-5.2.14` date format as
  492. specified by HTTP :rfc:`9110#section-5.6.7`.
  493. Accepts a floating point number expressed in seconds since the epoch in
  494. UTC--such as that outputted by ``time.time()``. If set to ``None``,
  495. defaults to the current time.
  496. Outputs a string in the format ``Wdy, DD Mon YYYY HH:MM:SS GMT``.
  497. .. function:: content_disposition_header(as_attachment, filename)
  498. .. versionadded:: 4.2
  499. Constructs a ``Content-Disposition`` HTTP header value from the given
  500. ``filename`` as specified by :rfc:`6266`. Returns ``None`` if
  501. ``as_attachment`` is ``False`` and ``filename`` is ``None``, otherwise
  502. returns a string suitable for the ``Content-Disposition`` HTTP header.
  503. .. function:: base36_to_int(s)
  504. Converts a base 36 string to an integer.
  505. .. function:: int_to_base36(i)
  506. Converts a positive integer to a base 36 string.
  507. .. function:: urlsafe_base64_encode(s)
  508. Encodes a bytestring to a base64 string for use in URLs, stripping any
  509. trailing equal signs.
  510. .. function:: urlsafe_base64_decode(s)
  511. Decodes a base64 encoded string, adding back any trailing equal signs that
  512. might have been stripped.
  513. ``django.utils.module_loading``
  514. ===============================
  515. .. module:: django.utils.module_loading
  516. :synopsis: Functions for working with Python modules.
  517. Functions for working with Python modules.
  518. .. function:: import_string(dotted_path)
  519. Imports a dotted module path and returns the attribute/class designated by
  520. the last name in the path. Raises ``ImportError`` if the import failed. For
  521. example::
  522. from django.utils.module_loading import import_string
  523. ValidationError = import_string("django.core.exceptions.ValidationError")
  524. is equivalent to::
  525. from django.core.exceptions import ValidationError
  526. ``django.utils.safestring``
  527. ===========================
  528. .. module:: django.utils.safestring
  529. :synopsis: Functions and classes for working with strings that can be displayed safely without further escaping in HTML.
  530. Functions and classes for working with "safe strings": strings that can be
  531. displayed safely without further escaping in HTML. Marking something as a "safe
  532. string" means that the producer of the string has already turned characters
  533. that should not be interpreted by the HTML engine (e.g. '<') into the
  534. appropriate entities.
  535. .. class:: SafeString
  536. A ``str`` subclass that has been specifically marked as "safe" (requires no
  537. further escaping) for HTML output purposes.
  538. .. function:: mark_safe(s)
  539. Explicitly mark a string as safe for (HTML) output purposes. The returned
  540. object can be used everywhere a string is appropriate.
  541. Can be called multiple times on a single string.
  542. Can also be used as a decorator.
  543. For building up fragments of HTML, you should normally be using
  544. :func:`django.utils.html.format_html` instead.
  545. String marked safe will become unsafe again if modified. For example:
  546. .. code-block:: pycon
  547. >>> mystr = "<b>Hello World</b> "
  548. >>> mystr = mark_safe(mystr)
  549. >>> type(mystr)
  550. <class 'django.utils.safestring.SafeString'>
  551. >>> mystr = mystr.strip() # removing whitespace
  552. >>> type(mystr)
  553. <type 'str'>
  554. ``django.utils.text``
  555. =====================
  556. .. module:: django.utils.text
  557. :synopsis: Text manipulation.
  558. .. function:: format_lazy(format_string, *args, **kwargs)
  559. A version of :meth:`str.format` for when ``format_string``, ``args``,
  560. and/or ``kwargs`` contain lazy objects. The first argument is the string to
  561. be formatted. For example::
  562. from django.utils.text import format_lazy
  563. from django.utils.translation import pgettext_lazy
  564. urlpatterns = [
  565. path(
  566. format_lazy("{person}/<int:pk>/", person=pgettext_lazy("URL", "person")),
  567. PersonDetailView.as_view(),
  568. ),
  569. ]
  570. This example allows translators to translate part of the URL. If "person"
  571. is translated to "persona", the regular expression will match
  572. ``persona/(?P<pk>\d+)/$``, e.g. ``persona/5/``.
  573. .. function:: slugify(value, allow_unicode=False)
  574. Converts a string to a URL slug by:
  575. #. Converting to ASCII if ``allow_unicode`` is ``False`` (the default).
  576. #. Converting to lowercase.
  577. #. Removing characters that aren't alphanumerics, underscores, hyphens, or
  578. whitespace.
  579. #. Replacing any whitespace or repeated dashes with single dashes.
  580. #. Removing leading and trailing whitespace, dashes, and underscores.
  581. For example:
  582. .. code-block:: pycon
  583. >>> slugify(" Joel is a slug ")
  584. 'joel-is-a-slug'
  585. If you want to allow Unicode characters, pass ``allow_unicode=True``. For
  586. example:
  587. .. code-block:: pycon
  588. >>> slugify("你好 World", allow_unicode=True)
  589. '你好-world'
  590. .. _time-zone-selection-functions:
  591. ``django.utils.timezone``
  592. =========================
  593. .. module:: django.utils.timezone
  594. :synopsis: Timezone support.
  595. .. function:: get_fixed_timezone(offset)
  596. Returns a :class:`~datetime.tzinfo` instance that represents a time zone
  597. with a fixed offset from UTC.
  598. ``offset`` is a :class:`datetime.timedelta` or an integer number of
  599. minutes. Use positive values for time zones east of UTC and negative
  600. values for west of UTC.
  601. .. function:: get_default_timezone()
  602. Returns a :class:`~datetime.tzinfo` instance that represents the
  603. :ref:`default time zone <default-current-time-zone>`.
  604. .. function:: get_default_timezone_name()
  605. Returns the name of the :ref:`default time zone
  606. <default-current-time-zone>`.
  607. .. function:: get_current_timezone()
  608. Returns a :class:`~datetime.tzinfo` instance that represents the
  609. :ref:`current time zone <default-current-time-zone>`.
  610. .. function:: get_current_timezone_name()
  611. Returns the name of the :ref:`current time zone
  612. <default-current-time-zone>`.
  613. .. function:: activate(timezone)
  614. Sets the :ref:`current time zone <default-current-time-zone>`. The
  615. ``timezone`` argument must be an instance of a :class:`~datetime.tzinfo`
  616. subclass or a time zone name.
  617. .. function:: deactivate()
  618. Unsets the :ref:`current time zone <default-current-time-zone>`.
  619. .. function:: override(timezone)
  620. This is a Python context manager that sets the :ref:`current time zone
  621. <default-current-time-zone>` on entry with :func:`activate()`, and restores
  622. the previously active time zone on exit. If the ``timezone`` argument is
  623. ``None``, the :ref:`current time zone <default-current-time-zone>` is unset
  624. on entry with :func:`deactivate()` instead.
  625. ``override`` is also usable as a function decorator.
  626. .. function:: localtime(value=None, timezone=None)
  627. Converts an aware :class:`~datetime.datetime` to a different time zone,
  628. by default the :ref:`current time zone <default-current-time-zone>`.
  629. When ``value`` is omitted, it defaults to :func:`now`.
  630. This function doesn't work on naive datetimes; use :func:`make_aware`
  631. instead.
  632. .. function:: localdate(value=None, timezone=None)
  633. Uses :func:`localtime` to convert an aware :class:`~datetime.datetime` to a
  634. :meth:`~datetime.datetime.date` in a different time zone, by default the
  635. :ref:`current time zone <default-current-time-zone>`.
  636. When ``value`` is omitted, it defaults to :func:`now`.
  637. This function doesn't work on naive datetimes.
  638. .. function:: now()
  639. Returns a :class:`~datetime.datetime` that represents the
  640. current point in time. Exactly what's returned depends on the value of
  641. :setting:`USE_TZ`:
  642. * If :setting:`USE_TZ` is ``False``, this will be a
  643. :ref:`naive <naive_vs_aware_datetimes>` datetime (i.e. a datetime
  644. without an associated timezone) that represents the current time
  645. in the system's local timezone.
  646. * If :setting:`USE_TZ` is ``True``, this will be an
  647. :ref:`aware <naive_vs_aware_datetimes>` datetime representing the
  648. current time in UTC. Note that :func:`now` will always return
  649. times in UTC regardless of the value of :setting:`TIME_ZONE`;
  650. you can use :func:`localtime` to get the time in the current time zone.
  651. .. function:: is_aware(value)
  652. Returns ``True`` if ``value`` is aware, ``False`` if it is naive. This
  653. function assumes that ``value`` is a :class:`~datetime.datetime`.
  654. .. function:: is_naive(value)
  655. Returns ``True`` if ``value`` is naive, ``False`` if it is aware. This
  656. function assumes that ``value`` is a :class:`~datetime.datetime`.
  657. .. function:: make_aware(value, timezone=None)
  658. Returns an aware :class:`~datetime.datetime` that represents the same
  659. point in time as ``value`` in ``timezone``, ``value`` being a naive
  660. :class:`~datetime.datetime`. If ``timezone`` is set to ``None``, it
  661. defaults to the :ref:`current time zone <default-current-time-zone>`.
  662. .. function:: make_naive(value, timezone=None)
  663. Returns a naive :class:`~datetime.datetime` that represents in
  664. ``timezone`` the same point in time as ``value``, ``value`` being an
  665. aware :class:`~datetime.datetime`. If ``timezone`` is set to ``None``, it
  666. defaults to the :ref:`current time zone <default-current-time-zone>`.
  667. ``django.utils.translation``
  668. ============================
  669. .. module:: django.utils.translation
  670. :synopsis: Internationalization support.
  671. For a complete discussion on the usage of the following see the
  672. :doc:`translation documentation </topics/i18n/translation>`.
  673. .. function:: gettext(message)
  674. Translates ``message`` and returns it as a string.
  675. .. function:: pgettext(context, message)
  676. Translates ``message`` given the ``context`` and returns it as a string.
  677. For more information, see :ref:`contextual-markers`.
  678. .. function:: gettext_lazy(message)
  679. .. function:: pgettext_lazy(context, message)
  680. Same as the non-lazy versions above, but using lazy execution.
  681. See :ref:`lazy translations documentation <lazy-translations>`.
  682. .. function:: gettext_noop(message)
  683. Marks strings for translation but doesn't translate them now. This can be
  684. used to store strings in global variables that should stay in the base
  685. language (because they might be used externally) and will be translated
  686. later.
  687. .. function:: ngettext(singular, plural, number)
  688. Translates ``singular`` and ``plural`` and returns the appropriate string
  689. based on ``number``.
  690. .. function:: npgettext(context, singular, plural, number)
  691. Translates ``singular`` and ``plural`` and returns the appropriate string
  692. based on ``number`` and the ``context``.
  693. .. function:: ngettext_lazy(singular, plural, number)
  694. .. function:: npgettext_lazy(context, singular, plural, number)
  695. Same as the non-lazy versions above, but using lazy execution.
  696. See :ref:`lazy translations documentation <lazy-translations>`.
  697. .. function:: activate(language)
  698. Fetches the translation object for a given language and activates it as
  699. the current translation object for the current thread.
  700. .. function:: deactivate()
  701. Deactivates the currently active translation object so that further _ calls
  702. will resolve against the default translation object, again.
  703. .. function:: deactivate_all()
  704. Makes the active translation object a ``NullTranslations()`` instance.
  705. This is useful when we want delayed translations to appear as the original
  706. string for some reason.
  707. .. function:: override(language, deactivate=False)
  708. A Python context manager that uses
  709. :func:`django.utils.translation.activate` to fetch the translation object
  710. for a given language, activates it as the translation object for the
  711. current thread and reactivates the previous active language on exit.
  712. Optionally, it can deactivate the temporary translation on exit with
  713. :func:`django.utils.translation.deactivate` if the ``deactivate`` argument
  714. is ``True``. If you pass ``None`` as the language argument, a
  715. ``NullTranslations()`` instance is activated within the context.
  716. ``override`` is also usable as a function decorator.
  717. .. function:: check_for_language(lang_code)
  718. Checks whether there is a global language file for the given language
  719. code (e.g. 'fr', 'pt_BR'). This is used to decide whether a user-provided
  720. language is available.
  721. .. function:: get_language()
  722. Returns the currently selected language code. Returns ``None`` if
  723. translations are temporarily deactivated (by :func:`deactivate_all()` or
  724. when ``None`` is passed to :func:`override()`).
  725. .. function:: get_language_bidi()
  726. Returns selected language's BiDi layout:
  727. * ``False`` = left-to-right layout
  728. * ``True`` = right-to-left layout
  729. .. function:: get_language_from_request(request, check_path=False)
  730. Analyzes the request to find what language the user wants the system to
  731. show. Only languages listed in settings.LANGUAGES are taken into account.
  732. If the user requests a sublanguage where we have a main language, we send
  733. out the main language.
  734. If ``check_path`` is ``True``, the function first checks the requested URL
  735. for whether its path begins with a language code listed in the
  736. :setting:`LANGUAGES` setting.
  737. .. function:: get_supported_language_variant(lang_code, strict=False)
  738. Returns ``lang_code`` if it's in the :setting:`LANGUAGES` setting, possibly
  739. selecting a more generic variant. For example, ``'es'`` is returned if
  740. ``lang_code`` is ``'es-ar'`` and ``'es'`` is in :setting:`LANGUAGES` but
  741. ``'es-ar'`` isn't.
  742. ``lang_code`` has a maximum accepted length of 500 characters. A
  743. :exc:`LookupError` is raised if ``lang_code`` exceeds this limit and
  744. ``strict`` is ``True``, or if there is no generic variant and ``strict``
  745. is ``False``.
  746. If ``strict`` is ``False`` (the default), a country-specific variant may
  747. be returned when neither the language code nor its generic variant is found.
  748. For example, if only ``'es-co'`` is in :setting:`LANGUAGES`, that's
  749. returned for ``lang_code``\s like ``'es'`` and ``'es-ar'``. Those matches
  750. aren't returned if ``strict=True``.
  751. Raises :exc:`LookupError` if nothing is found.
  752. .. versionchanged:: 4.2.15
  753. In older versions, ``lang_code`` values over 500 characters were
  754. processed without raising a :exc:`LookupError`.
  755. .. function:: to_locale(language)
  756. Turns a language name (en-us) into a locale name (en_US).
  757. .. function:: templatize(src)
  758. Turns a Django template into something that is understood by ``xgettext``.
  759. It does so by translating the Django translation tags into standard
  760. ``gettext`` function invocations.