utils.txt 39 KB

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