utils.txt 40 KB

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