utils.txt 40 KB

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