utils.txt 41 KB

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