utils.txt 39 KB

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