utils.txt 41 KB

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