utils.txt 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075
  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 need
  25. 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:`~exceptions.ValueError` if their input is well formatted but
  95. isn't a 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. Returns an ASCII string containing the encoded result.
  182. .. function:: filepath_to_uri(path)
  183. Convert a file system path to a URI portion that is suitable for inclusion
  184. in a URL. The path is assumed to be either UTF-8 or unicode.
  185. This method will encode certain characters that would normally be
  186. recognized as special characters for URIs. Note that this method does not
  187. encode the ' character, as it is a valid character within URIs. See
  188. ``encodeURIComponent()`` JavaScript function for more details.
  189. Returns an ASCII string containing the encoded result.
  190. ``django.utils.feedgenerator``
  191. ==============================
  192. .. module:: django.utils.feedgenerator
  193. :synopsis: Syndication feed generation library -- used for generating RSS, etc.
  194. Sample usage::
  195. >>> from django.utils import feedgenerator
  196. >>> feed = feedgenerator.Rss201rev2Feed(
  197. ... title=u"Poynter E-Media Tidbits",
  198. ... link=u"http://www.poynter.org/column.asp?id=31",
  199. ... description=u"A group Weblog by the sharpest minds in online media/journalism/publishing.",
  200. ... language=u"en",
  201. ... )
  202. >>> feed.add_item(
  203. ... title="Hello",
  204. ... link=u"http://www.holovaty.com/test/",
  205. ... description="Testing."
  206. ... )
  207. >>> with open('test.rss', 'w') as fp:
  208. ... feed.write(fp, 'utf-8')
  209. For simplifying the selection of a generator use ``feedgenerator.DefaultFeed``
  210. which is currently ``Rss201rev2Feed``
  211. For definitions of the different versions of RSS, see:
  212. http://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004/02/04/incompatible-rss
  213. .. function:: get_tag_uri(url, date)
  214. Creates a TagURI.
  215. See http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
  216. SyndicationFeed
  217. ---------------
  218. .. class:: SyndicationFeed
  219. Base class for all syndication feeds. Subclasses should provide write().
  220. .. method:: __init__(title, link, description, [language=None, author_email=None, author_name=None, author_link=None, subtitle=None, categories=None, feed_url=None, feed_copyright=None, feed_guid=None, ttl=None, **kwargs])
  221. Initialize the feed with the given dictionary of metadata, which applies
  222. to the entire feed.
  223. Any extra keyword arguments you pass to ``__init__`` will be stored in
  224. ``self.feed``.
  225. All parameters should be Unicode objects, except ``categories``, which
  226. should be a sequence of Unicode objects.
  227. .. 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])
  228. Adds an item to the feed. All args are expected to be Python ``unicode``
  229. objects except ``pubdate`` and ``updateddate``, which are ``datetime.datetime``
  230. objects, and ``enclosure``, which is an instance of the ``Enclosure`` class.
  231. .. versionadded:: 1.7
  232. The optional ``updateddate`` argument was added.
  233. .. method:: num_items()
  234. .. method:: root_attributes()
  235. Return extra attributes to place on the root (i.e. feed/channel)
  236. element. Called from ``write()``.
  237. .. method:: add_root_elements(handler)
  238. Add elements in the root (i.e. feed/channel) element.
  239. Called from ``write()``.
  240. .. method:: item_attributes(item)
  241. Return extra attributes to place on each item (i.e. item/entry)
  242. element.
  243. .. method:: add_item_elements(handler, item)
  244. Add elements on each item (i.e. item/entry) element.
  245. .. method:: write(outfile, encoding)
  246. Outputs the feed in the given encoding to ``outfile``, which is a
  247. file-like object. Subclasses should override this.
  248. .. method:: writeString(encoding)
  249. Returns the feed in the given encoding as a string.
  250. .. method:: latest_post_date()
  251. Returns the latest ``pubdate`` or ``updateddate`` for all items in the
  252. feed. If no items have either of these attributes this returns the
  253. current date/time.
  254. Enclosure
  255. ---------
  256. .. class:: Enclosure
  257. Represents an RSS enclosure
  258. RssFeed
  259. -------
  260. .. class:: RssFeed(SyndicationFeed)
  261. Rss201rev2Feed
  262. --------------
  263. .. class:: Rss201rev2Feed(RssFeed)
  264. Spec: http://cyber.law.harvard.edu/rss/rss.html
  265. RssUserland091Feed
  266. ------------------
  267. .. class:: RssUserland091Feed(RssFeed)
  268. Spec: http://backend.userland.com/rss091
  269. Atom1Feed
  270. ---------
  271. .. class:: Atom1Feed(SyndicationFeed)
  272. Spec: http://tools.ietf.org/html/rfc4287
  273. ``django.utils.functional``
  274. ===========================
  275. .. module:: django.utils.functional
  276. :synopsis: Functional programming tools.
  277. .. class:: cached_property(object)
  278. The ``@cached_property`` decorator caches the result of a method with a
  279. single ``self`` argument as a property. The cached result will persist
  280. as long as the instance does, so if the instance is passed around and the
  281. function subsequently invoked, the cached result will be returned.
  282. Consider a typical case, where a view might need to call a model's method
  283. to perform some computation, before placing the model instance into the
  284. context, where the template might invoke the method once more:
  285. .. code-block:: python
  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. # in the template:
  295. {% for friend in person.friends %}
  296. Here, ``friends()`` will be called twice. Since the instance ``person`` in
  297. the view and the template are the same, ``@cached_property`` can avoid
  298. that::
  299. from django.utils.functional import cached_property
  300. @cached_property
  301. def friends(self):
  302. # expensive computation
  303. ...
  304. return friends
  305. Note that as the method is now a property, in Python code it will need to
  306. be invoked appropriately::
  307. # in the view:
  308. if person.friends:
  309. The cached value can be treated like an ordinary attribute of the instance::
  310. # clear it, requiring re-computation next time it's called
  311. del person.friends # or delattr(person, "friends")
  312. # set a value manually, that will persist on the instance until cleared
  313. person.friends = ["Huckleberry Finn", "Tom Sawyer"]
  314. As well as offering potential performance advantages, ``@cached_property``
  315. can ensure that an attribute's value does not change unexpectedly over the
  316. life of an instance. This could occur with a method whose computation is
  317. based on ``datetime.now()``, or simply if a change were saved to the
  318. database by some other process in the brief interval between subsequent
  319. invocations of a method on the same instance.
  320. .. function:: allow_lazy(func, *resultclasses)
  321. Django offers many utility functions (particularly in ``django.utils``) that
  322. take a string as their first argument and do something to that string. These
  323. functions are used by template filters as well as directly in other code.
  324. If you write your own similar functions and deal with translations, you'll
  325. face the problem of what to do when the first argument is a lazy translation
  326. object. You don't want to convert it to a string immediately, because you might
  327. be using this function outside of a view (and hence the current thread's locale
  328. setting will not be correct).
  329. For cases like this, use the ``django.utils.functional.allow_lazy()``
  330. decorator. It modifies the function so that *if* it's called with a lazy
  331. translation as one of its arguments, the function evaluation is delayed
  332. until it needs to be converted to a string.
  333. For example::
  334. from django.utils.functional import allow_lazy
  335. def fancy_utility_function(s, ...):
  336. # Do some conversion on string 's'
  337. ...
  338. # Replace unicode by str on Python 3
  339. fancy_utility_function = allow_lazy(fancy_utility_function, unicode)
  340. The ``allow_lazy()`` decorator takes, in addition to the function to decorate,
  341. a number of extra arguments (``*args``) specifying the type(s) that the
  342. original function can return. Usually, it's enough to include ``unicode``
  343. (or ``str`` on Python 3) here and ensure that your function returns only
  344. Unicode strings.
  345. Using this decorator means you can write your function and assume that the
  346. input is a proper string, then add support for lazy translation objects at the
  347. end.
  348. ``django.utils.html``
  349. =====================
  350. .. module:: django.utils.html
  351. :synopsis: HTML helper functions
  352. Usually you should build up HTML using Django's templates to make use of its
  353. autoescape mechanism, using the utilities in :mod:`django.utils.safestring`
  354. where appropriate. This module provides some additional low level utilities for
  355. escaping HTML.
  356. .. function:: escape(text)
  357. Returns the given text with ampersands, quotes and angle brackets encoded
  358. for use in HTML. The input is first passed through
  359. :func:`~django.utils.encoding.force_text` and the output has
  360. :func:`~django.utils.safestring.mark_safe` applied.
  361. .. function:: conditional_escape(text)
  362. Similar to ``escape()``, except that it doesn't operate on pre-escaped strings,
  363. so it will not double escape.
  364. .. function:: format_html(format_string, *args, **kwargs)
  365. This is similar to `str.format`_, except that it is appropriate for
  366. building up HTML fragments. All args and kwargs are passed through
  367. :func:`conditional_escape` before being passed to ``str.format``.
  368. For the case of building up small HTML fragments, this function is to be
  369. preferred over string interpolation using ``%`` or ``str.format`` directly,
  370. because it applies escaping to all arguments - just like the Template system
  371. applies escaping by default.
  372. So, instead of writing:
  373. .. code-block:: python
  374. mark_safe(u"%s <b>%s</b> %s" % (some_html,
  375. escape(some_text),
  376. escape(some_other_text),
  377. ))
  378. you should instead use:
  379. .. code-block:: python
  380. format_html(u"{0} <b>{1}</b> {2}",
  381. mark_safe(some_html), some_text, some_other_text)
  382. This has the advantage that you don't need to apply :func:`escape` to each
  383. argument and risk a bug and an XSS vulnerability if you forget one.
  384. Note that although this function uses ``str.format`` to do the
  385. interpolation, some of the formatting options provided by `str.format`_
  386. (e.g. number formatting) will not work, since all arguments are passed
  387. through :func:`conditional_escape` which (ultimately) calls
  388. :func:`~django.utils.encoding.force_text` on the values.
  389. .. function:: format_html_join(sep, format_string, args_generator)
  390. A wrapper of :func:`format_html`, for the common case of a group of
  391. arguments that need to be formatted using the same format string, and then
  392. joined using ``sep``. ``sep`` is also passed through
  393. :func:`conditional_escape`.
  394. ``args_generator`` should be an iterator that returns the sequence of
  395. ``args`` that will be passed to :func:`format_html`. For example::
  396. format_html_join('\n', "<li>{0} {1}</li>", ((u.first_name, u.last_name)
  397. for u in users))
  398. .. function:: strip_tags(value)
  399. Removes anything that looks like an html tag from the string, that is
  400. anything contained within ``<>``.
  401. For example::
  402. strip_tags(value)
  403. If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"`` the
  404. return value will be ``"Joel is a slug"``. Note that ``strip_tags`` result
  405. may still contain unsafe HTML content, so you might use
  406. :func:`~django.utils.html.escape` to make it a safe string.
  407. .. versionchanged:: 1.6
  408. For improved safety, ``strip_tags`` is now parser-based.
  409. .. function:: remove_tags(value, tags)
  410. Removes a space-separated list of [X]HTML tag names from the output.
  411. For example::
  412. remove_tags(value, "b span")
  413. If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"`` the
  414. return value will be ``"Joel <button>is</button> a slug"``.
  415. Note that this filter is case-sensitive.
  416. If ``value`` is ``"<B>Joel</B> <button>is</button> a <span>slug</span>"`` the
  417. return value will be ``"<B>Joel</B> <button>is</button> a slug"``.
  418. .. _str.format: http://docs.python.org/library/stdtypes.html#str.format
  419. ``django.utils.http``
  420. =====================
  421. .. module:: django.utils.http
  422. :synopsis: HTTP helper functions. (URL encoding, cookie handling, ...)
  423. .. function:: urlquote(url, safe='/')
  424. A version of Python's ``urllib.quote()`` function that can operate on
  425. unicode strings. The url is first UTF-8 encoded before quoting. The
  426. returned string can safely be used as part of an argument to a subsequent
  427. ``iri_to_uri()`` call without double-quoting occurring. Employs lazy
  428. execution.
  429. .. function:: urlquote_plus(url, safe='')
  430. A version of Python's urllib.quote_plus() function that can operate on
  431. unicode strings. The url is first UTF-8 encoded before quoting. The
  432. returned string can safely be used as part of an argument to a subsequent
  433. ``iri_to_uri()`` call without double-quoting occurring. Employs lazy
  434. execution.
  435. .. function:: urlencode(query, doseq=0)
  436. A version of Python's urllib.urlencode() function that can operate on
  437. unicode strings. The parameters are first case to UTF-8 encoded strings
  438. and then encoded as per normal.
  439. .. function:: cookie_date(epoch_seconds=None)
  440. Formats the time to ensure compatibility with Netscape's cookie standard.
  441. Accepts a floating point number expressed in seconds since the epoch in
  442. UTC--such as that outputted by ``time.time()``. If set to ``None``,
  443. defaults to the current time.
  444. Outputs a string in the format ``Wdy, DD-Mon-YYYY HH:MM:SS GMT``.
  445. .. function:: http_date(epoch_seconds=None)
  446. Formats the time to match the :rfc:`1123` date format as specified by HTTP
  447. :rfc:`2616#section-3.3.1` section 3.3.1.
  448. Accepts a floating point number expressed in seconds since the epoch in
  449. UTC--such as that outputted by ``time.time()``. If set to ``None``,
  450. defaults to the current time.
  451. Outputs a string in the format ``Wdy, DD Mon YYYY HH:MM:SS GMT``.
  452. .. function:: base36_to_int(s)
  453. Converts a base 36 string to an integer. On Python 2 the output is
  454. guaranteed to be an ``int`` and not a ``long``.
  455. .. function:: int_to_base36(i)
  456. Converts a positive integer to a base 36 string. On Python 2 ``i`` must be
  457. smaller than :data:`sys.maxint`.
  458. .. function:: urlsafe_base64_encode(s)
  459. .. versionadded:: 1.6
  460. Encodes a bytestring in base64 for use in URLs, stripping any trailing
  461. equal signs.
  462. .. function:: urlsafe_base64_decode(s)
  463. .. versionadded:: 1.6
  464. Decodes a base64 encoded string, adding back any trailing equal signs that
  465. might have been stripped.
  466. ``django.utils.module_loading``
  467. ===============================
  468. .. module:: django.utils.module_loading
  469. :synopsis: Functions for working with Python modules.
  470. Functions for working with Python modules.
  471. .. function:: import_string(dotted_path)
  472. .. versionadded:: 1.7
  473. Imports a dotted module path and returns the attribute/class designated by
  474. the last name in the path. Raises ``ImportError`` if the import failed. For
  475. example::
  476. from django.utils.module_loading import import_string
  477. ImproperlyConfigured = import_string('django.core.exceptions.ImproperlyConfigured')
  478. is equivalent to::
  479. from django.core.exceptions import ImproperlyConfigured
  480. .. function:: import_by_path(dotted_path, error_prefix='')
  481. .. versionadded:: 1.6
  482. .. deprecated:: 1.7
  483. Use :meth:`~django.utils.module_loading.import_string` instead.
  484. Imports a dotted module path and returns the attribute/class designated by
  485. the last name in the path. Raises :exc:`~django.core.exceptions.ImproperlyConfigured`
  486. if something goes wrong.
  487. ``django.utils.safestring``
  488. ===========================
  489. .. module:: django.utils.safestring
  490. :synopsis: Functions and classes for working with strings that can be displayed safely without further escaping in HTML.
  491. Functions and classes for working with "safe strings": strings that can be
  492. displayed safely without further escaping in HTML. Marking something as a "safe
  493. string" means that the producer of the string has already turned characters
  494. that should not be interpreted by the HTML engine (e.g. '<') into the
  495. appropriate entities.
  496. .. class:: SafeBytes
  497. A ``bytes`` subclass that has been specifically marked as "safe"
  498. (requires no further escaping) for HTML output purposes.
  499. .. class:: SafeString
  500. A ``str`` subclass that has been specifically marked as "safe"
  501. (requires no further escaping) for HTML output purposes. This is
  502. :class:`SafeBytes` on Python 2 and :class:`SafeText` on Python 3.
  503. .. class:: SafeText
  504. A ``str`` (in Python 3) or ``unicode`` (in Python 2) subclass
  505. that has been specifically marked as "safe" for HTML output purposes.
  506. .. class:: SafeUnicode
  507. Historical name of :class:`SafeText`. Only available under Python 2.
  508. .. function:: mark_safe(s)
  509. Explicitly mark a string as safe for (HTML) output purposes. The returned
  510. object can be used everywhere a string or unicode object is appropriate.
  511. Can be called multiple times on a single string.
  512. String marked safe will become unsafe again if modified. For example::
  513. >>> mystr = '<b>Hello World</b> '
  514. >>> mystr = mark_safe(mystr)
  515. >>> type(mystr)
  516. <class 'django.utils.safestring.SafeBytes'>
  517. >>> mystr = mystr.strip() # removing whitespace
  518. >>> type(mystr)
  519. <type 'str'>
  520. .. function:: mark_for_escaping(s)
  521. Explicitly mark a string as requiring HTML escaping upon output. Has no
  522. effect on ``SafeData`` subclasses.
  523. Can be called multiple times on a single string (the resulting escaping is
  524. only applied once).
  525. ``django.utils.text``
  526. =====================
  527. .. module:: django.utils.text
  528. :synopsis: Text manipulation.
  529. .. function:: slugify
  530. Converts to lowercase, removes non-word characters (alphanumerics and
  531. underscores) and converts spaces to hyphens. Also strips leading and trailing
  532. whitespace.
  533. For example::
  534. slugify(value)
  535. If ``value`` is ``"Joel is a slug"``, the output will be ``"joel-is-a-slug"``.
  536. ``django.utils.translation``
  537. ============================
  538. .. module:: django.utils.translation
  539. :synopsis: Internationalization support.
  540. For a complete discussion on the usage of the following see the
  541. :doc:`translation documentation </topics/i18n/translation>`.
  542. .. function:: gettext(message)
  543. Translates ``message`` and returns it in a UTF-8 bytestring
  544. .. function:: ugettext(message)
  545. Translates ``message`` and returns it in a unicode string
  546. .. function:: pgettext(context, message)
  547. Translates ``message`` given the ``context`` and returns
  548. it in a unicode string.
  549. For more information, see :ref:`contextual-markers`.
  550. .. function:: gettext_lazy(message)
  551. .. function:: ugettext_lazy(message)
  552. .. function:: pgettext_lazy(context, message)
  553. Same as the non-lazy versions above, but using lazy execution.
  554. See :ref:`lazy translations documentation <lazy-translations>`.
  555. .. function:: gettext_noop(message)
  556. .. function:: ugettext_noop(message)
  557. Marks strings for translation but doesn't translate them now. This can be
  558. used to store strings in global variables that should stay in the base
  559. language (because they might be used externally) and will be translated
  560. later.
  561. .. function:: ngettext(singular, plural, number)
  562. Translates ``singular`` and ``plural`` and returns the appropriate string
  563. based on ``number`` in a UTF-8 bytestring.
  564. .. function:: ungettext(singular, plural, number)
  565. Translates ``singular`` and ``plural`` and returns the appropriate string
  566. based on ``number`` in a unicode string.
  567. .. function:: npgettext(context, singular, plural, number)
  568. Translates ``singular`` and ``plural`` and returns the appropriate string
  569. based on ``number`` and the ``context`` in a unicode string.
  570. .. function:: ngettext_lazy(singular, plural, number)
  571. .. function:: ungettext_lazy(singular, plural, number)
  572. .. function:: npgettext_lazy(context, singular, plural, number)
  573. Same as the non-lazy versions above, but using lazy execution.
  574. See :ref:`lazy translations documentation <lazy-translations>`.
  575. .. function:: string_concat(*strings)
  576. Lazy variant of string concatenation, needed for translations that are
  577. constructed from multiple parts.
  578. .. function:: activate(language)
  579. Fetches the translation object for a given language and installs it as
  580. the current translation object for the current thread.
  581. .. function:: deactivate()
  582. De-installs the currently active translation object so that further _ calls
  583. will resolve against the default translation object, again.
  584. .. function:: deactivate_all()
  585. Makes the active translation object a NullTranslations() instance. This is
  586. useful when we want delayed translations to appear as the original string
  587. for some reason.
  588. .. function:: override(language, deactivate=False)
  589. A Python context manager that uses
  590. :func:`django.utils.translation.activate` to fetch the translation object
  591. for a given language, installing it as the translation object for the
  592. current thread and reinstall the previous active language on exit.
  593. Optionally it can simply deinstall the temporary translation on exit with
  594. :func:`django.utils.translation.deactivate` if the deactivate argument is
  595. True. If you pass None as the language argument, a NullTranslations()
  596. instance is installed while the context is active.
  597. .. function:: get_language()
  598. Returns the currently selected language code.
  599. .. function:: get_language_bidi()
  600. Returns selected language's BiDi layout:
  601. * ``False`` = left-to-right layout
  602. * ``True`` = right-to-left layout
  603. .. function:: get_language_from_request(request, check_path=False)
  604. Analyzes the request to find what language the user wants the system to show.
  605. Only languages listed in settings.LANGUAGES are taken into account. If the user
  606. requests a sublanguage where we have a main language, we send out the main
  607. language.
  608. If ``check_path`` is ``True``, the function first checks the requested URL
  609. for whether its path begins with a language code listed in the
  610. :setting:`LANGUAGES` setting.
  611. .. function:: to_locale(language)
  612. Turns a language name (en-us) into a locale name (en_US).
  613. .. function:: templatize(src)
  614. Turns a Django template into something that is understood by xgettext. It does
  615. so by translating the Django translation tags into standard gettext function
  616. invocations.
  617. .. _time-zone-selection-functions:
  618. ``django.utils.timezone``
  619. =========================
  620. .. module:: django.utils.timezone
  621. :synopsis: Timezone support.
  622. .. data:: utc
  623. :class:`~datetime.tzinfo` instance that represents UTC.
  624. .. function:: get_fixed_timezone(offset)
  625. .. versionadded:: 1.7
  626. Returns a :class:`~datetime.tzinfo` instance that represents a time zone
  627. with a fixed offset from UTC.
  628. ``offset`` is a :class:`datetime.timedelta` or an integer number of
  629. minutes. Use positive values for time zones east of UTC and negative
  630. values for west of UTC.
  631. .. function:: get_default_timezone()
  632. Returns a :class:`~datetime.tzinfo` instance that represents the
  633. :ref:`default time zone <default-current-time-zone>`.
  634. .. function:: get_default_timezone_name()
  635. Returns the name of the :ref:`default time zone
  636. <default-current-time-zone>`.
  637. .. function:: get_current_timezone()
  638. Returns a :class:`~datetime.tzinfo` instance that represents the
  639. :ref:`current time zone <default-current-time-zone>`.
  640. .. function:: get_current_timezone_name()
  641. Returns the name of the :ref:`current time zone
  642. <default-current-time-zone>`.
  643. .. function:: activate(timezone)
  644. Sets the :ref:`current time zone <default-current-time-zone>`. The
  645. ``timezone`` argument must be an instance of a :class:`~datetime.tzinfo`
  646. subclass or, if pytz_ is available, a time zone name.
  647. .. function:: deactivate()
  648. Unsets the :ref:`current time zone <default-current-time-zone>`.
  649. .. function:: override(timezone)
  650. This is a Python context manager that sets the :ref:`current time zone
  651. <default-current-time-zone>` on entry with :func:`activate()`, and restores
  652. the previously active time zone on exit. If the ``timezone`` argument is
  653. ``None``, the :ref:`current time zone <default-current-time-zone>` is unset
  654. on entry with :func:`deactivate()` instead.
  655. .. function:: localtime(value, timezone=None)
  656. Converts an aware :class:`~datetime.datetime` to a different time zone,
  657. by default the :ref:`current time zone <default-current-time-zone>`.
  658. This function doesn't work on naive datetimes; use :func:`make_aware`
  659. instead.
  660. .. function:: now()
  661. Returns a :class:`~datetime.datetime` that represents the
  662. current point in time. Exactly what's returned depends on the value of
  663. :setting:`USE_TZ`:
  664. * If :setting:`USE_TZ` is ``False``, this will be be a
  665. :ref:`naive <naive_vs_aware_datetimes>` datetime (i.e. a datetime
  666. without an associated timezone) that represents the current time
  667. in the system's local timezone.
  668. * If :setting:`USE_TZ` is ``True``, this will be an
  669. :ref:`aware <naive_vs_aware_datetimes>` datetime representing the
  670. current time in UTC. Note that :func:`now` will always return
  671. times in UTC regardless of the value of :setting:`TIME_ZONE`;
  672. you can use :func:`localtime` to convert to a time in the current
  673. time zone.
  674. .. function:: is_aware(value)
  675. Returns ``True`` if ``value`` is aware, ``False`` if it is naive. This
  676. function assumes that ``value`` is a :class:`~datetime.datetime`.
  677. .. function:: is_naive(value)
  678. Returns ``True`` if ``value`` is naive, ``False`` if it is aware. This
  679. function assumes that ``value`` is a :class:`~datetime.datetime`.
  680. .. function:: make_aware(value, timezone)
  681. Returns an aware :class:`~datetime.datetime` that represents the same
  682. point in time as ``value`` in ``timezone``, ``value`` being a naive
  683. :class:`~datetime.datetime`.
  684. This function can raise an exception if ``value`` doesn't exist or is
  685. ambiguous because of DST transitions.
  686. .. function:: make_naive(value, timezone)
  687. Returns an naive :class:`~datetime.datetime` that represents in
  688. ``timezone`` the same point in time as ``value``, ``value`` being an
  689. aware :class:`~datetime.datetime`
  690. .. _pytz: http://pytz.sourceforge.net/
  691. ``django.utils.tzinfo``
  692. =======================
  693. .. deprecated:: 1.7
  694. Use :mod:`~django.utils.timezone` instead.
  695. .. module:: django.utils.tzinfo
  696. :synopsis: Implementation of ``tzinfo`` classes for use with ``datetime.datetime``.
  697. .. class:: FixedOffset
  698. Fixed offset in minutes east from UTC.
  699. .. deprecated:: 1.7
  700. Use :func:`~django.utils.timezone.get_fixed_timezone` instead.
  701. .. class:: LocalTimezone
  702. Proxy timezone information from time module.
  703. .. deprecated:: 1.7
  704. Use :func:`~django.utils.timezone.get_default_timezone` instead.