1. ============
    
  2. Django Utils
    
  3. ============
    
  4. 
    
  5. .. module:: django.utils
    
  6.    :synopsis: Django's built-in utilities.
    
  7. 
    
  8. This document covers all stable modules in ``django.utils``. Most of the
    
  9. modules in ``django.utils`` are designed for internal use and only the
    
  10. following parts can be considered stable and thus backwards compatible as per
    
  11. the :ref:`internal release deprecation policy <internal-release-deprecation-policy>`.
    
  12. 
    
  13. ``django.utils.cache``
    
  14. ======================
    
  15. 
    
  16. .. module:: django.utils.cache
    
  17.    :synopsis: Helper functions for controlling caching.
    
  18. 
    
  19. This module contains helper functions for controlling HTTP caching. It does so
    
  20. by managing the ``Vary`` header of responses. It includes functions to patch
    
  21. the header of response objects directly and decorators that change functions to
    
  22. do that header-patching themselves.
    
  23. 
    
  24. For information on the ``Vary`` header, see :rfc:`7231#section-7.1.4`.
    
  25. 
    
  26. Essentially, the ``Vary`` HTTP header defines which headers a cache should take
    
  27. into account when building its cache key. Requests with the same path but
    
  28. different header content for headers named in ``Vary`` need to get different
    
  29. cache keys to prevent delivery of wrong content.
    
  30. 
    
  31. For example, :doc:`internationalization </topics/i18n/index>` middleware would
    
  32. need to distinguish caches by the ``Accept-language`` header.
    
  33. 
    
  34. .. function:: patch_cache_control(response, **kwargs)
    
  35. 
    
  36.     This function patches the ``Cache-Control`` header by adding all keyword
    
  37.     arguments to it. The transformation is as follows:
    
  38. 
    
  39.     * All keyword parameter names are turned to lowercase, and underscores
    
  40.       are converted to hyphens.
    
  41.     * If the value of a parameter is ``True`` (exactly ``True``, not just a
    
  42.       true value), only the parameter name is added to the header.
    
  43.     * All other parameters are added with their value, after applying
    
  44.       ``str()`` to it.
    
  45. 
    
  46. .. function:: get_max_age(response)
    
  47. 
    
  48.     Returns the max-age from the response Cache-Control header as an integer
    
  49.     (or ``None`` if it wasn't found or wasn't an integer).
    
  50. 
    
  51. .. function:: patch_response_headers(response, cache_timeout=None)
    
  52. 
    
  53.     Adds some useful headers to the given ``HttpResponse`` object:
    
  54. 
    
  55.     * ``Expires``
    
  56.     * ``Cache-Control``
    
  57. 
    
  58.     Each header is only added if it isn't already set.
    
  59. 
    
  60.     ``cache_timeout`` is in seconds. The :setting:`CACHE_MIDDLEWARE_SECONDS`
    
  61.     setting is used by default.
    
  62. 
    
  63. .. function:: add_never_cache_headers(response)
    
  64. 
    
  65.     Adds an ``Expires`` header to the current date/time.
    
  66. 
    
  67.     Adds a ``Cache-Control: max-age=0, no-cache, no-store, must-revalidate,
    
  68.     private`` header to a response to indicate that a page should never be
    
  69.     cached.
    
  70. 
    
  71.     Each header is only added if it isn't already set.
    
  72. 
    
  73. .. function:: patch_vary_headers(response, newheaders)
    
  74. 
    
  75.     Adds (or updates) the ``Vary`` header in the given ``HttpResponse`` object.
    
  76.     ``newheaders`` is a list of header names that should be in ``Vary``. If
    
  77.     headers contains an asterisk, then ``Vary`` header will consist of a single
    
  78.     asterisk ``'*'``, according to :rfc:`7231#section-7.1.4`. Otherwise,
    
  79.     existing headers in ``Vary`` aren't removed.
    
  80. 
    
  81. .. function:: get_cache_key(request, key_prefix=None, method='GET', cache=None)
    
  82. 
    
  83.     Returns a cache key based on the request path. It can be used in the
    
  84.     request phase because it pulls the list of headers to take into account
    
  85.     from the global path registry and uses those to build a cache key to
    
  86.     check against.
    
  87. 
    
  88.     If there is no headerlist stored, the page needs to be rebuilt, so this
    
  89.     function returns ``None``.
    
  90. 
    
  91. .. function:: learn_cache_key(request, response, cache_timeout=None, key_prefix=None, cache=None)
    
  92. 
    
  93.     Learns what headers to take into account for some request path from the
    
  94.     response object. It stores those headers in a global path registry so that
    
  95.     later access to that path will know what headers to take into account
    
  96.     without building the response object itself. The headers are named in
    
  97.     the ``Vary`` header of the response, but we want to prevent response
    
  98.     generation.
    
  99. 
    
  100.     The list of headers to use for cache key generation is stored in the same
    
  101.     cache as the pages themselves. If the cache ages some data out of the
    
  102.     cache, this means that we have to build the response once to get at the
    
  103.     Vary header and so at the list of headers to use for the cache key.
    
  104. 
    
  105. ``django.utils.dateparse``
    
  106. ==========================
    
  107. 
    
  108. .. module:: django.utils.dateparse
    
  109.    :synopsis: Functions to parse strings to datetime objects.
    
  110. 
    
  111. The functions defined in this module share the following properties:
    
  112. 
    
  113. - They accept strings in ISO 8601 date/time formats (or some close
    
  114.   alternatives) and return objects from the corresponding classes in Python's
    
  115.   :mod:`datetime` module.
    
  116. - They raise :exc:`ValueError` if their input is well formatted but isn't a
    
  117.   valid date or time.
    
  118. - They return ``None`` if it isn't well formatted at all.
    
  119. - They accept up to picosecond resolution in input, but they truncate it to
    
  120.   microseconds, since that's what Python supports.
    
  121. 
    
  122. .. function:: parse_date(value)
    
  123. 
    
  124.     Parses a string and returns a :class:`datetime.date`.
    
  125. 
    
  126. .. function:: parse_time(value)
    
  127. 
    
  128.     Parses a string and returns a :class:`datetime.time`.
    
  129. 
    
  130.     UTC offsets aren't supported; if ``value`` describes one, the result is
    
  131.     ``None``.
    
  132. 
    
  133. .. function:: parse_datetime(value)
    
  134. 
    
  135.     Parses a string and returns a :class:`datetime.datetime`.
    
  136. 
    
  137.     UTC offsets are supported; if ``value`` describes one, the result's
    
  138.     ``tzinfo`` attribute is a :class:`datetime.timezone` instance.
    
  139. 
    
  140. .. function:: parse_duration(value)
    
  141. 
    
  142.     Parses a string and returns a :class:`datetime.timedelta`.
    
  143. 
    
  144.     Expects data in the format ``"DD HH:MM:SS.uuuuuu"``,
    
  145.     ``"DD HH:MM:SS,uuuuuu"``,  or as specified by ISO 8601 (e.g.
    
  146.     ``P4DT1H15M20S`` which is equivalent to ``4 1:15:20``) or PostgreSQL's
    
  147.     day-time interval format (e.g. ``3 days 04:05:06``).
    
  148. 
    
  149. ``django.utils.decorators``
    
  150. ===========================
    
  151. 
    
  152. .. module:: django.utils.decorators
    
  153.     :synopsis: Functions that help with creating decorators for views.
    
  154. 
    
  155. .. function:: method_decorator(decorator, name='')
    
  156. 
    
  157.     Converts a function decorator into a method decorator. It can be used to
    
  158.     decorate methods or classes; in the latter case, ``name`` is the name
    
  159.     of the method to be decorated and is required.
    
  160. 
    
  161.     ``decorator`` may also be a list or tuple of functions. They are wrapped
    
  162.     in reverse order so that the call order is the order in which the functions
    
  163.     appear in the list/tuple.
    
  164. 
    
  165.     See :ref:`decorating class based views <decorating-class-based-views>` for
    
  166.     example usage.
    
  167. 
    
  168. .. function:: decorator_from_middleware(middleware_class)
    
  169. 
    
  170.     Given a middleware class, returns a view decorator. This lets you use
    
  171.     middleware functionality on a per-view basis. The middleware is created
    
  172.     with no params passed.
    
  173. 
    
  174.     It assumes middleware that's compatible with the old style of Django 1.9
    
  175.     and earlier (having methods like ``process_request()``,
    
  176.     ``process_exception()``, and ``process_response()``).
    
  177. 
    
  178. .. function:: decorator_from_middleware_with_args(middleware_class)
    
  179. 
    
  180.     Like ``decorator_from_middleware``, but returns a function
    
  181.     that accepts the arguments to be passed to the middleware_class.
    
  182.     For example, the :func:`~django.views.decorators.cache.cache_page`
    
  183.     decorator is created from the ``CacheMiddleware`` like this::
    
  184. 
    
  185.          cache_page = decorator_from_middleware_with_args(CacheMiddleware)
    
  186. 
    
  187.          @cache_page(3600)
    
  188.          def my_view(request):
    
  189.              pass
    
  190. 
    
  191. .. function:: sync_only_middleware(middleware)
    
  192. 
    
  193.     Marks a middleware as :ref:`synchronous-only <async-middleware>`. (The
    
  194.     default in Django, but this allows you to future-proof if the default ever
    
  195.     changes in a future release.)
    
  196. 
    
  197. .. function:: async_only_middleware(middleware)
    
  198. 
    
  199.     Marks a middleware as :ref:`asynchronous-only <async-middleware>`. Django
    
  200.     will wrap it in an asynchronous event loop when it is called from the WSGI
    
  201.     request path.
    
  202. 
    
  203. .. function:: sync_and_async_middleware(middleware)
    
  204. 
    
  205.     Marks a middleware as :ref:`sync and async compatible <async-middleware>`,
    
  206.     this allows to avoid converting requests. You must implement detection of
    
  207.     the current request type to use this decorator. See :ref:`asynchronous
    
  208.     middleware documentation <async-middleware>` for details.
    
  209. 
    
  210. ``django.utils.encoding``
    
  211. =========================
    
  212. 
    
  213. .. module:: django.utils.encoding
    
  214.    :synopsis: A series of helper functions to manage character encoding.
    
  215. 
    
  216. .. function:: smart_str(s, encoding='utf-8', strings_only=False, errors='strict')
    
  217. 
    
  218.     Returns a ``str`` object representing arbitrary object ``s``. Treats
    
  219.     bytestrings using the ``encoding`` codec.
    
  220. 
    
  221.     If ``strings_only`` is ``True``, don't convert (some) non-string-like
    
  222.     objects.
    
  223. 
    
  224. .. function:: is_protected_type(obj)
    
  225. 
    
  226.     Determine if the object instance is of a protected type.
    
  227. 
    
  228.     Objects of protected types are preserved as-is when passed to
    
  229.     ``force_str(strings_only=True)``.
    
  230. 
    
  231. .. function:: force_str(s, encoding='utf-8', strings_only=False, errors='strict')
    
  232. 
    
  233.     Similar to ``smart_str()``, except that lazy instances are resolved to
    
  234.     strings, rather than kept as lazy objects.
    
  235. 
    
  236.     If ``strings_only`` is ``True``, don't convert (some) non-string-like
    
  237.     objects.
    
  238. 
    
  239. .. function:: smart_bytes(s, encoding='utf-8', strings_only=False, errors='strict')
    
  240. 
    
  241.     Returns a bytestring version of arbitrary object ``s``, encoded as
    
  242.     specified in ``encoding``.
    
  243. 
    
  244.     If ``strings_only`` is ``True``, don't convert (some) non-string-like
    
  245.     objects.
    
  246. 
    
  247. .. function:: force_bytes(s, encoding='utf-8', strings_only=False, errors='strict')
    
  248. 
    
  249.     Similar to ``smart_bytes``, except that lazy instances are resolved to
    
  250.     bytestrings, rather than kept as lazy objects.
    
  251. 
    
  252.     If ``strings_only`` is ``True``, don't convert (some) non-string-like
    
  253.     objects.
    
  254. 
    
  255. .. function:: iri_to_uri(iri)
    
  256. 
    
  257.     Convert an Internationalized Resource Identifier (IRI) portion to a URI
    
  258.     portion that is suitable for inclusion in a URL.
    
  259. 
    
  260.     This is the algorithm from section 3.1 of :rfc:`3987#section-3.1`, slightly
    
  261.     simplified since the input is assumed to be a string rather than an
    
  262.     arbitrary byte stream.
    
  263. 
    
  264.     Takes an IRI (string or UTF-8 bytes) and returns a string containing the
    
  265.     encoded result.
    
  266. 
    
  267. .. function:: uri_to_iri(uri)
    
  268. 
    
  269.     Converts a Uniform Resource Identifier into an Internationalized Resource
    
  270.     Identifier.
    
  271. 
    
  272.     This is an algorithm from section 3.2 of :rfc:`3987#section-3.2`.
    
  273. 
    
  274.     Takes a URI in ASCII bytes and returns a string containing the encoded
    
  275.     result.
    
  276. 
    
  277. .. function:: filepath_to_uri(path)
    
  278. 
    
  279.     Convert a file system path to a URI portion that is suitable for inclusion
    
  280.     in a URL. The path is assumed to be either UTF-8 bytes, string, or a
    
  281.     :class:`~pathlib.Path`.
    
  282. 
    
  283.     This method will encode certain characters that would normally be
    
  284.     recognized as special characters for URIs.  Note that this method does not
    
  285.     encode the ' character, as it is a valid character within URIs. See
    
  286.     ``encodeURIComponent()`` JavaScript function for more details.
    
  287. 
    
  288.     Returns an ASCII string containing the encoded result.
    
  289. 
    
  290. .. function:: escape_uri_path(path)
    
  291. 
    
  292.     Escapes the unsafe characters from the path portion of a Uniform Resource
    
  293.     Identifier (URI).
    
  294. 
    
  295. ``django.utils.feedgenerator``
    
  296. ==============================
    
  297. 
    
  298. .. module:: django.utils.feedgenerator
    
  299.    :synopsis: Syndication feed generation library -- used for generating RSS, etc.
    
  300. 
    
  301. Sample usage::
    
  302. 
    
  303.     >>> from django.utils import feedgenerator
    
  304.     >>> feed = feedgenerator.Rss201rev2Feed(
    
  305.     ...     title="Poynter E-Media Tidbits",
    
  306.     ...     link="http://www.poynter.org/column.asp?id=31",
    
  307.     ...     description="A group blog by the sharpest minds in online media/journalism/publishing.",
    
  308.     ...     language="en",
    
  309.     ... )
    
  310.     >>> feed.add_item(
    
  311.     ...     title="Hello",
    
  312.     ...     link="http://www.holovaty.com/test/",
    
  313.     ...     description="Testing.",
    
  314.     ... )
    
  315.     >>> with open('test.rss', 'w') as fp:
    
  316.     ...     feed.write(fp, 'utf-8')
    
  317. 
    
  318. For simplifying the selection of a generator use ``feedgenerator.DefaultFeed``
    
  319. which is currently ``Rss201rev2Feed``
    
  320. 
    
  321. For definitions of the different versions of RSS, see:
    
  322. https://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004/02/04/incompatible-rss
    
  323. 
    
  324. .. function:: get_tag_uri(url, date)
    
  325. 
    
  326.     Creates a TagURI.
    
  327. 
    
  328.     See https://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
    
  329. 
    
  330. ``SyndicationFeed``
    
  331. -------------------
    
  332. 
    
  333. .. class:: SyndicationFeed
    
  334. 
    
  335.     Base class for all syndication feeds. Subclasses should provide
    
  336.     ``write()``.
    
  337. 
    
  338.     .. 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)
    
  339. 
    
  340.         Initialize the feed with the given dictionary of metadata, which applies
    
  341.         to the entire feed.
    
  342. 
    
  343.         Any extra keyword arguments you pass to ``__init__`` will be stored in
    
  344.         ``self.feed``.
    
  345. 
    
  346.         All parameters should be strings, except ``categories``, which should
    
  347.         be a sequence of strings.
    
  348. 
    
  349.     .. method:: add_item(title, link, description, author_email=None, author_name=None, author_link=None, pubdate=None, comments=None, unique_id=None, categories=(), item_copyright=None, ttl=None, updateddate=None, enclosures=None, **kwargs)
    
  350. 
    
  351.         Adds an item to the feed. All args are expected to be strings except
    
  352.         ``pubdate`` and ``updateddate``, which are ``datetime.datetime``
    
  353.         objects, and ``enclosures``, which is a list of ``Enclosure`` instances.
    
  354. 
    
  355.     .. method:: num_items()
    
  356. 
    
  357.     .. method:: root_attributes()
    
  358. 
    
  359.         Return extra attributes to place on the root (i.e. feed/channel)
    
  360.         element. Called from ``write()``.
    
  361. 
    
  362.     .. method:: add_root_elements(handler)
    
  363. 
    
  364.         Add elements in the root (i.e. feed/channel) element.
    
  365.         Called from ``write()``.
    
  366. 
    
  367.     .. method:: item_attributes(item)
    
  368. 
    
  369.         Return extra attributes to place on each item (i.e. item/entry)
    
  370.         element.
    
  371. 
    
  372.     .. method:: add_item_elements(handler, item)
    
  373. 
    
  374.         Add elements on each item (i.e. item/entry) element.
    
  375. 
    
  376.     .. method:: write(outfile, encoding)
    
  377. 
    
  378.         Outputs the feed in the given encoding to ``outfile``, which is a
    
  379.         file-like object. Subclasses should override this.
    
  380. 
    
  381.     .. method:: writeString(encoding)
    
  382. 
    
  383.         Returns the feed in the given encoding as a string.
    
  384. 
    
  385.     .. method:: latest_post_date()
    
  386. 
    
  387.         Returns the latest ``pubdate`` or ``updateddate`` for all items in the
    
  388.         feed. If no items have either of these attributes this returns the
    
  389.         current UTC date/time.
    
  390. 
    
  391. ``Enclosure``
    
  392. -------------
    
  393. 
    
  394. .. class:: Enclosure
    
  395. 
    
  396.     Represents an RSS enclosure
    
  397. 
    
  398. ``RssFeed``
    
  399. -----------
    
  400. 
    
  401. .. class:: RssFeed(SyndicationFeed)
    
  402. 
    
  403. ``Rss201rev2Feed``
    
  404. ------------------
    
  405. 
    
  406. .. class:: Rss201rev2Feed(RssFeed)
    
  407. 
    
  408.     Spec: https://cyber.harvard.edu/rss/rss.html
    
  409. 
    
  410. ``RssUserland091Feed``
    
  411. ----------------------
    
  412. 
    
  413. .. class:: RssUserland091Feed(RssFeed)
    
  414. 
    
  415.     Spec: http://backend.userland.com/rss091
    
  416. 
    
  417. ``Atom1Feed``
    
  418. -------------
    
  419. 
    
  420. .. class:: Atom1Feed(SyndicationFeed)
    
  421. 
    
  422.     Spec: :rfc:`4287`
    
  423. 
    
  424. ``django.utils.functional``
    
  425. ===========================
    
  426. 
    
  427. .. module:: django.utils.functional
    
  428.     :synopsis: Functional programming tools.
    
  429. 
    
  430. .. class:: cached_property(func, name=None)
    
  431. 
    
  432.     The ``@cached_property`` decorator caches the result of a method with a
    
  433.     single ``self`` argument as a property. The cached result will persist
    
  434.     as long as the instance does, so if the instance is passed around and the
    
  435.     function subsequently invoked, the cached result will be returned.
    
  436. 
    
  437.     Consider a typical case, where a view might need to call a model's method
    
  438.     to perform some computation, before placing the model instance into the
    
  439.     context, where the template might invoke the method once more::
    
  440. 
    
  441.         # the model
    
  442.         class Person(models.Model):
    
  443. 
    
  444.             def friends(self):
    
  445.                 # expensive computation
    
  446.                 ...
    
  447.                 return friends
    
  448. 
    
  449.         # in the view:
    
  450.         if person.friends():
    
  451.             ...
    
  452. 
    
  453.     And in the template you would have:
    
  454. 
    
  455.     .. code-block:: html+django
    
  456. 
    
  457.         {% for friend in person.friends %}
    
  458. 
    
  459.     Here, ``friends()`` will be called twice. Since the instance ``person`` in
    
  460.     the view and the template are the same, decorating the ``friends()`` method
    
  461.     with ``@cached_property`` can avoid that::
    
  462. 
    
  463.         from django.utils.functional import cached_property
    
  464. 
    
  465.         class Person(models.Model):
    
  466. 
    
  467.             @cached_property
    
  468.             def friends(self):
    
  469.                 ...
    
  470. 
    
  471.     Note that as the method is now a property, in Python code it will need to
    
  472.     be accessed appropriately::
    
  473. 
    
  474.         # in the view:
    
  475.         if person.friends:
    
  476.             ...
    
  477. 
    
  478.     The cached value can be treated like an ordinary attribute of the instance::
    
  479. 
    
  480.         # clear it, requiring re-computation next time it's called
    
  481.         del person.friends # or delattr(person, "friends")
    
  482. 
    
  483.         # set a value manually, that will persist on the instance until cleared
    
  484.         person.friends = ["Huckleberry Finn", "Tom Sawyer"]
    
  485. 
    
  486.     Because of the way the :py:ref:`descriptor protocol
    
  487.     <descriptor-invocation>` works, using ``del`` (or ``delattr``) on a
    
  488.     ``cached_property`` that hasn't been accessed raises ``AttributeError``.
    
  489. 
    
  490.     As well as offering potential performance advantages, ``@cached_property``
    
  491.     can ensure that an attribute's value does not change unexpectedly over the
    
  492.     life of an instance. This could occur with a method whose computation is
    
  493.     based on ``datetime.now()``, or if a change were saved to the database by
    
  494.     some other process in the brief interval between subsequent invocations of
    
  495.     a method on the same instance.
    
  496. 
    
  497.     You can make cached properties of methods. For example, if you had an
    
  498.     expensive ``get_friends()`` method and wanted to allow calling it without
    
  499.     retrieving the cached value, you could write::
    
  500. 
    
  501.         friends = cached_property(get_friends)
    
  502. 
    
  503.     While ``person.get_friends()`` will recompute the friends on each call, the
    
  504.     value of the cached property will persist until you delete it as described
    
  505.     above::
    
  506. 
    
  507.         x = person.friends         # calls first time
    
  508.         y = person.get_friends()   # calls again
    
  509.         z = person.friends         # does not call
    
  510.         x is z                     # is True
    
  511. 
    
  512.     .. deprecated:: 4.1
    
  513. 
    
  514.         The ``name`` parameter is deprecated and will be removed in Django 5.0
    
  515.         as it's unnecessary as of Python 3.6.
    
  516. 
    
  517. .. class:: classproperty(method=None)
    
  518. 
    
  519.     Similar to :py:func:`@classmethod <classmethod>`, the ``@classproperty``
    
  520.     decorator converts the result of a method with a single ``cls`` argument
    
  521.     into a property that can be accessed directly from the class.
    
  522. 
    
  523. .. function:: keep_lazy(func, *resultclasses)
    
  524. 
    
  525.     Django offers many utility functions (particularly in ``django.utils``)
    
  526.     that take a string as their first argument and do something to that string.
    
  527.     These functions are used by template filters as well as directly in other
    
  528.     code.
    
  529. 
    
  530.     If you write your own similar functions and deal with translations, you'll
    
  531.     face the problem of what to do when the first argument is a lazy
    
  532.     translation object. You don't want to convert it to a string immediately,
    
  533.     because you might be using this function outside of a view (and hence the
    
  534.     current thread's locale setting will not be correct).
    
  535. 
    
  536.     For cases like this, use the ``django.utils.functional.keep_lazy()``
    
  537.     decorator. It modifies the function so that *if* it's called with a lazy
    
  538.     translation as one of its arguments, the function evaluation is delayed
    
  539.     until it needs to be converted to a string.
    
  540. 
    
  541.     For example::
    
  542. 
    
  543.         from django.utils.functional import keep_lazy, keep_lazy_text
    
  544. 
    
  545.         def fancy_utility_function(s, ...):
    
  546.             # Do some conversion on string 's'
    
  547.             ...
    
  548.         fancy_utility_function = keep_lazy(str)(fancy_utility_function)
    
  549. 
    
  550.         # Or more succinctly:
    
  551.         @keep_lazy(str)
    
  552.         def fancy_utility_function(s, ...):
    
  553.             ...
    
  554. 
    
  555.     The ``keep_lazy()`` decorator takes a number of extra arguments (``*args``)
    
  556.     specifying the type(s) that the original function can return. A common
    
  557.     use case is to have functions that return text. For these, you can pass the
    
  558.     ``str`` type to ``keep_lazy`` (or use the :func:`keep_lazy_text` decorator
    
  559.     described in the next section).
    
  560. 
    
  561.     Using this decorator means you can write your function and assume that the
    
  562.     input is a proper string, then add support for lazy translation objects at
    
  563.     the end.
    
  564. 
    
  565. .. function:: keep_lazy_text(func)
    
  566. 
    
  567.     A shortcut for ``keep_lazy(str)(func)``.
    
  568. 
    
  569.     If you have a function that returns text and you want to be able to take
    
  570.     lazy arguments while delaying their evaluation, you can use this
    
  571.     decorator::
    
  572. 
    
  573.         from django.utils.functional import keep_lazy, keep_lazy_text
    
  574. 
    
  575.         # Our previous example was:
    
  576.         @keep_lazy(str)
    
  577.         def fancy_utility_function(s, ...):
    
  578.             ...
    
  579. 
    
  580.         # Which can be rewritten as:
    
  581.         @keep_lazy_text
    
  582.         def fancy_utility_function(s, ...):
    
  583.             ...
    
  584. 
    
  585. ``django.utils.html``
    
  586. =====================
    
  587. 
    
  588. .. module:: django.utils.html
    
  589.    :synopsis: HTML helper functions
    
  590. 
    
  591. Usually you should build up HTML using Django's templates to make use of its
    
  592. autoescape mechanism, using the utilities in :mod:`django.utils.safestring`
    
  593. where appropriate. This module provides some additional low level utilities for
    
  594. escaping HTML.
    
  595. 
    
  596. .. function:: escape(text)
    
  597. 
    
  598.     Returns the given text with ampersands, quotes and angle brackets encoded
    
  599.     for use in HTML. The input is first coerced to a string and the output has
    
  600.     :func:`~django.utils.safestring.mark_safe` applied.
    
  601. 
    
  602. .. function:: conditional_escape(text)
    
  603. 
    
  604.     Similar to ``escape()``, except that it doesn't operate on preescaped
    
  605.     strings, so it will not double escape.
    
  606. 
    
  607. .. function:: format_html(format_string, *args, **kwargs)
    
  608. 
    
  609.     This is similar to :meth:`str.format`, except that it is appropriate for
    
  610.     building up HTML fragments. All args and kwargs are passed through
    
  611.     :func:`conditional_escape` before being passed to ``str.format()``.
    
  612. 
    
  613.     For the case of building up small HTML fragments, this function is to be
    
  614.     preferred over string interpolation using ``%`` or ``str.format()``
    
  615.     directly, because it applies escaping to all arguments - just like the
    
  616.     template system applies escaping by default.
    
  617. 
    
  618.     So, instead of writing::
    
  619. 
    
  620.         mark_safe("%s <b>%s</b> %s" % (
    
  621.             some_html,
    
  622.             escape(some_text),
    
  623.             escape(some_other_text),
    
  624.         ))
    
  625. 
    
  626.     You should instead use::
    
  627. 
    
  628.         format_html("{} <b>{}</b> {}",
    
  629.             mark_safe(some_html),
    
  630.             some_text,
    
  631.             some_other_text,
    
  632.         )
    
  633. 
    
  634.     This has the advantage that you don't need to apply :func:`escape` to each
    
  635.     argument and risk a bug and an XSS vulnerability if you forget one.
    
  636. 
    
  637.     Note that although this function uses ``str.format()`` to do the
    
  638.     interpolation, some of the formatting options provided by ``str.format()``
    
  639.     (e.g. number formatting) will not work, since all arguments are passed
    
  640.     through :func:`conditional_escape` which (ultimately) calls
    
  641.     :func:`~django.utils.encoding.force_str` on the values.
    
  642. 
    
  643. .. function:: format_html_join(sep, format_string, args_generator)
    
  644. 
    
  645.     A wrapper of :func:`format_html`, for the common case of a group of
    
  646.     arguments that need to be formatted using the same format string, and then
    
  647.     joined using ``sep``. ``sep`` is also passed through
    
  648.     :func:`conditional_escape`.
    
  649. 
    
  650.     ``args_generator`` should be an iterator that returns the sequence of
    
  651.     ``args`` that will be passed to :func:`format_html`. For example::
    
  652. 
    
  653.         format_html_join(
    
  654.             '\n', "<li>{} {}</li>",
    
  655.             ((u.first_name, u.last_name) for u in users)
    
  656.         )
    
  657. 
    
  658. .. function:: json_script(value, element_id=None)
    
  659. 
    
  660.     Escapes all HTML/XML special characters with their Unicode escapes, so
    
  661.     value is safe for use with JavaScript. Also wraps the escaped JSON in a
    
  662.     ``<script>`` tag. If the ``element_id`` parameter is not ``None``, the
    
  663.     ``<script>`` tag is given the passed id. For example::
    
  664. 
    
  665.         >> json_script({"hello": "world"}, element_id="hello-data")
    
  666.         '<script id="hello-data" type="application/json">{"hello": "world"}</script>'
    
  667. 
    
  668.     .. versionchanged:: 4.1
    
  669. 
    
  670.         In older versions, the ``element_id`` argument was required.
    
  671. 
    
  672. .. function:: strip_tags(value)
    
  673. 
    
  674.     Tries to remove anything that looks like an HTML tag from the string, that
    
  675.     is anything contained within ``<>``.
    
  676. 
    
  677.     Absolutely NO guarantee is provided about the resulting string being
    
  678.     HTML safe. So NEVER mark safe the result of a ``strip_tag`` call without
    
  679.     escaping it first, for example with :func:`~django.utils.html.escape`.
    
  680. 
    
  681.     For example::
    
  682. 
    
  683.         strip_tags(value)
    
  684. 
    
  685.     If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"``
    
  686.     the return value will be ``"Joel is a slug"``.
    
  687. 
    
  688.     If you are looking for a more robust solution, take a look at the `bleach
    
  689.     <https://pypi.org/project/bleach/>`_ Python library.
    
  690. 
    
  691. .. function:: html_safe()
    
  692. 
    
  693.     The ``__html__()`` method on a class helps non-Django templates detect
    
  694.     classes whose output doesn't require HTML escaping.
    
  695. 
    
  696.     This decorator defines the ``__html__()`` method on the decorated class
    
  697.     by wrapping ``__str__()`` in :meth:`~django.utils.safestring.mark_safe`.
    
  698.     Ensure the ``__str__()`` method does indeed return text that doesn't
    
  699.     require HTML escaping.
    
  700. 
    
  701. ``django.utils.http``
    
  702. =====================
    
  703. 
    
  704. .. module:: django.utils.http
    
  705.    :synopsis: HTTP helper functions. (URL encoding, cookie handling, ...)
    
  706. 
    
  707. .. function:: urlencode(query, doseq=False)
    
  708. 
    
  709.     A version of Python's :func:`urllib.parse.urlencode` function that can
    
  710.     operate on ``MultiValueDict`` and non-string values.
    
  711. 
    
  712. .. function:: http_date(epoch_seconds=None)
    
  713. 
    
  714.     Formats the time to match the :rfc:`1123#section-5.2.14` date format as
    
  715.     specified by HTTP :rfc:`7231#section-7.1.1.1`.
    
  716. 
    
  717.     Accepts a floating point number expressed in seconds since the epoch in
    
  718.     UTC--such as that outputted by ``time.time()``. If set to ``None``,
    
  719.     defaults to the current time.
    
  720. 
    
  721.     Outputs a string in the format ``Wdy, DD Mon YYYY HH:MM:SS GMT``.
    
  722. 
    
  723. .. function:: base36_to_int(s)
    
  724. 
    
  725.     Converts a base 36 string to an integer.
    
  726. 
    
  727. .. function:: int_to_base36(i)
    
  728. 
    
  729.     Converts a positive integer to a base 36 string.
    
  730. 
    
  731. .. function:: urlsafe_base64_encode(s)
    
  732. 
    
  733.     Encodes a bytestring to a base64 string for use in URLs, stripping any
    
  734.     trailing equal signs.
    
  735. 
    
  736. .. function::  urlsafe_base64_decode(s)
    
  737. 
    
  738.     Decodes a base64 encoded string, adding back any trailing equal signs that
    
  739.     might have been stripped.
    
  740. 
    
  741. ``django.utils.module_loading``
    
  742. ===============================
    
  743. 
    
  744. .. module:: django.utils.module_loading
    
  745.    :synopsis: Functions for working with Python modules.
    
  746. 
    
  747. Functions for working with Python modules.
    
  748. 
    
  749. .. function:: import_string(dotted_path)
    
  750. 
    
  751.     Imports a dotted module path and returns the attribute/class designated by
    
  752.     the last name in the path. Raises ``ImportError`` if the import failed. For
    
  753.     example::
    
  754. 
    
  755.         from django.utils.module_loading import import_string
    
  756.         ValidationError = import_string('django.core.exceptions.ValidationError')
    
  757. 
    
  758.     is equivalent to::
    
  759. 
    
  760.         from django.core.exceptions import ValidationError
    
  761. 
    
  762. ``django.utils.safestring``
    
  763. ===========================
    
  764. 
    
  765. .. module:: django.utils.safestring
    
  766.    :synopsis: Functions and classes for working with strings that can be displayed safely without further escaping in HTML.
    
  767. 
    
  768. Functions and classes for working with "safe strings": strings that can be
    
  769. displayed safely without further escaping in HTML. Marking something as a "safe
    
  770. string" means that the producer of the string has already turned characters
    
  771. that should not be interpreted by the HTML engine (e.g. '<') into the
    
  772. appropriate entities.
    
  773. 
    
  774. .. class:: SafeString
    
  775. 
    
  776.     A ``str`` subclass that has been specifically marked as "safe" (requires no
    
  777.     further escaping) for HTML output purposes.
    
  778. 
    
  779. .. function:: mark_safe(s)
    
  780. 
    
  781.     Explicitly mark a string as safe for (HTML) output purposes. The returned
    
  782.     object can be used everywhere a string is appropriate.
    
  783. 
    
  784.     Can be called multiple times on a single string.
    
  785. 
    
  786.     Can also be used as a decorator.
    
  787. 
    
  788.     For building up fragments of HTML, you should normally be using
    
  789.     :func:`django.utils.html.format_html` instead.
    
  790. 
    
  791.     String marked safe will become unsafe again if modified. For example::
    
  792. 
    
  793.         >>> mystr = '<b>Hello World</b>   '
    
  794.         >>> mystr = mark_safe(mystr)
    
  795.         >>> type(mystr)
    
  796.         <class 'django.utils.safestring.SafeString'>
    
  797. 
    
  798.         >>> mystr = mystr.strip()  # removing whitespace
    
  799.         >>> type(mystr)
    
  800.         <type 'str'>
    
  801. 
    
  802. ``django.utils.text``
    
  803. =====================
    
  804. 
    
  805. .. module:: django.utils.text
    
  806.     :synopsis: Text manipulation.
    
  807. 
    
  808. .. function:: format_lazy(format_string, *args, **kwargs)
    
  809. 
    
  810.     A version of :meth:`str.format` for when ``format_string``, ``args``,
    
  811.     and/or ``kwargs`` contain lazy objects. The first argument is the string to
    
  812.     be formatted. For example::
    
  813. 
    
  814.         from django.utils.text import format_lazy
    
  815.         from django.utils.translation import pgettext_lazy
    
  816. 
    
  817.         urlpatterns = [
    
  818.             path(format_lazy('{person}/<int:pk>/', person=pgettext_lazy('URL', 'person')),
    
  819.                  PersonDetailView.as_view()),
    
  820.         ]
    
  821. 
    
  822.     This example allows translators to translate part of the URL. If "person"
    
  823.     is translated to "persona", the regular expression will match
    
  824.     ``persona/(?P<pk>\d+)/$``, e.g. ``persona/5/``.
    
  825. 
    
  826. .. function:: slugify(value, allow_unicode=False)
    
  827. 
    
  828.     Converts a string to a URL slug by:
    
  829. 
    
  830.     #. Converting to ASCII if ``allow_unicode`` is ``False`` (the default).
    
  831.     #. Converting to lowercase.
    
  832.     #. Removing characters that aren't alphanumerics, underscores, hyphens, or
    
  833.        whitespace.
    
  834.     #. Replacing any whitespace or repeated dashes with single dashes.
    
  835.     #. Removing leading and trailing whitespace, dashes, and underscores.
    
  836. 
    
  837.     For example::
    
  838. 
    
  839.         >>> slugify(' Joel is a slug ')
    
  840.         'joel-is-a-slug'
    
  841. 
    
  842.     If you want to allow Unicode characters, pass ``allow_unicode=True``. For
    
  843.     example::
    
  844. 
    
  845.         >>> slugify('你好 World', allow_unicode=True)
    
  846.         '你好-world'
    
  847. 
    
  848. .. _time-zone-selection-functions:
    
  849. 
    
  850. ``django.utils.timezone``
    
  851. =========================
    
  852. 
    
  853. .. module:: django.utils.timezone
    
  854.     :synopsis: Timezone support.
    
  855. 
    
  856. .. data:: utc
    
  857. 
    
  858.     :class:`~datetime.tzinfo` instance that represents UTC.
    
  859. 
    
  860.     .. deprecated:: 4.1
    
  861. 
    
  862.         This is an alias to :attr:`datetime.timezone.utc`. Use
    
  863.         :attr:`datetime.timezone.utc` directly.
    
  864. 
    
  865. .. function:: get_fixed_timezone(offset)
    
  866. 
    
  867.     Returns a :class:`~datetime.tzinfo` instance that represents a time zone
    
  868.     with a fixed offset from UTC.
    
  869. 
    
  870.     ``offset`` is a :class:`datetime.timedelta` or an integer number of
    
  871.     minutes. Use positive values for time zones east of UTC and negative
    
  872.     values for west of UTC.
    
  873. 
    
  874. .. function:: get_default_timezone()
    
  875. 
    
  876.     Returns a :class:`~datetime.tzinfo` instance that represents the
    
  877.     :ref:`default time zone <default-current-time-zone>`.
    
  878. 
    
  879. .. function:: get_default_timezone_name()
    
  880. 
    
  881.     Returns the name of the :ref:`default time zone
    
  882.     <default-current-time-zone>`.
    
  883. 
    
  884. .. function:: get_current_timezone()
    
  885. 
    
  886.     Returns a :class:`~datetime.tzinfo` instance that represents the
    
  887.     :ref:`current time zone <default-current-time-zone>`.
    
  888. 
    
  889. .. function:: get_current_timezone_name()
    
  890. 
    
  891.     Returns the name of the :ref:`current time zone
    
  892.     <default-current-time-zone>`.
    
  893. 
    
  894. .. function:: activate(timezone)
    
  895. 
    
  896.     Sets the :ref:`current time zone <default-current-time-zone>`. The
    
  897.     ``timezone`` argument must be an instance of a :class:`~datetime.tzinfo`
    
  898.     subclass or a time zone name.
    
  899. 
    
  900. .. function:: deactivate()
    
  901. 
    
  902.     Unsets the :ref:`current time zone <default-current-time-zone>`.
    
  903. 
    
  904. .. function:: override(timezone)
    
  905. 
    
  906.     This is a Python context manager that sets the :ref:`current time zone
    
  907.     <default-current-time-zone>` on entry with :func:`activate()`, and restores
    
  908.     the previously active time zone on exit. If the ``timezone`` argument is
    
  909.     ``None``, the :ref:`current time zone <default-current-time-zone>` is unset
    
  910.     on entry with :func:`deactivate()` instead.
    
  911. 
    
  912.     ``override`` is also usable as a function decorator.
    
  913. 
    
  914. .. function:: localtime(value=None, timezone=None)
    
  915. 
    
  916.     Converts an aware :class:`~datetime.datetime` to a different time zone,
    
  917.     by default the :ref:`current time zone <default-current-time-zone>`.
    
  918. 
    
  919.     When ``value`` is omitted, it defaults to :func:`now`.
    
  920. 
    
  921.     This function doesn't work on naive datetimes; use :func:`make_aware`
    
  922.     instead.
    
  923. 
    
  924. .. function:: localdate(value=None, timezone=None)
    
  925. 
    
  926.     Uses :func:`localtime` to convert an aware :class:`~datetime.datetime` to a
    
  927.     :meth:`~datetime.datetime.date` in a different time zone, by default the
    
  928.     :ref:`current time zone <default-current-time-zone>`.
    
  929. 
    
  930.     When ``value`` is omitted, it defaults to :func:`now`.
    
  931. 
    
  932.     This function doesn't work on naive datetimes.
    
  933. 
    
  934. .. function:: now()
    
  935. 
    
  936.     Returns a :class:`~datetime.datetime` that represents the
    
  937.     current point in time. Exactly what's returned depends on the value of
    
  938.     :setting:`USE_TZ`:
    
  939. 
    
  940.     * If :setting:`USE_TZ` is ``False``, this will be a
    
  941.       :ref:`naive <naive_vs_aware_datetimes>` datetime (i.e. a datetime
    
  942.       without an associated timezone) that represents the current time
    
  943.       in the system's local timezone.
    
  944. 
    
  945.     * If :setting:`USE_TZ` is ``True``, this will be an
    
  946.       :ref:`aware <naive_vs_aware_datetimes>` datetime representing the
    
  947.       current time in UTC. Note that :func:`now` will always return
    
  948.       times in UTC regardless of the value of :setting:`TIME_ZONE`;
    
  949.       you can use :func:`localtime` to get the time in the current time zone.
    
  950. 
    
  951. .. function:: is_aware(value)
    
  952. 
    
  953.     Returns ``True`` if ``value`` is aware, ``False`` if it is naive. This
    
  954.     function assumes that ``value`` is a :class:`~datetime.datetime`.
    
  955. 
    
  956. .. function:: is_naive(value)
    
  957. 
    
  958.     Returns ``True`` if ``value`` is naive, ``False`` if it is aware. This
    
  959.     function assumes that ``value`` is a :class:`~datetime.datetime`.
    
  960. 
    
  961. .. function:: make_aware(value, timezone=None, is_dst=None)
    
  962. 
    
  963.     Returns an aware :class:`~datetime.datetime` that represents the same
    
  964.     point in time as ``value`` in ``timezone``, ``value`` being a naive
    
  965.     :class:`~datetime.datetime`. If ``timezone`` is set to ``None``, it
    
  966.     defaults to the :ref:`current time zone <default-current-time-zone>`.
    
  967. 
    
  968.     .. deprecated:: 4.0
    
  969. 
    
  970.         When using ``pytz``, the ``pytz.AmbiguousTimeError`` exception is
    
  971.         raised if you try to make ``value`` aware during a DST transition where
    
  972.         the same time occurs twice (when reverting from DST). Setting
    
  973.         ``is_dst`` to ``True`` or ``False`` will avoid the exception by
    
  974.         choosing if the time is pre-transition or post-transition respectively.
    
  975. 
    
  976.         When using ``pytz``, the ``pytz.NonExistentTimeError`` exception is
    
  977.         raised if you try to make ``value`` aware during a DST transition such
    
  978.         that the time never occurred. For example, if the 2:00 hour is skipped
    
  979.         during a DST transition, trying to make 2:30 aware in that time zone
    
  980.         will raise an exception. To avoid that you can use ``is_dst`` to
    
  981.         specify how ``make_aware()`` should interpret such a nonexistent time.
    
  982.         If ``is_dst=True`` then the above time would be interpreted as 2:30 DST
    
  983.         time (equivalent to 1:30 local time). Conversely, if ``is_dst=False``
    
  984.         the time would be interpreted as 2:30 standard time (equivalent to 3:30
    
  985.         local time).
    
  986. 
    
  987.         The ``is_dst`` parameter has no effect when using non-``pytz`` timezone
    
  988.         implementations.
    
  989. 
    
  990.         The ``is_dst`` parameter is deprecated and will be removed in Django
    
  991.         5.0.
    
  992. 
    
  993. .. function:: make_naive(value, timezone=None)
    
  994. 
    
  995.     Returns a naive :class:`~datetime.datetime` that represents in
    
  996.     ``timezone``  the same point in time as ``value``, ``value`` being an
    
  997.     aware :class:`~datetime.datetime`. If ``timezone`` is set to ``None``, it
    
  998.     defaults to the :ref:`current time zone <default-current-time-zone>`.
    
  999. 
    
  1000. ``django.utils.translation``
    
  1001. ============================
    
  1002. 
    
  1003. .. module:: django.utils.translation
    
  1004.    :synopsis: Internationalization support.
    
  1005. 
    
  1006. For a complete discussion on the usage of the following see the
    
  1007. :doc:`translation documentation </topics/i18n/translation>`.
    
  1008. 
    
  1009. .. function:: gettext(message)
    
  1010. 
    
  1011.     Translates ``message`` and returns it as a string.
    
  1012. 
    
  1013. .. function:: pgettext(context, message)
    
  1014. 
    
  1015.     Translates ``message`` given the ``context`` and returns it as a string.
    
  1016. 
    
  1017.     For more information, see :ref:`contextual-markers`.
    
  1018. 
    
  1019. .. function:: gettext_lazy(message)
    
  1020. .. function:: pgettext_lazy(context, message)
    
  1021. 
    
  1022.     Same as the non-lazy versions above, but using lazy execution.
    
  1023. 
    
  1024.     See :ref:`lazy translations documentation <lazy-translations>`.
    
  1025. 
    
  1026. .. function:: gettext_noop(message)
    
  1027. 
    
  1028.     Marks strings for translation but doesn't translate them now. This can be
    
  1029.     used to store strings in global variables that should stay in the base
    
  1030.     language (because they might be used externally) and will be translated
    
  1031.     later.
    
  1032. 
    
  1033. .. function:: ngettext(singular, plural, number)
    
  1034. 
    
  1035.     Translates ``singular`` and ``plural`` and returns the appropriate string
    
  1036.     based on ``number``.
    
  1037. 
    
  1038. .. function:: npgettext(context, singular, plural, number)
    
  1039. 
    
  1040.     Translates ``singular`` and ``plural`` and returns the appropriate string
    
  1041.     based on ``number`` and the ``context``.
    
  1042. 
    
  1043. .. function:: ngettext_lazy(singular, plural, number)
    
  1044. .. function:: npgettext_lazy(context, singular, plural, number)
    
  1045. 
    
  1046.     Same as the non-lazy versions above, but using lazy execution.
    
  1047. 
    
  1048.     See :ref:`lazy translations documentation <lazy-translations>`.
    
  1049. 
    
  1050. .. function:: activate(language)
    
  1051. 
    
  1052.     Fetches the translation object for a given language and activates it as
    
  1053.     the current translation object for the current thread.
    
  1054. 
    
  1055. .. function:: deactivate()
    
  1056. 
    
  1057.     Deactivates the currently active translation object so that further _ calls
    
  1058.     will resolve against the default translation object, again.
    
  1059. 
    
  1060. .. function:: deactivate_all()
    
  1061. 
    
  1062.     Makes the active translation object a ``NullTranslations()`` instance.
    
  1063.     This is useful when we want delayed translations to appear as the original
    
  1064.     string for some reason.
    
  1065. 
    
  1066. .. function:: override(language, deactivate=False)
    
  1067. 
    
  1068.     A Python context manager that uses
    
  1069.     :func:`django.utils.translation.activate` to fetch the translation object
    
  1070.     for a given language, activates it as the translation object for the
    
  1071.     current thread and reactivates the previous active language on exit.
    
  1072.     Optionally, it can deactivate the temporary translation on exit with
    
  1073.     :func:`django.utils.translation.deactivate` if the ``deactivate`` argument
    
  1074.     is ``True``. If you pass ``None`` as the language argument, a
    
  1075.     ``NullTranslations()`` instance is activated within the context.
    
  1076. 
    
  1077.     ``override`` is also usable as a function decorator.
    
  1078. 
    
  1079. .. function:: check_for_language(lang_code)
    
  1080. 
    
  1081.     Checks whether there is a global language file for the given language
    
  1082.     code (e.g. 'fr', 'pt_BR'). This is used to decide whether a user-provided
    
  1083.     language is available.
    
  1084. 
    
  1085. .. function:: get_language()
    
  1086. 
    
  1087.     Returns the currently selected language code. Returns ``None`` if
    
  1088.     translations are temporarily deactivated (by :func:`deactivate_all()` or
    
  1089.     when ``None`` is passed to :func:`override()`).
    
  1090. 
    
  1091. .. function:: get_language_bidi()
    
  1092. 
    
  1093.     Returns selected language's BiDi layout:
    
  1094. 
    
  1095.     * ``False`` = left-to-right layout
    
  1096.     * ``True`` = right-to-left layout
    
  1097. 
    
  1098. .. function:: get_language_from_request(request, check_path=False)
    
  1099. 
    
  1100.     Analyzes the request to find what language the user wants the system to
    
  1101.     show. Only languages listed in settings.LANGUAGES are taken into account.
    
  1102.     If the user requests a sublanguage where we have a main language, we send
    
  1103.     out the main language.
    
  1104. 
    
  1105.     If ``check_path`` is ``True``, the function first checks the requested URL
    
  1106.     for whether its path begins with a language code listed in the
    
  1107.     :setting:`LANGUAGES` setting.
    
  1108. 
    
  1109. .. function:: get_supported_language_variant(lang_code, strict=False)
    
  1110. 
    
  1111.     Returns ``lang_code`` if it's in the :setting:`LANGUAGES` setting, possibly
    
  1112.     selecting a more generic variant. For example, ``'es'`` is returned if
    
  1113.     ``lang_code`` is ``'es-ar'`` and ``'es'`` is in :setting:`LANGUAGES` but
    
  1114.     ``'es-ar'`` isn't.
    
  1115. 
    
  1116.     If ``strict`` is ``False`` (the default), a country-specific variant may
    
  1117.     be returned when neither the language code nor its generic variant is found.
    
  1118.     For example, if only ``'es-co'`` is in :setting:`LANGUAGES`, that's
    
  1119.     returned for ``lang_code``\s like ``'es'`` and ``'es-ar'``. Those matches
    
  1120.     aren't returned if ``strict=True``.
    
  1121. 
    
  1122.     Raises :exc:`LookupError` if nothing is found.
    
  1123. 
    
  1124. .. function:: to_locale(language)
    
  1125. 
    
  1126.     Turns a language name (en-us) into a locale name (en_US).
    
  1127. 
    
  1128. .. function:: templatize(src)
    
  1129. 
    
  1130.     Turns a Django template into something that is understood by ``xgettext``.
    
  1131.     It does so by translating the Django translation tags into standard
    
  1132.     ``gettext`` function invocations.