utils.txt 39 KB

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