utils.txt 42 KB

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