utils.txt 43 KB

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