[{"groupName":"","id":3,"nodeType":"Repo","repoName":"django#django#8328811f048fed0dd22573224def8c65410c9f2e","name":null,"path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":10,"nodeType":"Package","repoName":null,"name":"docs/ref","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":12,"nodeType":"Package","repoName":null,"name":"docs/faq","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":13,"nodeType":"Package","repoName":null,"name":"docs/man","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":16,"nodeType":"Package","repoName":null,"name":"docs/ref/files","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":19,"nodeType":"TextFile","repoName":null,"name":"middleware.txt","path":"docs/ref","text":"==========\nMiddleware\n==========\n\n.. module:: django.middleware\n   :synopsis: Django's built-in middleware classes.\n\nThis document explains all middleware components that come with Django. For\ninformation on how to use them and how to write your own middleware, see\nthe :doc:`middleware usage guide </topics/http/middleware>`.\n\nAvailable middleware\n====================\n\nCache middleware\n----------------\n\n.. module:: django.middleware.cache\n   :synopsis: Middleware for the site-wide cache.\n\n.. class:: UpdateCacheMiddleware\n\n.. class:: FetchFromCacheMiddleware\n\nEnable the site-wide cache. If these are enabled, each Django-powered page will\nbe cached for as long as the :setting:`CACHE_MIDDLEWARE_SECONDS` setting\ndefines. See the :doc:`cache documentation </topics/cache>`.\n\n\"Common\" middleware\n-------------------\n\n.. module:: django.middleware.common\n   :synopsis: Middleware adding \"common\" conveniences for perfectionists.\n\n.. class:: CommonMiddleware\n\nAdds a few conveniences for perfectionists:\n\n* Forbids access to user agents in the :setting:`DISALLOWED_USER_AGENTS`\n  setting, which should be a list of compiled regular expression objects.\n\n* Performs URL rewriting based on the :setting:`APPEND_SLASH` and\n  :setting:`PREPEND_WWW` settings.\n\n  If :setting:`APPEND_SLASH` is ``True`` and the initial URL doesn't end\n  with a slash, and it is not found in the URLconf, then a new URL is\n  formed by appending a slash at the end. If this new URL is found in the\n  URLconf, then Django redirects the request to this new URL. Otherwise,\n  the initial URL is processed as usual.\n\n  For example, ``foo.com/bar`` will be redirected to ``foo.com/bar/`` if\n  you don't have a valid URL pattern for ``foo.com/bar`` but *do* have a\n  valid pattern for ``foo.com/bar/``.\n\n  If :setting:`PREPEND_WWW` is ``True``, URLs that lack a leading \"www.\"\n  will be redirected to the same URL with a leading \"www.\"\n\n  Both of these options are meant to normalize URLs. The philosophy is that\n  each URL should exist in one, and only one, place. Technically a URL\n  ``foo.com/bar`` is distinct from ``foo.com/bar/`` -- a search-engine\n  indexer would treat them as separate URLs -- so it's best practice to\n  normalize URLs.\n\n* Sets the ``Content-Length`` header for non-streaming responses.\n\n.. attribute:: CommonMiddleware.response_redirect_class\n\nDefaults to :class:`~django.http.HttpResponsePermanentRedirect`. Subclass\n``CommonMiddleware`` and override the attribute to customize the redirects\nissued by the middleware.\n\n.. class:: BrokenLinkEmailsMiddleware\n\n* Sends broken link notification emails to :setting:`MANAGERS` (see\n  :doc:`/howto/error-reporting`).\n\nGZip middleware\n---------------\n\n.. module:: django.middleware.gzip\n   :synopsis: Middleware to serve GZipped content for performance.\n\n.. class:: GZipMiddleware\n\n.. warning::\n\n    Security researchers recently revealed that when compression techniques\n    (including ``GZipMiddleware``) are used on a website, the site may become\n    exposed to a number of possible attacks. Before using ``GZipMiddleware`` on\n    your site, you should consider very carefully whether you are subject to\n    these attacks. If you're in *any* doubt about whether you're affected, you\n    should avoid using ``GZipMiddleware``. For more details, see the `the BREACH\n    paper (PDF)`_ and `breachattack.com`_.\n\n    .. _the BREACH paper (PDF): http://breachattack.com/resources/BREACH%20-%20SSL,%20gone%20in%2030%20seconds.pdf\n    .. _breachattack.com: http://breachattack.com\n\nThe ``django.middleware.gzip.GZipMiddleware`` compresses content for browsers\nthat understand GZip compression (all modern browsers).\n\nThis middleware should be placed before any other middleware that need to\nread or write the response body so that compression happens afterward.\n\nIt will NOT compress content if any of the following are true:\n\n* The content body is less than 200 bytes long.\n\n* The response has already set the ``Content-Encoding`` header.\n\n* The request (the browser) hasn't sent an ``Accept-Encoding`` header\n  containing ``gzip``.\n\nIf the response has an ``ETag`` header, the ETag is made weak to comply with\n:rfc:`7232#section-2.1`.\n\nYou can apply GZip compression to individual views using the\n:func:`~django.views.decorators.gzip.gzip_page()` decorator.\n\nConditional GET middleware\n--------------------------\n\n.. module:: django.middleware.http\n   :synopsis: Middleware handling advanced HTTP features.\n\n.. class:: ConditionalGetMiddleware\n\nHandles conditional GET operations. If the response doesn't have an ``ETag``\nheader, the middleware adds one if needed. If the response has an ``ETag`` or\n``Last-Modified`` header, and the request has ``If-None-Match`` or\n``If-Modified-Since``, the response is replaced by an\n:class:`~django.http.HttpResponseNotModified`.\n\nLocale middleware\n-----------------\n\n.. module:: django.middleware.locale\n   :synopsis: Middleware to enable language selection based on the request.\n\n.. class:: LocaleMiddleware\n\nEnables language selection based on data from the request. It customizes\ncontent for each user. See the :doc:`internationalization documentation\n</topics/i18n/translation>`.\n\n.. attribute:: LocaleMiddleware.response_redirect_class\n\nDefaults to :class:`~django.http.HttpResponseRedirect`. Subclass\n``LocaleMiddleware`` and override the attribute to customize the redirects\nissued by the middleware.\n\nMessage middleware\n------------------\n\n.. module:: django.contrib.messages.middleware\n   :synopsis: Message middleware.\n\n.. class:: MessageMiddleware\n\nEnables cookie- and session-based message support. See the\n:doc:`messages documentation </ref/contrib/messages>`.\n\n.. _security-middleware:\n\nSecurity middleware\n-------------------\n\n.. module:: django.middleware.security\n    :synopsis: Security middleware.\n\n.. warning::\n    If your deployment situation allows, it's usually a good idea to have your\n    front-end Web server perform the functionality provided by the\n    ``SecurityMiddleware``. That way, if there are requests that aren't served\n    by Django (such as static media or user-uploaded files), they will have\n    the same protections as requests to your Django application.\n\n.. class:: SecurityMiddleware\n\nThe ``django.middleware.security.SecurityMiddleware`` provides several security\nenhancements to the request/response cycle. Each one can be independently\nenabled or disabled with a setting.\n\n* :setting:`SECURE_BROWSER_XSS_FILTER`\n* :setting:`SECURE_CONTENT_TYPE_NOSNIFF`\n* :setting:`SECURE_HSTS_INCLUDE_SUBDOMAINS`\n* :setting:`SECURE_HSTS_PRELOAD`\n* :setting:`SECURE_HSTS_SECONDS`\n* :setting:`SECURE_REDIRECT_EXEMPT`\n* :setting:`SECURE_REFERRER_POLICY`\n* :setting:`SECURE_SSL_HOST`\n* :setting:`SECURE_SSL_REDIRECT`\n\n.. _http-strict-transport-security:\n\nHTTP Strict Transport Security\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nFor sites that should only be accessed over HTTPS, you can instruct modern\nbrowsers to refuse to connect to your domain name via an insecure connection\n(for a given period of time) by setting the `\"Strict-Transport-Security\"\nheader`__. This reduces your exposure to some SSL-stripping man-in-the-middle\n(MITM) attacks.\n\n``SecurityMiddleware`` will set this header for you on all HTTPS responses if\nyou set the :setting:`SECURE_HSTS_SECONDS` setting to a non-zero integer value.\n\nWhen enabling HSTS, it's a good idea to first use a small value for testing,\nfor example, :setting:`SECURE_HSTS_SECONDS = 3600<SECURE_HSTS_SECONDS>` for one\nhour. Each time a Web browser sees the HSTS header from your site, it will\nrefuse to communicate non-securely (using HTTP) with your domain for the given\nperiod of time. Once you confirm that all assets are served securely on your\nsite (i.e. HSTS didn't break anything), it's a good idea to increase this value\nso that infrequent visitors will be protected (31536000 seconds, i.e. 1 year,\nis common).\n\nAdditionally, if you set the :setting:`SECURE_HSTS_INCLUDE_SUBDOMAINS` setting\nto ``True``, ``SecurityMiddleware`` will add the ``includeSubDomains`` directive\nto the ``Strict-Transport-Security`` header. This is recommended (assuming all\nsubdomains are served exclusively using HTTPS), otherwise your site may still\nbe vulnerable via an insecure connection to a subdomain.\n\nIf you wish to submit your site to the `browser preload list`_, set the\n:setting:`SECURE_HSTS_PRELOAD` setting to ``True``. That appends the\n``preload`` directive to the ``Strict-Transport-Security`` header.\n\n.. warning::\n    The HSTS policy applies to your entire domain, not just the URL of the\n    response that you set the header on. Therefore, you should only use it if\n    your entire domain is served via HTTPS only.\n\n    Browsers properly respecting the HSTS header will refuse to allow users to\n    bypass warnings and connect to a site with an expired, self-signed, or\n    otherwise invalid SSL certificate. If you use HSTS, make sure your\n    certificates are in good shape and stay that way!\n\n.. note::\n    If you are deployed behind a load-balancer or reverse-proxy server, and the\n    ``Strict-Transport-Security`` header is not being added to your responses,\n    it may be because Django doesn't realize that it's on a secure connection;\n    you may need to set the :setting:`SECURE_PROXY_SSL_HEADER` setting.\n\n__ https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security\n.. _browser preload list: https://hstspreload.org/\n\n.. _referrer-policy:\n\nReferrer Policy\n~~~~~~~~~~~~~~~\n\nBrowsers use `the Referer header`__ as a way to send information to a site\nabout how users got there. When a user clicks a link, the browser will send the\nfull URL of the linking page as the referrer. While this can be useful for some\npurposes -- like figuring out who's linking to your site -- it also can cause\nprivacy concerns by informing one site that a user was visiting another site.\n\n__ https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer\n\nSome browsers have the ability to accept hints about whether they should send\nthe HTTP ``Referer`` header when a user clicks a link; this hint is provided\nvia `the Referrer-Policy header`__. This header can suggest any of three\nbehaviors to browsers:\n\n__ https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy\n\n* Full URL: send the entire URL in the ``Referer`` header. For example, if the\n  user is visiting ``https://example.com/page.html``, the ``Referer`` header\n  would contain ``\"https://example.com/page.html\"``.\n\n* Origin only: send only the \"origin\" in the referrer. The origin consists of\n  the scheme, host and (optionally) port number. For example, if the user is\n  visiting ``https://example.com/page.html``, the origin would be\n  ``https://example.com/``.\n\n* No referrer: do not send a ``Referer`` header at all.\n\nThere are two types of conditions this header can tell a browser to watch out\nfor:\n\n* Same-origin versus cross-origin: a link from ``https://example.com/1.html``\n  to ``https://example.com/2.html`` is same-origin. A link from\n  ``https://example.com/page.html`` to ``https://not.example.com/page.html`` is\n  cross-origin.\n\n* Protocol downgrade: a downgrade occurs if the page containing the link is\n  served via HTTPS, but the page being linked to is not served via HTTPS.\n\n.. warning::\n    When your site is served via HTTPS, :ref:`Django's CSRF protection system\n    <using-csrf>` requires the ``Referer`` header to be present, so completely\n    disabling the ``Referer`` header will interfere with CSRF protection. To\n    gain most of the benefits of disabling ``Referer`` headers while also\n    keeping CSRF protection, consider enabling only same-origin referrers.\n\n``SecurityMiddleware`` can set the ``Referrer-Policy`` header for you, based on\nthe :setting:`SECURE_REFERRER_POLICY` setting (note spelling: browsers send a\n``Referer`` header when a user clicks a link, but the header instructing a\nbrowser whether to do so is spelled ``Referrer-Policy``). The valid values for\nthis setting are:\n\n``no-referrer``\n    Instructs the browser to send no referrer for links clicked on this site.\n\n``no-referrer-when-downgrade``\n    Instructs the browser to send a full URL as the referrer, but only when no\n    protocol downgrade occurs.\n\n``origin``\n    Instructs the browser to send only the origin, not the full URL, as the\n    referrer.\n\n``origin-when-cross-origin``\n    Instructs the browser to send the full URL as the referrer for same-origin\n    links, and only the origin for cross-origin links.\n\n``same-origin``\n    Instructs the browser to send a full URL, but only for same-origin links. No\n    referrer will be sent for cross-origin links.\n\n``strict-origin``\n    Instructs the browser to send only the origin, not the full URL, and to send\n    no referrer when a protocol downgrade occurs.\n\n``strict-origin-when-cross-origin``\n    Instructs the browser to send the full URL when the link is same-origin and\n    no protocol downgrade occurs; send only the origin when the link is\n    cross-origin and no protocol downgrade occurs; and no referrer when a\n    protocol downgrade occurs.\n\n``unsafe-url``\n    Instructs the browser to always send the full URL as the referrer.\n\n.. admonition:: Unknown Policy Values\n\n    Where a policy value is `unknown`__ by a user agent, it is possible to\n    specify multiple policy values to provide a fallback. The last specified\n    value that is understood takes precedence. To support this, an iterable or\n    comma-separated string can be used with :setting:`SECURE_REFERRER_POLICY`.\n\n    __ https://w3c.github.io/webappsec-referrer-policy/#unknown-policy-values\n\n.. _x-content-type-options:\n\n``X-Content-Type-Options: nosniff``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nSome browsers will try to guess the content types of the assets that they\nfetch, overriding the ``Content-Type`` header. While this can help display\nsites with improperly configured servers, it can also pose a security\nrisk.\n\nIf your site serves user-uploaded files, a malicious user could upload a\nspecially-crafted file that would be interpreted as HTML or JavaScript by\nthe browser when you expected it to be something harmless.\n\nTo prevent the browser from guessing the content type and force it to\nalways use the type provided in the ``Content-Type`` header, you can pass\nthe `X-Content-Type-Options: nosniff`__ header.  ``SecurityMiddleware`` will\ndo this for all responses if the :setting:`SECURE_CONTENT_TYPE_NOSNIFF` setting\nis ``True``.\n\nNote that in most deployment situations where Django isn't involved in serving\nuser-uploaded files, this setting won't help you. For example, if your\n:setting:`MEDIA_URL` is served directly by your front-end Web server (nginx,\nApache, etc.) then you'd want to set this header there. On the other hand, if\nyou are using Django to do something like require authorization in order to\ndownload files and you cannot set the header using your Web server, this\nsetting will be useful.\n\n__ https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options\n\n.. _x-xss-protection:\n\n``X-XSS-Protection: 1; mode=block``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nSome browsers have the ability to block content that appears to be an `XSS\nattack`_. They work by looking for JavaScript content in the GET or POST\nparameters of a page. If the JavaScript is replayed in the server's response,\nthe page is blocked from rendering and an error page is shown instead.\n\nThe `X-XSS-Protection header`__ is used to control the operation of the\nXSS filter.\n\nTo enable the XSS filter in the browser, and force it to always block\nsuspected XSS attacks, you can pass the ``X-XSS-Protection: 1; mode=block``\nheader. ``SecurityMiddleware`` will do this for all responses if the\n:setting:`SECURE_BROWSER_XSS_FILTER` setting is ``True``.\n\n.. warning::\n    The browser XSS filter is a useful defense measure, but must not be\n    relied upon exclusively. It cannot detect all XSS attacks and not all\n    browsers support the header. Ensure you are still :ref:`validating and\n    sanitizing <cross-site-scripting>` all input to prevent XSS attacks.\n\n.. _XSS attack: https://en.wikipedia.org/wiki/Cross-site_scripting\n__ https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection\n\n.. _ssl-redirect:\n\nSSL Redirect\n~~~~~~~~~~~~\n\nIf your site offers both HTTP and HTTPS connections, most users will end up\nwith an unsecured connection by default. For best security, you should redirect\nall HTTP connections to HTTPS.\n\nIf you set the :setting:`SECURE_SSL_REDIRECT` setting to True,\n``SecurityMiddleware`` will permanently (HTTP 301) redirect all HTTP\nconnections to HTTPS.\n\n.. note::\n\n    For performance reasons, it's preferable to do these redirects outside of\n    Django, in a front-end load balancer or reverse-proxy server such as\n    `nginx`_. :setting:`SECURE_SSL_REDIRECT` is intended for the deployment\n    situations where this isn't an option.\n\nIf the :setting:`SECURE_SSL_HOST` setting has a value, all redirects will be\nsent to that host instead of the originally-requested host.\n\nIf there are a few pages on your site that should be available over HTTP, and\nnot redirected to HTTPS, you can list regular expressions to match those URLs\nin the :setting:`SECURE_REDIRECT_EXEMPT` setting.\n\n.. note::\n    If you are deployed behind a load-balancer or reverse-proxy server and\n    Django can't seem to tell when a request actually is already secure, you\n    may need to set the :setting:`SECURE_PROXY_SSL_HEADER` setting.\n\n.. _nginx: https://nginx.org\n\nSession middleware\n------------------\n\n.. module:: django.contrib.sessions.middleware\n   :synopsis: Session middleware.\n\n.. class:: SessionMiddleware\n\nEnables session support. See the :doc:`session documentation\n</topics/http/sessions>`.\n\nSite middleware\n---------------\n\n.. module:: django.contrib.sites.middleware\n  :synopsis: Site middleware.\n\n.. class:: CurrentSiteMiddleware\n\nAdds the ``site`` attribute representing the current site to every incoming\n``HttpRequest`` object. See the :ref:`sites documentation <site-middleware>`.\n\nAuthentication middleware\n-------------------------\n\n.. module:: django.contrib.auth.middleware\n  :synopsis: Authentication middleware.\n\n.. class:: AuthenticationMiddleware\n\nAdds the ``user`` attribute, representing the currently-logged-in user, to\nevery incoming ``HttpRequest`` object. See :ref:`Authentication in Web requests\n<auth-web-requests>`.\n\n.. class:: RemoteUserMiddleware\n\nMiddleware for utilizing Web server provided authentication. See\n:doc:`/howto/auth-remote-user` for usage details.\n\n.. class:: PersistentRemoteUserMiddleware\n\nMiddleware for utilizing Web server provided authentication when enabled only\non the login page. See :ref:`persistent-remote-user-middleware-howto` for usage\ndetails.\n\nCSRF protection middleware\n--------------------------\n\n.. currentmodule:: django.middleware.csrf\n\n.. class:: CsrfViewMiddleware\n\nAdds protection against Cross Site Request Forgeries by adding hidden form\nfields to POST forms and checking requests for the correct value. See the\n:doc:`Cross Site Request Forgery protection documentation </ref/csrf>`.\n\n``X-Frame-Options`` middleware\n------------------------------\n\n.. currentmodule:: django.middleware.clickjacking\n\n.. class:: XFrameOptionsMiddleware\n\nSimple :doc:`clickjacking protection via the X-Frame-Options header </ref/clickjacking/>`.\n\n.. _middleware-ordering:\n\nMiddleware ordering\n===================\n\nHere are some hints about the ordering of various Django middleware classes:\n\n#. :class:`~django.middleware.security.SecurityMiddleware`\n\n   It should go near the top of the list if you're going to turn on the SSL\n   redirect as that avoids running through a bunch of other unnecessary\n   middleware.\n\n#. :class:`~django.middleware.cache.UpdateCacheMiddleware`\n\n   Before those that modify the ``Vary`` header (``SessionMiddleware``,\n   ``GZipMiddleware``, ``LocaleMiddleware``).\n\n#. :class:`~django.middleware.gzip.GZipMiddleware`\n\n   Before any middleware that may change or use the response body.\n\n   After ``UpdateCacheMiddleware``: Modifies ``Vary`` header.\n\n#. :class:`~django.contrib.sessions.middleware.SessionMiddleware`\n\n   Before any middleware that may raise an exception to trigger an error\n   view (such as :exc:`~django.core.exceptions.PermissionDenied`) if you're\n   using :setting:`CSRF_USE_SESSIONS`.\n\n   After ``UpdateCacheMiddleware``: Modifies ``Vary`` header.\n\n#. :class:`~django.middleware.http.ConditionalGetMiddleware`\n\n   Before any middleware that may change the response (it sets the ``ETag``\n   header).\n\n   After ``GZipMiddleware`` so it won't calculate an ``ETag`` header on gzipped\n   contents.\n\n#. :class:`~django.middleware.locale.LocaleMiddleware`\n\n   One of the topmost, after ``SessionMiddleware`` (uses session data) and\n   ``UpdateCacheMiddleware`` (modifies ``Vary`` header).\n\n#. :class:`~django.middleware.common.CommonMiddleware`\n\n   Before any middleware that may change the response (it sets the\n   ``Content-Length`` header). A middleware that appears before\n   ``CommonMiddleware`` and changes the response must reset ``Content-Length``.\n\n   Close to the top: it redirects when :setting:`APPEND_SLASH` or\n   :setting:`PREPEND_WWW` are set to ``True``.\n\n   After ``SessionMiddleware`` if you're using :setting:`CSRF_USE_SESSIONS`.\n\n#. :class:`~django.middleware.csrf.CsrfViewMiddleware`\n\n   Before any view middleware that assumes that CSRF attacks have been dealt\n   with.\n\n   Before :class:`~django.contrib.auth.middleware.RemoteUserMiddleware`, or any\n   other authentication middleware that may perform a login, and hence rotate\n   the CSRF token, before calling down the middleware chain.\n\n   After ``SessionMiddleware`` if you're using :setting:`CSRF_USE_SESSIONS`.\n\n#. :class:`~django.contrib.auth.middleware.AuthenticationMiddleware`\n\n   After ``SessionMiddleware``: uses session storage.\n\n#. :class:`~django.contrib.messages.middleware.MessageMiddleware`\n\n   After ``SessionMiddleware``: can use session-based storage.\n\n#. :class:`~django.middleware.cache.FetchFromCacheMiddleware`\n\n   After any middleware that modifies the ``Vary`` header: that header is used\n   to pick a value for the cache hash-key.\n\n#. :class:`~django.contrib.flatpages.middleware.FlatpageFallbackMiddleware`\n\n   Should be near the bottom as it's a last-resort type of middleware.\n\n#. :class:`~django.contrib.redirects.middleware.RedirectFallbackMiddleware`\n\n   Should be near the bottom as it's a last-resort type of middleware.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":20,"nodeType":"TextFile","repoName":null,"name":"storage.txt","path":"docs/ref/files","text":"================\nFile storage API\n================\n\n.. module:: django.core.files.storage\n\nGetting the current storage class\n=================================\n\nDjango provides two convenient ways to access the current storage class:\n\n.. class:: DefaultStorage\n\n    :class:`~django.core.files.storage.DefaultStorage` provides\n    lazy access to the current default storage system as defined by\n    :setting:`DEFAULT_FILE_STORAGE`. :class:`DefaultStorage` uses\n    :func:`~django.core.files.storage.get_storage_class` internally.\n\n.. function:: get_storage_class(import_path=None)\n\n    Returns a class or module which implements the storage API.\n\n    When called without the ``import_path`` parameter ``get_storage_class``\n    will return the current default storage system as defined by\n    :setting:`DEFAULT_FILE_STORAGE`. If ``import_path`` is provided,\n    ``get_storage_class`` will attempt to import the class or module from the\n    given path and will return it if successful. An exception will be\n    raised if the import is unsuccessful.\n\nThe ``FileSystemStorage`` class\n===============================\n\n.. class:: FileSystemStorage(location=None, base_url=None, file_permissions_mode=None, directory_permissions_mode=None)\n\n    The :class:`~django.core.files.storage.FileSystemStorage` class implements\n    basic file storage on a local filesystem. It inherits from\n    :class:`~django.core.files.storage.Storage` and provides implementations\n    for all the public methods thereof.\n\n    .. attribute:: location\n\n        Absolute path to the directory that will hold the files.\n        Defaults to the value of your :setting:`MEDIA_ROOT` setting.\n\n    .. attribute:: base_url\n\n        URL that serves the files stored at this location.\n        Defaults to the value of your :setting:`MEDIA_URL` setting.\n\n    .. attribute:: file_permissions_mode\n\n        The file system permissions that the file will receive when it is\n        saved. Defaults to :setting:`FILE_UPLOAD_PERMISSIONS`.\n\n    .. attribute:: directory_permissions_mode\n\n        The file system permissions that the directory will receive when it is\n        saved. Defaults to :setting:`FILE_UPLOAD_DIRECTORY_PERMISSIONS`.\n\n    .. note::\n\n        The ``FileSystemStorage.delete()`` method will not raise\n        an exception if the given file name does not exist.\n\n    .. method:: get_created_time(name)\n\n        Returns a :class:`~datetime.datetime` of the system's ctime, i.e.\n        :func:`os.path.getctime`. On some systems (like Unix), this is the\n        time of the last metadata change, and on others (like Windows), it's\n        the creation time of the file.\n\n.. versionchanged:: 3.1\n\n    Support for :class:`pathlib.Path` was added to the\n    ``FileSystemStorage.save()`` method.\n\nThe ``Storage`` class\n=====================\n\n.. class:: Storage\n\n    The :class:`~django.core.files.storage.Storage` class provides a\n    standardized API for storing files, along with a set of default\n    behaviors that all other storage systems can inherit or override\n    as necessary.\n\n    .. note::\n        When methods return naive ``datetime`` objects, the effective timezone\n        used will be the current value of ``os.environ['TZ']``; note that this\n        is usually set from Django's :setting:`TIME_ZONE`.\n\n    .. method:: delete(name)\n\n        Deletes the file referenced by ``name``. If deletion is not supported\n        on the target storage system this will raise ``NotImplementedError``\n        instead\n\n    .. method:: exists(name)\n\n        Returns ``True`` if a file referenced by the given name already exists\n        in the storage system, or ``False`` if the name is available for a new\n        file.\n\n    .. method:: get_accessed_time(name)\n\n        Returns a :class:`~datetime.datetime` of the last accessed time of the\n        file. For storage systems unable to return the last accessed time this\n        will raise :exc:`NotImplementedError`.\n\n        If :setting:`USE_TZ` is ``True``, returns an aware ``datetime``,\n        otherwise returns a naive ``datetime`` in the local timezone.\n\n    .. method:: get_alternative_name(file_root, file_ext)\n\n        Returns an alternative filename based on the ``file_root`` and\n        ``file_ext`` parameters, an underscore plus a random 7 character\n        alphanumeric string is appended to the filename before the extension.\n\n    .. method:: get_available_name(name, max_length=None)\n\n        Returns a filename based on the ``name`` parameter that's free and\n        available for new content to be written to on the target storage\n        system.\n\n        The length of the filename will not exceed ``max_length``, if provided.\n        If a free unique filename cannot be found, a\n        :exc:`SuspiciousFileOperation\n        <django.core.exceptions.SuspiciousOperation>` exception will be raised.\n\n        If a file with ``name`` already exists, :meth:`get_alternative_name` is\n        called to obtain an alternative name.\n\n    .. method:: get_created_time(name)\n\n        Returns a :class:`~datetime.datetime` of the creation time of the file.\n        For storage systems unable to return the creation time this will raise\n        :exc:`NotImplementedError`.\n\n        If :setting:`USE_TZ` is ``True``, returns an aware ``datetime``,\n        otherwise returns a naive ``datetime`` in the local timezone.\n\n    .. method:: get_modified_time(name)\n\n        Returns a :class:`~datetime.datetime` of the last modified time of the\n        file. For storage systems unable to return the last modified time this\n        will raise :exc:`NotImplementedError`.\n\n        If :setting:`USE_TZ` is ``True``, returns an aware ``datetime``,\n        otherwise returns a naive ``datetime`` in the local timezone.\n\n    .. method:: get_valid_name(name)\n\n        Returns a filename based on the ``name`` parameter that's suitable\n        for use on the target storage system.\n\n    .. method:: generate_filename(filename)\n\n        Validates the ``filename`` by calling :attr:`get_valid_name()` and\n        returns a filename to be passed to the :meth:`save` method.\n\n        The ``filename`` argument may include a path as returned by\n        :attr:`FileField.upload_to <django.db.models.FileField.upload_to>`.\n        In that case, the path won't be passed to :attr:`get_valid_name()` but\n        will be prepended back to the resulting name.\n\n        The default implementation uses :mod:`os.path` operations. Override\n        this method if that's not appropriate for your storage.\n\n    .. method:: listdir(path)\n\n        Lists the contents of the specified path, returning a 2-tuple of lists;\n        the first item being directories, the second item being files. For\n        storage systems that aren't able to provide such a listing, this will\n        raise a ``NotImplementedError`` instead.\n\n    .. method:: open(name, mode='rb')\n\n        Opens the file given by ``name``. Note that although the returned file\n        is guaranteed to be a ``File`` object, it might actually be some\n        subclass. In the case of remote file storage this means that\n        reading/writing could be quite slow, so be warned.\n\n    .. method:: path(name)\n\n        The local filesystem path where the file can be opened using Python's\n        standard ``open()``. For storage systems that aren't accessible from\n        the local filesystem, this will raise ``NotImplementedError`` instead.\n\n    .. method:: save(name, content, max_length=None)\n\n        Saves a new file using the storage system, preferably with the name\n        specified. If there already exists a file with this name ``name``, the\n        storage system may modify the filename as necessary to get a unique\n        name. The actual name of the stored file will be returned.\n\n        The ``max_length`` argument is passed along to\n        :meth:`get_available_name`.\n\n        The ``content`` argument must be an instance of\n        :class:`django.core.files.File` or a file-like object that can be\n        wrapped in ``File``.\n\n    .. method:: size(name)\n\n        Returns the total size, in bytes, of the file referenced by ``name``.\n        For storage systems that aren't able to return the file size this will\n        raise ``NotImplementedError`` instead.\n\n    .. method:: url(name)\n\n        Returns the URL where the contents of the file referenced by ``name``\n        can be accessed. For storage systems that don't support access by URL\n        this will raise ``NotImplementedError`` instead.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":22,"nodeType":"TextFile","repoName":null,"name":"unicode.txt","path":"docs/ref","text":"============\nUnicode data\n============\n\nDjango supports Unicode data everywhere.\n\nThis document tells you what you need to know if you're writing applications\nthat use data or templates that are encoded in something other than ASCII.\n\nCreating the database\n=====================\n\nMake sure your database is configured to be able to store arbitrary string\ndata. Normally, this means giving it an encoding of UTF-8 or UTF-16. If you use\na more restrictive encoding -- for example, latin1 (iso8859-1) -- you won't be\nable to store certain characters in the database, and information will be lost.\n\n* MySQL users, refer to the `MySQL manual`_ for details on how to set or alter\n  the database character set encoding.\n\n* PostgreSQL users, refer to the `PostgreSQL manual`_ (section 22.3.2 in\n  PostgreSQL 9) for details on creating databases with the correct encoding.\n\n* Oracle users, refer to the `Oracle manual`_ for details on how to set\n  (`section 2`_) or alter (`section 11`_) the database character set encoding.\n\n* SQLite users, there is nothing you need to do. SQLite always uses UTF-8\n  for internal encoding.\n\n.. _MySQL manual: https://dev.mysql.com/doc/refman/en/charset-database.html\n.. _PostgreSQL manual: https://www.postgresql.org/docs/current/multibyte.html\n.. _Oracle manual: https://docs.oracle.com/en/database/oracle/oracle-database/18/nlspg/index.html\n.. _section 2: https://docs.oracle.com/en/database/oracle/oracle-database/18/nlspg/choosing-character-set.html\n.. _section 11: https://docs.oracle.com/en/database/oracle/oracle-database/18/nlspg/character-set-migration.html\n\nAll of Django's database backends automatically convert strings into\nthe appropriate encoding for talking to the database. They also automatically\nconvert strings retrieved from the database into strings. You don't even need\nto tell Django what encoding your database uses: that is handled transparently.\n\nFor more, see the section \"The database API\" below.\n\nGeneral string handling\n=======================\n\nWhenever you use strings with Django -- e.g., in database lookups, template\nrendering or anywhere else -- you have two choices for encoding those strings.\nYou can use normal strings or bytestrings (starting with a 'b').\n\n.. warning::\n\n    A bytestring does not carry any information with it about its encoding.\n    For that reason, we have to make an assumption, and Django assumes that all\n    bytestrings are in UTF-8.\n\n    If you pass a string to Django that has been encoded in some other format,\n    things will go wrong in interesting ways. Usually, Django will raise a\n    ``UnicodeDecodeError`` at some point.\n\nIf your code only uses ASCII data, it's safe to use your normal strings,\npassing them around at will, because ASCII is a subset of UTF-8.\n\nDon't be fooled into thinking that if your :setting:`DEFAULT_CHARSET` setting is set\nto something other than ``'utf-8'`` you can use that other encoding in your\nbytestrings! :setting:`DEFAULT_CHARSET` only applies to the strings generated as\nthe result of template rendering (and email). Django will always assume UTF-8\nencoding for internal bytestrings. The reason for this is that the\n:setting:`DEFAULT_CHARSET` setting is not actually under your control (if you are the\napplication developer). It's under the control of the person installing and\nusing your application -- and if that person chooses a different setting, your\ncode must still continue to work. Ergo, it cannot rely on that setting.\n\nIn most cases when Django is dealing with strings, it will convert them to\nstrings before doing anything else. So, as a general rule, if you pass\nin a bytestring, be prepared to receive a string back in the result.\n\nTranslated strings\n------------------\n\nAside from strings and bytestrings, there's a third type of string-like\nobject you may encounter when using Django. The framework's\ninternationalization features introduce the concept of a \"lazy translation\" --\na string that has been marked as translated but whose actual translation result\nisn't determined until the object is used in a string. This feature is useful\nin cases where the translation locale is unknown until the string is used, even\nthough the string might have originally been created when the code was first\nimported.\n\nNormally, you won't have to worry about lazy translations. Just be aware that\nif you examine an object and it claims to be a\n``django.utils.functional.__proxy__`` object, it is a lazy translation.\nCalling ``str()`` with the lazy translation as the argument will generate a\nstring in the current locale.\n\nFor more details about lazy translation objects, refer to the\n:doc:`internationalization </topics/i18n/index>` documentation.\n\nUseful utility functions\n------------------------\n\nBecause some string operations come up again and again, Django ships with a few\nuseful functions that should make working with string and bytestring objects\na bit easier.\n\nConversion functions\n~~~~~~~~~~~~~~~~~~~~\n\nThe ``django.utils.encoding`` module contains a few functions that are handy\nfor converting back and forth between strings and bytestrings.\n\n* ``smart_str(s, encoding='utf-8', strings_only=False, errors='strict')``\n  converts its input to a string. The ``encoding`` parameter\n  specifies the input encoding. (For example, Django uses this internally\n  when processing form input data, which might not be UTF-8 encoded.) The\n  ``strings_only`` parameter, if set to True, will result in Python\n  numbers, booleans and ``None`` not being converted to a string (they keep\n  their original types). The ``errors`` parameter takes any of the values\n  that are accepted by Python's ``str()`` function for its error\n  handling.\n\n* ``force_str(s, encoding='utf-8', strings_only=False, errors='strict')`` is\n  identical to ``smart_str()`` in almost all cases. The difference is when the\n  first argument is a :ref:`lazy translation <lazy-translations>` instance.\n  While ``smart_str()`` preserves lazy translations, ``force_str()`` forces\n  those objects to a string (causing the translation to occur). Normally,\n  you'll want to use ``smart_str()``. However, ``force_str()`` is useful in\n  template tags and filters that absolutely *must* have a string to work with,\n  not just something that can be converted to a string.\n\n* ``smart_bytes(s, encoding='utf-8', strings_only=False, errors='strict')``\n  is essentially the opposite of ``smart_str()``. It forces the first\n  argument to a bytestring. The ``strings_only`` parameter has the same\n  behavior as for ``smart_str()`` and ``force_str()``. This is\n  slightly different semantics from Python's builtin ``str()`` function,\n  but the difference is needed in a few places within Django's internals.\n\nNormally, you'll only need to use ``force_str()``. Call it as early as\npossible on any input data that might be either a string or a bytestring, and\nfrom then on, you can treat the result as always being a string.\n\n.. _uri-and-iri-handling:\n\nURI and IRI handling\n~~~~~~~~~~~~~~~~~~~~\n\nWeb frameworks have to deal with URLs (which are a type of IRI). One\nrequirement of URLs is that they are encoded using only ASCII characters.\nHowever, in an international environment, you might need to construct a\nURL from an :rfc:`IRI <3987>` -- very loosely speaking, a :rfc:`URI <2396>`\nthat can contain Unicode characters. Use these functions for quoting and\nconverting an IRI to a URI:\n\n* The :func:`django.utils.encoding.iri_to_uri()` function, which implements the\n  conversion from IRI to URI as required by :rfc:`3987#section-3.1`.\n\n* The :func:`urllib.parse.quote` and :func:`urllib.parse.quote_plus`\n  functions from Python's standard library.\n\nThese two groups of functions have slightly different purposes, and it's\nimportant to keep them straight. Normally, you would use ``quote()`` on the\nindividual portions of the IRI or URI path so that any reserved characters\nsuch as '&' or '%' are correctly encoded. Then, you apply ``iri_to_uri()`` to\nthe full IRI and it converts any non-ASCII characters to the correct encoded\nvalues.\n\n.. note::\n    Technically, it isn't correct to say that ``iri_to_uri()`` implements the\n    full algorithm in the IRI specification. It doesn't (yet) perform the\n    international domain name encoding portion of the algorithm.\n\nThe ``iri_to_uri()`` function will not change ASCII characters that are\notherwise permitted in a URL. So, for example, the character '%' is not\nfurther encoded when passed to ``iri_to_uri()``. This means you can pass a\nfull URL to this function and it will not mess up the query string or anything\nlike that.\n\nAn example might clarify things here::\n\n    >>> from urllib.parse import quote\n    >>> from django.utils.encoding import iri_to_uri\n    >>> quote('Paris & Orléans')\n    'Paris%20%26%20Orl%C3%A9ans'\n    >>> iri_to_uri('/favorites/François/%s' % quote('Paris & Orléans'))\n    '/favorites/Fran%C3%A7ois/Paris%20%26%20Orl%C3%A9ans'\n\nIf you look carefully, you can see that the portion that was generated by\n``quote()`` in the second example was not double-quoted when passed to\n``iri_to_uri()``. This is a very important and useful feature. It means that\nyou can construct your IRI without worrying about whether it contains\nnon-ASCII characters and then, right at the end, call ``iri_to_uri()`` on the\nresult.\n\nSimilarly, Django provides :func:`django.utils.encoding.uri_to_iri()` which\nimplements the conversion from URI to IRI as per :rfc:`3987#section-3.2`.\n\nAn example to demonstrate::\n\n    >>> from django.utils.encoding import uri_to_iri\n    >>> uri_to_iri('/%E2%99%A5%E2%99%A5/?utf8=%E2%9C%93')\n    '/♥♥/?utf8=✓'\n    >>> uri_to_iri('%A9hello%3Fworld')\n    '%A9hello%3Fworld'\n\nIn the first example, the UTF-8 characters are unquoted. In the second, the\npercent-encodings remain unchanged because they lie outside the valid UTF-8\nrange or represent a reserved character.\n\nBoth ``iri_to_uri()`` and ``uri_to_iri()`` functions are idempotent, which means the\nfollowing is always true::\n\n    iri_to_uri(iri_to_uri(some_string)) == iri_to_uri(some_string)\n    uri_to_iri(uri_to_iri(some_string)) == uri_to_iri(some_string)\n\nSo you can safely call it multiple times on the same URI/IRI without risking\ndouble-quoting problems.\n\nModels\n======\n\nBecause all strings are returned from the database as ``str`` objects, model\nfields that are character based (CharField, TextField, URLField, etc.) will\ncontain Unicode values when Django retrieves data from the database. This\nis *always* the case, even if the data could fit into an ASCII bytestring.\n\nYou can pass in bytestrings when creating a model or populating a field, and\nDjango will convert it to strings when it needs to.\n\nTaking care in ``get_absolute_url()``\n-------------------------------------\n\nURLs can only contain ASCII characters. If you're constructing a URL from\npieces of data that might be non-ASCII, be careful to encode the results in a\nway that is suitable for a URL. The :func:`~django.urls.reverse` function\nhandles this for you automatically.\n\nIf you're constructing a URL manually (i.e., *not* using the ``reverse()``\nfunction), you'll need to take care of the encoding yourself. In this case,\nuse the ``iri_to_uri()`` and ``quote()`` functions that were documented\nabove_. For example::\n\n    from urllib.parse import quote\n    from django.utils.encoding import iri_to_uri\n\n    def get_absolute_url(self):\n        url = '/person/%s/?x=0&y=0' % quote(self.location)\n        return iri_to_uri(url)\n\nThis function returns a correctly encoded URL even if ``self.location`` is\nsomething like \"Jack visited Paris & Orléans\". (In fact, the ``iri_to_uri()``\ncall isn't strictly necessary in the above example, because all the\nnon-ASCII characters would have been removed in quoting in the first line.)\n\n.. _above: `URI and IRI handling`_\n\nTemplates\n=========\n\nUse strings when creating templates manually::\n\n    from django.template import Template\n    t2 = Template('This is a string template.')\n\nBut the common case is to read templates from the filesystem. If your template\nfiles are not stored with a UTF-8 encoding, adjust the :setting:`TEMPLATES`\nsetting. The built-in :py:mod:`~django.template.backends.django` backend\nprovides the ``'file_charset'`` option to change the encoding used to read\nfiles from disk.\n\nThe :setting:`DEFAULT_CHARSET` setting controls the encoding of rendered templates.\nThis is set to UTF-8 by default.\n\nTemplate tags and filters\n-------------------------\n\nA couple of tips to remember when writing your own template tags and filters:\n\n* Always return strings from a template tag's ``render()`` method\n  and from template filters.\n\n* Use ``force_str()`` in preference to ``smart_str()`` in these\n  places. Tag rendering and filter calls occur as the template is being\n  rendered, so there is no advantage to postponing the conversion of lazy\n  translation objects into strings. It's easier to work solely with\n  strings at that point.\n\n.. _unicode-files:\n\nFiles\n=====\n\nIf you intend to allow users to upload files, you must ensure that the\nenvironment used to run Django is configured to work with non-ASCII file names.\nIf your environment isn't configured correctly, you'll encounter\n``UnicodeEncodeError`` exceptions when saving files with file names that\ncontain non-ASCII characters.\n\nFilesystem support for UTF-8 file names varies and might depend on the\nenvironment. Check your current configuration in an interactive Python shell by\nrunning::\n\n    import sys\n    sys.getfilesystemencoding()\n\nThis should output \"UTF-8\".\n\nThe ``LANG`` environment variable is responsible for setting the expected\nencoding on Unix platforms. Consult the documentation for your operating system\nand application server for the appropriate syntax and location to set this\nvariable.\n\nIn your development environment, you might need to add a setting to your\n``~.bashrc`` analogous to:::\n\n    export LANG=\"en_US.UTF-8\"\n\nForm submission\n===============\n\nHTML form submission is a tricky area. There's no guarantee that the\nsubmission will include encoding information, which means the framework might\nhave to guess at the encoding of submitted data.\n\nDjango adopts a \"lazy\" approach to decoding form data. The data in an\n``HttpRequest`` object is only decoded when you access it. In fact, most of\nthe data is not decoded at all. Only the ``HttpRequest.GET`` and\n``HttpRequest.POST`` data structures have any decoding applied to them. Those\ntwo fields will return their members as Unicode data. All other attributes and\nmethods of ``HttpRequest`` return data exactly as it was submitted by the\nclient.\n\nBy default, the :setting:`DEFAULT_CHARSET` setting is used as the assumed encoding\nfor form data. If you need to change this for a particular form, you can set\nthe ``encoding`` attribute on an ``HttpRequest`` instance. For example::\n\n    def some_view(request):\n        # We know that the data must be encoded as KOI8-R (for some reason).\n        request.encoding = 'koi8-r'\n        ...\n\nYou can even change the encoding after having accessed ``request.GET`` or\n``request.POST``, and all subsequent accesses will use the new encoding.\n\nMost developers won't need to worry about changing form encoding, but this is\na useful feature for applications that talk to legacy systems whose encoding\nyou cannot control.\n\nDjango does not decode the data of file uploads, because that data is normally\ntreated as collections of bytes, rather than strings. Any automatic decoding\nthere would alter the meaning of the stream of bytes.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":23,"nodeType":"TextFile","repoName":null,"name":"uploads.txt","path":"docs/ref/files","text":"==================================\nUploaded Files and Upload Handlers\n==================================\n\n.. module:: django.core.files.uploadedfile\n   :synopsis: Classes representing uploaded files.\n\nUploaded files\n==============\n\n.. class:: UploadedFile\n\nDuring file uploads, the actual file data is stored in :attr:`request.FILES\n<django.http.HttpRequest.FILES>`. Each entry in this dictionary is an\n``UploadedFile`` object (or a subclass) -- a wrapper around an uploaded file.\nYou'll usually use one of these methods to access the uploaded content:\n\n.. method:: UploadedFile.read()\n\n    Read the entire uploaded data from the file. Be careful with this method:\n    if the uploaded file is huge it can overwhelm your system if you try to\n    read it into memory. You'll probably want to use ``chunks()`` instead; see\n    below.\n\n.. method:: UploadedFile.multiple_chunks(chunk_size=None)\n\n    Returns ``True`` if the uploaded file is big enough to require reading in\n    multiple chunks. By default this will be any file larger than 2.5 megabytes,\n    but that's configurable; see below.\n\n.. method:: UploadedFile.chunks(chunk_size=None)\n\n    A generator returning chunks of the file. If ``multiple_chunks()`` is\n    ``True``, you should use this method in a loop instead of ``read()``.\n\n    In practice, it's often easiest to use ``chunks()`` all the time. Looping\n    over ``chunks()`` instead of using ``read()`` ensures that large files\n    don't overwhelm your system's memory.\n\nHere are some useful attributes of ``UploadedFile``:\n\n.. attribute:: UploadedFile.name\n\n    The name of the uploaded file (e.g. ``my_file.txt``).\n\n.. attribute:: UploadedFile.size\n\n    The size, in bytes, of the uploaded file.\n\n.. attribute:: UploadedFile.content_type\n\n    The content-type header uploaded with the file (e.g. :mimetype:`text/plain`\n    or :mimetype:`application/pdf`). Like any data supplied by the user, you\n    shouldn't trust that the uploaded file is actually this type. You'll still\n    need to validate that the file contains the content that the content-type\n    header claims -- \"trust but verify.\"\n\n.. attribute:: UploadedFile.content_type_extra\n\n    A dictionary containing extra parameters passed to the ``content-type``\n    header. This is typically provided by services, such as Google App Engine,\n    that intercept and handle file uploads on your behalf. As a result your\n    handler may not receive the uploaded file content, but instead a URL or\n    other pointer to the file (see :rfc:`RFC 2388 <2388#section-5.3>`).\n\n.. attribute:: UploadedFile.charset\n\n    For :mimetype:`text/*` content-types, the character set (i.e. ``utf8``)\n    supplied by the browser. Again, \"trust but verify\" is the best policy here.\n\n.. note::\n\n    Like regular Python files, you can read the file line-by-line by iterating\n    over the uploaded file::\n\n        for line in uploadedfile:\n            do_something_with(line)\n\n    Lines are split using :pep:`universal newlines <278>`. The following are\n    recognized as ending a line: the Unix end-of-line convention ``'\\n'``, the\n    Windows convention ``'\\r\\n'``, and the old Macintosh convention ``'\\r'``.\n\nSubclasses of ``UploadedFile`` include:\n\n.. class:: TemporaryUploadedFile\n\n    A file uploaded to a temporary location (i.e. stream-to-disk). This class\n    is used by the\n    :class:`~django.core.files.uploadhandler.TemporaryFileUploadHandler`. In\n    addition to the methods from :class:`UploadedFile`, it has one additional\n    method:\n\n.. method:: TemporaryUploadedFile.temporary_file_path()\n\n    Returns the full path to the temporary uploaded file.\n\n.. class:: InMemoryUploadedFile\n\n    A file uploaded into memory (i.e. stream-to-memory). This class is used\n    by the :class:`~django.core.files.uploadhandler.MemoryFileUploadHandler`.\n\nBuilt-in upload handlers\n========================\n\n.. module:: django.core.files.uploadhandler\n   :synopsis: Django's handlers for file uploads.\n\nTogether the :class:`MemoryFileUploadHandler` and\n:class:`TemporaryFileUploadHandler` provide Django's default file upload\nbehavior of reading small files into memory and large ones onto disk. They\nare located in ``django.core.files.uploadhandler``.\n\n.. class:: MemoryFileUploadHandler\n\nFile upload handler to stream uploads into memory (used for small files).\n\n.. class:: TemporaryFileUploadHandler\n\nUpload handler that streams data into a temporary file using\n:class:`~django.core.files.uploadedfile.TemporaryUploadedFile`.\n\n.. _custom_upload_handlers:\n\nWriting custom upload handlers\n==============================\n\n.. class:: FileUploadHandler\n\nAll file upload handlers should be subclasses of\n``django.core.files.uploadhandler.FileUploadHandler``. You can define upload\nhandlers wherever you wish.\n\nRequired methods\n----------------\n\nCustom file upload handlers **must** define the following methods:\n\n.. method:: FileUploadHandler.receive_data_chunk(raw_data, start)\n\n    Receives a \"chunk\" of data from the file upload.\n\n    ``raw_data`` is a bytestring containing the uploaded data.\n\n    ``start`` is the position in the file where this ``raw_data`` chunk\n    begins.\n\n    The data you return will get fed into the subsequent upload handlers'\n    ``receive_data_chunk`` methods. In this way, one handler can be a\n    \"filter\" for other handlers.\n\n    Return ``None`` from ``receive_data_chunk`` to short-circuit remaining\n    upload handlers from getting this chunk. This is useful if you're\n    storing the uploaded data yourself and don't want future handlers to\n    store a copy of the data.\n\n    If you raise a ``StopUpload`` or a ``SkipFile`` exception, the upload\n    will abort or the file will be completely skipped.\n\n.. method:: FileUploadHandler.file_complete(file_size)\n\n    Called when a file has finished uploading.\n\n    The handler should return an ``UploadedFile`` object that will be stored\n    in ``request.FILES``. Handlers may also return ``None`` to indicate that\n    the ``UploadedFile`` object should come from subsequent upload handlers.\n\nOptional methods\n----------------\n\nCustom upload handlers may also define any of the following optional methods or\nattributes:\n\n.. attribute:: FileUploadHandler.chunk_size\n\n    Size, in bytes, of the \"chunks\" Django should store into memory and feed\n    into the handler. That is, this attribute controls the size of chunks\n    fed into ``FileUploadHandler.receive_data_chunk``.\n\n    For maximum performance the chunk sizes should be divisible by ``4`` and\n    should not exceed 2 GB (2\\ :sup:`31` bytes) in size. When there are\n    multiple chunk sizes provided by multiple handlers, Django will use the\n    smallest chunk size defined by any handler.\n\n    The default is 64*2\\ :sup:`10` bytes, or 64 KB.\n\n.. method:: FileUploadHandler.new_file(field_name, file_name, content_type, content_length, charset, content_type_extra)\n\n    Callback signaling that a new file upload is starting. This is called\n    before any data has been fed to any upload handlers.\n\n    ``field_name`` is a string name of the file ``<input>`` field.\n\n    ``file_name`` is the filename provided by the browser.\n\n    ``content_type`` is the MIME type provided by the browser -- E.g.\n    ``'image/jpeg'``.\n\n    ``content_length`` is the length of the image given by the browser.\n    Sometimes this won't be provided and will be ``None``.\n\n    ``charset`` is the character set (i.e. ``utf8``) given by the browser.\n    Like ``content_length``, this sometimes won't be provided.\n\n    ``content_type_extra`` is extra information about the file from the\n    ``content-type`` header. See :attr:`UploadedFile.content_type_extra\n    <django.core.files.uploadedfile.UploadedFile.content_type_extra>`.\n\n    This method may raise a ``StopFutureHandlers`` exception to prevent\n    future handlers from handling this file.\n\n.. method:: FileUploadHandler.upload_complete()\n\n    Callback signaling that the entire upload (all files) has completed.\n\n.. method:: FileUploadHandler.handle_raw_input(input_data, META, content_length, boundary, encoding)\n\n    Allows the handler to completely override the parsing of the raw\n    HTTP input.\n\n    ``input_data`` is a file-like object that supports ``read()``-ing.\n\n    ``META`` is the same object as ``request.META``.\n\n    ``content_length`` is the length of the data in ``input_data``. Don't\n    read more than ``content_length`` bytes from ``input_data``.\n\n    ``boundary`` is the MIME boundary for this request.\n\n    ``encoding`` is the encoding of the request.\n\n    Return ``None`` if you want upload handling to continue, or a tuple of\n    ``(POST, FILES)`` if you want to return the new data structures suitable\n    for the request directly.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":24,"nodeType":"TextFile","repoName":null,"name":"install.txt","path":"docs/faq","text":"=================\nFAQ: Installation\n=================\n\nHow do I get started?\n=====================\n\n#. `Download the code`_.\n#. Install Django (read the :doc:`installation guide </intro/install>`).\n#. Walk through the :doc:`tutorial </intro/tutorial01>`.\n#. Check out the rest of the :doc:`documentation </index>`, and `ask questions`_ if you\n   run into trouble.\n\n.. _`Download the code`: https://www.djangoproject.com/download/\n.. _ask questions: https://www.djangoproject.com/community/\n\nWhat are Django's prerequisites?\n================================\n\nDjango requires Python. See the table in the next question for the versions of\nPython that work with each version of Django. Other Python libraries may be\nrequired for some use cases, but you'll receive an error about them as they're\nneeded.\n\nFor a development environment -- if you just want to experiment with Django --\nyou don't need to have a separate Web server installed or database server.\n\nDjango comes with its own :djadmin:`lightweight development server<runserver>`.\nFor a production environment, Django follows the WSGI spec, :pep:`3333`, which\nmeans it can run on a variety of web servers. See :doc:`Deploying Django\n</howto/deployment/index>` for more information.\n\nDjango runs `SQLite`_ by default, which is included in Python installations.\nFor a production environment, we recommend PostgreSQL_; but we also officially\nsupport MariaDB_, MySQL_, `SQLite`_, and Oracle_. See :doc:`Supported Databases\n</ref/databases>` for more information.\n\n.. _Python: https://www.python.org/\n.. _PostgreSQL: https://www.postgresql.org/\n.. _MariaDB: https://mariadb.org/\n.. _MySQL: https://www.mysql.com/\n.. _`SQLite`: https://www.sqlite.org/\n.. _Oracle: https://www.oracle.com/\n\n.. _faq-python-version-support:\n\nWhat Python version can I use with Django?\n==========================================\n\n============== ===============\nDjango version Python versions\n============== ===============\n2.2            3.5, 3.6, 3.7, 3.8 (added in 2.2.8)\n3.0, 3.1, 3.2  3.6, 3.7, 3.8\n============== ===============\n\nFor each version of Python, only the latest micro release (A.B.C) is officially\nsupported. You can find the latest micro version for each series on the `Python\ndownload page <https://www.python.org/downloads/>`_.\n\nTypically, we will support a Python version up to and including the first\nDjango LTS release whose security support ends after security support for that\nversion of Python ends. For example, Python 3.3 security support ended\nSeptember 2017 and Django 1.8 LTS security support ended April 2018. Therefore\nDjango 1.8 is the last version to support Python 3.3.\n\nWhat Python version should I use with Django?\n=============================================\n\nPython 3 is recommended. Django 1.11 is the last version to support Python 2.7.\nSupport for Python 2.7 and Django 1.11 ends in 2020.\n\nSince newer versions of Python are often faster, have more features, and are\nbetter supported, the latest version of Python 3 is recommended.\n\nYou don't lose anything in Django by using an older release, but you don't take\nadvantage of the improvements and optimizations in newer Python releases.\nThird-party applications for use with Django are free to set their own version\nrequirements.\n\nShould I use the stable version or development version?\n=======================================================\n\nGenerally, if you're using code in production, you should be using a\nstable release. The Django project publishes a full stable release\nevery nine months or so, with bugfix updates in between. These stable\nreleases contain the API that is covered by our backwards\ncompatibility guarantees; if you write code against stable releases,\nyou shouldn't have any problems upgrading when the next official\nversion is released.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":25,"nodeType":"TextFile","repoName":null,"name":"migration-operations.txt","path":"docs/ref","text":"====================\nMigration Operations\n====================\n\n.. module:: django.db.migrations.operations\n\nMigration files are composed of one or more ``Operation``\\s, objects that\ndeclaratively record what the migration should do to your database.\n\nDjango also uses these ``Operation`` objects to work out what your models\nlooked like historically, and to calculate what changes you've made to\nyour models since the last migration so it can automatically write\nyour migrations; that's why they're declarative, as it means Django can\neasily load them all into memory and run through them without touching\nthe database to work out what your project should look like.\n\nThere are also more specialized ``Operation`` objects which are for things like\n:ref:`data migrations <data-migrations>` and for advanced manual database\nmanipulation. You can also write your own ``Operation`` classes if you want\nto encapsulate a custom change you commonly make.\n\nIf you need an empty migration file to write your own ``Operation`` objects\ninto, use ``python manage.py makemigrations --empty yourappname``, but be aware\nthat manually adding schema-altering operations can confuse the migration\nautodetector and make resulting runs of :djadmin:`makemigrations` output\nincorrect code.\n\nAll of the core Django operations are available from the\n``django.db.migrations.operations`` module.\n\nFor introductory material, see the :doc:`migrations topic guide\n</topics/migrations>`.\n\nSchema Operations\n=================\n\n``CreateModel``\n---------------\n\n.. class:: CreateModel(name, fields, options=None, bases=None, managers=None)\n\nCreates a new model in the project history and a corresponding table in the\ndatabase to match it.\n\n``name`` is the model name, as would be written in the ``models.py`` file.\n\n``fields`` is a list of 2-tuples of ``(field_name, field_instance)``.\nThe field instance should be an unbound field (so just\n``models.CharField(...)``, rather than a field taken from another model).\n\n``options`` is an optional dictionary of values from the model's ``Meta`` class.\n\n``bases`` is an optional list of other classes to have this model inherit from;\nit can contain both class objects as well as strings in the format\n``\"appname.ModelName\"`` if you want to depend on another model (so you inherit\nfrom the historical version). If it's not supplied, it defaults to inheriting\nfrom the standard ``models.Model``.\n\n``managers`` takes a list of 2-tuples of ``(manager_name, manager_instance)``.\nThe first manager in the list will be the default manager for this model during\nmigrations.\n\n``DeleteModel``\n---------------\n\n.. class:: DeleteModel(name)\n\nDeletes the model from the project history and its table from the database.\n\n``RenameModel``\n---------------\n\n.. class:: RenameModel(old_name, new_name)\n\nRenames the model from an old name to a new one.\n\nYou may have to manually add\nthis if you change the model's name and quite a few of its fields at once; to\nthe autodetector, this will look like you deleted a model with the old name\nand added a new one with a different name, and the migration it creates will\nlose any data in the old table.\n\n``AlterModelTable``\n-------------------\n\n.. class:: AlterModelTable(name, table)\n\nChanges the model's table name (the :attr:`~django.db.models.Options.db_table`\noption on the ``Meta`` subclass).\n\n``AlterUniqueTogether``\n-----------------------\n\n.. class:: AlterUniqueTogether(name, unique_together)\n\nChanges the model's set of unique constraints (the\n:attr:`~django.db.models.Options.unique_together` option on the ``Meta``\nsubclass).\n\n``AlterIndexTogether``\n----------------------\n\n.. class:: AlterIndexTogether(name, index_together)\n\nChanges the model's set of custom indexes (the\n:attr:`~django.db.models.Options.index_together` option on the ``Meta``\nsubclass).\n\n``AlterOrderWithRespectTo``\n---------------------------\n\n.. class:: AlterOrderWithRespectTo(name, order_with_respect_to)\n\nMakes or deletes the ``_order`` column needed for the\n:attr:`~django.db.models.Options.order_with_respect_to` option on the ``Meta``\nsubclass.\n\n``AlterModelOptions``\n---------------------\n\n.. class:: AlterModelOptions(name, options)\n\nStores changes to miscellaneous model options (settings on a model's ``Meta``)\nlike ``permissions`` and ``verbose_name``. Does not affect the database, but\npersists these changes for :class:`RunPython` instances to use. ``options``\nshould be a dictionary mapping option names to values.\n\n``AlterModelManagers``\n----------------------\n\n.. class:: AlterModelManagers(name, managers)\n\nAlters the managers that are available during migrations.\n\n``AddField``\n------------\n\n.. class:: AddField(model_name, name, field, preserve_default=True)\n\nAdds a field to a model. ``model_name`` is the model's name, ``name`` is\nthe field's name, and ``field`` is an unbound Field instance (the thing\nyou would put in the field declaration in ``models.py`` - for example,\n``models.IntegerField(null=True)``.\n\nThe ``preserve_default`` argument indicates whether the field's default\nvalue is permanent and should be baked into the project state (``True``),\nor if it is temporary and just for this migration (``False``) - usually\nbecause the migration is adding a non-nullable field to a table and needs\na default value to put into existing rows. It does not affect the behavior\nof setting defaults in the database directly - Django never sets database\ndefaults and always applies them in the Django ORM code.\n\n.. warning::\n\n    On older databases, adding a field with a default value may cause a full\n    rewrite of the table. This happens even for nullable fields and may have a\n    negative performance impact. To avoid that, the following steps should be\n    taken.\n\n    * Add the nullable field without the default value and run the\n      :djadmin:`makemigrations` command. This should generate a migration with\n      an ``AddField`` operation.\n\n    * Add the default value to your field and run the :djadmin:`makemigrations`\n      command. This should generate a migration with an ``AlterField``\n      operation.\n\n``RemoveField``\n---------------\n\n.. class:: RemoveField(model_name, name)\n\nRemoves a field from a model.\n\nBear in mind that when reversed, this is actually adding a field to a model.\nThe operation is reversible (apart from any data loss, which is irreversible)\nif the field is nullable or if it has a default value that can be used to\npopulate the recreated column. If the field is not nullable and does not have a\ndefault value, the operation is irreversible.\n\n``AlterField``\n--------------\n\n.. class:: AlterField(model_name, name, field, preserve_default=True)\n\nAlters a field's definition, including changes to its type,\n:attr:`~django.db.models.Field.null`, :attr:`~django.db.models.Field.unique`,\n:attr:`~django.db.models.Field.db_column` and other field attributes.\n\nThe ``preserve_default`` argument indicates whether the field's default\nvalue is permanent and should be baked into the project state (``True``),\nor if it is temporary and just for this migration (``False``) - usually\nbecause the migration is altering a nullable field to a non-nullable one and\nneeds a default value to put into existing rows. It does not affect the\nbehavior of setting defaults in the database directly - Django never sets\ndatabase defaults and always applies them in the Django ORM code.\n\nNote that not all changes are possible on all databases - for example, you\ncannot change a text-type field like ``models.TextField()`` into a number-type\nfield like ``models.IntegerField()`` on most databases.\n\n``RenameField``\n---------------\n\n.. class:: RenameField(model_name, old_name, new_name)\n\nChanges a field's name (and, unless :attr:`~django.db.models.Field.db_column`\nis set, its column name).\n\n``AddIndex``\n------------\n\n.. class:: AddIndex(model_name, index)\n\nCreates an index in the database table for the model with ``model_name``.\n``index`` is an instance of the :class:`~django.db.models.Index` class.\n\n``RemoveIndex``\n---------------\n\n.. class:: RemoveIndex(model_name, name)\n\nRemoves the index named ``name`` from the model with ``model_name``.\n\n``AddConstraint``\n-----------------\n\n.. class:: AddConstraint(model_name, constraint)\n\nCreates a :doc:`constraint </ref/models/constraints>` in the database table for\nthe model with ``model_name``.\n\n``RemoveConstraint``\n--------------------\n\n.. class:: RemoveConstraint(model_name, name)\n\nRemoves the constraint named ``name`` from the model with ``model_name``.\n\nSpecial Operations\n==================\n\n``RunSQL``\n----------\n\n.. class:: RunSQL(sql, reverse_sql=None, state_operations=None, hints=None, elidable=False)\n\nAllows running of arbitrary SQL on the database - useful for more advanced\nfeatures of database backends that Django doesn't support directly.\n\n``sql``, and ``reverse_sql`` if provided, should be strings of SQL to run on\nthe database. On most database backends (all but PostgreSQL), Django will\nsplit the SQL into individual statements prior to executing them.\n\n.. warning::\n\n    On PostgreSQL and SQLite, only use ``BEGIN`` or ``COMMIT`` in your SQL in\n    :ref:`non-atomic migrations <non-atomic-migrations>`, to avoid breaking\n    Django's transaction state.\n\nYou can also pass a list of strings or 2-tuples. The latter is used for passing\nqueries and parameters in the same way as :ref:`cursor.execute()\n<executing-custom-sql>`. These three operations are equivalent::\n\n    migrations.RunSQL(\"INSERT INTO musician (name) VALUES ('Reinhardt');\")\n    migrations.RunSQL([(\"INSERT INTO musician (name) VALUES ('Reinhardt');\", None)])\n    migrations.RunSQL([(\"INSERT INTO musician (name) VALUES (%s);\", ['Reinhardt'])])\n\nIf you want to include literal percent signs in the query, you have to double\nthem if you are passing parameters.\n\nThe ``reverse_sql`` queries are executed when the migration is unapplied. They\nshould undo what is done by the ``sql`` queries. For example, to undo the above\ninsertion with a deletion::\n\n    migrations.RunSQL(\n        sql=[(\"INSERT INTO musician (name) VALUES (%s);\", ['Reinhardt'])],\n        reverse_sql=[(\"DELETE FROM musician where name=%s;\", ['Reinhardt'])],\n    )\n\nIf ``reverse_sql`` is ``None`` (the default), the ``RunSQL`` operation is\nirreversible.\n\nThe ``state_operations`` argument allows you to supply operations that are\nequivalent to the SQL in terms of project state. For example, if you are\nmanually creating a column, you should pass in a list containing an ``AddField``\noperation here so that the autodetector still has an up-to-date state of the\nmodel. If you don't, when you next run ``makemigrations``, it won't see any\noperation that adds that field and so will try to run it again. For example::\n\n    migrations.RunSQL(\n        \"ALTER TABLE musician ADD COLUMN name varchar(255) NOT NULL;\",\n        state_operations=[\n            migrations.AddField(\n                'musician',\n                'name',\n                models.CharField(max_length=255),\n            ),\n        ],\n    )\n\nThe optional ``hints`` argument will be passed as ``**hints`` to the\n:meth:`allow_migrate` method of database routers to assist them in making\nrouting decisions. See :ref:`topics-db-multi-db-hints` for more details on\ndatabase hints.\n\nThe optional ``elidable`` argument determines whether or not the operation will\nbe removed (elided) when :ref:`squashing migrations <migration-squashing>`.\n\n.. attribute:: RunSQL.noop\n\n    Pass the ``RunSQL.noop`` attribute to ``sql`` or ``reverse_sql`` when you\n    want the operation not to do anything in the given direction. This is\n    especially useful in making the operation reversible.\n\n``RunPython``\n-------------\n\n.. class:: RunPython(code, reverse_code=None, atomic=None, hints=None, elidable=False)\n\nRuns custom Python code in a historical context. ``code`` (and ``reverse_code``\nif supplied) should be callable objects that accept two arguments; the first is\nan instance of ``django.apps.registry.Apps`` containing historical models that\nmatch the operation's place in the project history, and the second is an\ninstance of :class:`SchemaEditor\n<django.db.backends.base.schema.BaseDatabaseSchemaEditor>`.\n\nThe ``reverse_code`` argument is called when unapplying migrations. This\ncallable should undo what is done in the ``code`` callable so that the\nmigration is reversible. If ``reverse_code`` is ``None`` (the default), the\n``RunPython`` operation is irreversible.\n\nThe optional ``hints`` argument will be passed as ``**hints`` to the\n:meth:`allow_migrate` method of database routers to assist them in making a\nrouting decision. See :ref:`topics-db-multi-db-hints` for more details on\ndatabase hints.\n\nThe optional ``elidable`` argument determines whether or not the operation will\nbe removed (elided) when :ref:`squashing migrations <migration-squashing>`.\n\nYou are advised to write the code as a separate function above the ``Migration``\nclass in the migration file, and pass it to ``RunPython``. Here's an example of\nusing ``RunPython`` to create some initial objects on a ``Country`` model::\n\n    from django.db import migrations\n\n    def forwards_func(apps, schema_editor):\n        # We get the model from the versioned app registry;\n        # if we directly import it, it'll be the wrong version\n        Country = apps.get_model(\"myapp\", \"Country\")\n        db_alias = schema_editor.connection.alias\n        Country.objects.using(db_alias).bulk_create([\n            Country(name=\"USA\", code=\"us\"),\n            Country(name=\"France\", code=\"fr\"),\n        ])\n\n    def reverse_func(apps, schema_editor):\n        # forwards_func() creates two Country instances,\n        # so reverse_func() should delete them.\n        Country = apps.get_model(\"myapp\", \"Country\")\n        db_alias = schema_editor.connection.alias\n        Country.objects.using(db_alias).filter(name=\"USA\", code=\"us\").delete()\n        Country.objects.using(db_alias).filter(name=\"France\", code=\"fr\").delete()\n\n    class Migration(migrations.Migration):\n\n        dependencies = []\n\n        operations = [\n            migrations.RunPython(forwards_func, reverse_func),\n        ]\n\nThis is generally the operation you would use to create\n:ref:`data migrations <data-migrations>`, run\ncustom data updates and alterations, and anything else you need access to an\nORM and/or Python code for.\n\nMuch like :class:`RunSQL`, ensure that if you change schema inside here you're\neither doing it outside the scope of the Django model system (e.g. triggers)\nor that you use :class:`SeparateDatabaseAndState` to add in operations that will\nreflect your changes to the model state - otherwise, the versioned ORM and\nthe autodetector will stop working correctly.\n\nBy default, ``RunPython`` will run its contents inside a transaction on\ndatabases that do not support DDL transactions (for example, MySQL and\nOracle). This should be safe, but may cause a crash if you attempt to use\nthe ``schema_editor`` provided on these backends; in this case, pass\n``atomic=False`` to the ``RunPython`` operation.\n\nOn databases that do support DDL transactions (SQLite and PostgreSQL),\n``RunPython`` operations do not have any transactions automatically added\nbesides the transactions created for each migration. Thus, on PostgreSQL, for\nexample, you should avoid combining schema changes and ``RunPython`` operations\nin the same migration or you may hit errors like ``OperationalError: cannot\nALTER TABLE \"mytable\" because it has pending trigger events``.\n\nIf you have a different database and aren't sure if it supports DDL\ntransactions, check the ``django.db.connection.features.can_rollback_ddl``\nattribute.\n\nIf the ``RunPython`` operation is part of a :ref:`non-atomic migration\n<non-atomic-migrations>`, the operation will only be executed in a transaction\nif ``atomic=True`` is passed to the ``RunPython`` operation.\n\n.. warning::\n\n    ``RunPython`` does not magically alter the connection of the models for you;\n    any model methods you call will go to the default database unless you\n    give them the current database alias (available from\n    ``schema_editor.connection.alias``, where ``schema_editor`` is the second\n    argument to your function).\n\n.. staticmethod:: RunPython.noop\n\n    Pass the ``RunPython.noop`` method to ``code`` or ``reverse_code`` when\n    you want the operation not to do anything in the given direction. This is\n    especially useful in making the operation reversible.\n\n``SeparateDatabaseAndState``\n----------------------------\n\n.. class:: SeparateDatabaseAndState(database_operations=None, state_operations=None)\n\nA highly specialized operation that lets you mix and match the database\n(schema-changing) and state (autodetector-powering) aspects of operations.\n\nIt accepts two lists of operations. When asked to apply state, it will use the\n``state_operations`` list (this is a generalized version of :class:`RunSQL`'s\n``state_operations`` argument). When asked to apply changes to the database, it\nwill use the ``database_operations`` list.\n\nIf the actual state of the database and Django's view of the state get out of\nsync, this can break the migration framework, even leading to data loss. It's\nworth exercising caution and checking your database and state operations\ncarefully. You can use :djadmin:`sqlmigrate` and :djadmin:`dbshell` to check\nyour database operations. You can use :djadmin:`makemigrations`, especially\nwith :option:`--dry-run<makemigrations --dry-run>`, to check your state\noperations.\n\nFor an example using ``SeparateDatabaseAndState``, see\n:ref:`changing-a-manytomanyfield-to-use-a-through-model`.\n\n.. _writing-your-own-migration-operation:\n\nWriting your own\n================\n\nOperations have a relatively simple API, and they're designed so that you can\neasily write your own to supplement the built-in Django ones. The basic\nstructure of an ``Operation`` looks like this::\n\n    from django.db.migrations.operations.base import Operation\n\n    class MyCustomOperation(Operation):\n\n        # If this is False, it means that this operation will be ignored by\n        # sqlmigrate; if true, it will be run and the SQL collected for its output.\n        reduces_to_sql = False\n\n        # If this is False, Django will refuse to reverse past this operation.\n        reversible = False\n\n        def __init__(self, arg1, arg2):\n            # Operations are usually instantiated with arguments in migration\n            # files. Store the values of them on self for later use.\n            pass\n\n        def state_forwards(self, app_label, state):\n            # The Operation should take the 'state' parameter (an instance of\n            # django.db.migrations.state.ProjectState) and mutate it to match\n            # any schema changes that have occurred.\n            pass\n\n        def database_forwards(self, app_label, schema_editor, from_state, to_state):\n            # The Operation should use schema_editor to apply any changes it\n            # wants to make to the database.\n            pass\n\n        def database_backwards(self, app_label, schema_editor, from_state, to_state):\n            # If reversible is True, this is called when the operation is reversed.\n            pass\n\n        def describe(self):\n            # This is used to describe what the operation does in console output.\n            return \"Custom Operation\"\n\nYou can take this template and work from it, though we suggest looking at the\nbuilt-in Django operations in ``django.db.migrations.operations`` - they cover\na lot of the example usage of semi-internal aspects of the migration framework\nlike ``ProjectState`` and the patterns used to get historical models, as well\nas ``ModelState`` and the patterns used to mutate historical models in\n``state_forwards()``.\n\nSome things to note:\n\n* You don't need to learn too much about ``ProjectState`` to write migrations;\n  just know that it has an ``apps`` property that gives access to an app\n  registry (which you can then call ``get_model`` on).\n\n* ``database_forwards`` and ``database_backwards`` both get two states passed\n  to them; these represent the difference the ``state_forwards`` method would\n  have applied, but are given to you for convenience and speed reasons.\n\n* If you want to work with model classes or model instances from the\n  ``from_state`` argument in ``database_forwards()`` or\n  ``database_backwards()``, you must render model states using the\n  ``clear_delayed_apps_cache()`` method to make related models available::\n\n    def database_forwards(self, app_label, schema_editor, from_state, to_state):\n        # This operation should have access to all models. Ensure that all models are\n        # reloaded in case any are delayed.\n        from_state.clear_delayed_apps_cache()\n        ...\n\n* ``to_state`` in the database_backwards method is the *older* state; that is,\n  the one that will be the current state once the migration has finished reversing.\n\n* You might see implementations of ``references_model`` on the built-in\n  operations; this is part of the autodetection code and does not matter for\n  custom operations.\n\n.. warning::\n\n    For performance reasons, the :class:`~django.db.models.Field` instances in\n    ``ModelState.fields`` are reused across migrations. You must never change\n    the attributes on these instances. If you need to mutate a field in\n    ``state_forwards()``, you must remove the old instance from\n    ``ModelState.fields`` and add a new instance in its place. The same is true\n    for the :class:`~django.db.models.Manager` instances in\n    ``ModelState.managers``.\n\nAs an example, let's make an operation that loads PostgreSQL extensions (which\ncontain some of PostgreSQL's more exciting features). Since there's no model\nstate changes, all it does is run one command::\n\n    from django.db.migrations.operations.base import Operation\n\n    class LoadExtension(Operation):\n\n        reversible = True\n\n        def __init__(self, name):\n            self.name = name\n\n        def state_forwards(self, app_label, state):\n            pass\n\n        def database_forwards(self, app_label, schema_editor, from_state, to_state):\n            schema_editor.execute(\"CREATE EXTENSION IF NOT EXISTS %s\" % self.name)\n\n        def database_backwards(self, app_label, schema_editor, from_state, to_state):\n            schema_editor.execute(\"DROP EXTENSION %s\" % self.name)\n\n        def describe(self):\n            return \"Creates extension %s\" % self.name\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":26,"nodeType":"TextFile","repoName":null,"name":"admin.txt","path":"docs/faq","text":"==============\nFAQ: The admin\n==============\n\nI can't log in. When I enter a valid username and password, it just brings up the login page again, with no error messages.\n===========================================================================================================================\n\nThe login cookie isn't being set correctly, because the domain of the cookie\nsent out by Django doesn't match the domain in your browser. Try setting the\n:setting:`SESSION_COOKIE_DOMAIN` setting to match your domain. For example, if\nyou're going to \"https://www.example.com/admin/\" in your browser, set\n``SESSION_COOKIE_DOMAIN = 'www.example.com'``.\n\nI can't log in. When I enter a valid username and password, it brings up the login page again, with a \"Please enter a correct username and password\" error.\n===========================================================================================================================================================\n\nIf you're sure your username and password are correct, make sure your user\naccount has :attr:`~django.contrib.auth.models.User.is_active` and\n:attr:`~django.contrib.auth.models.User.is_staff` set to True. The admin site\nonly allows access to users with those two fields both set to True.\n\nHow do I automatically set a field's value to the user who last edited the object in the admin?\n===============================================================================================\n\nThe :class:`~django.contrib.admin.ModelAdmin` class provides customization hooks\nthat allow you to transform an object as it saved, using details from the\nrequest. By extracting the current user from the request, and customizing the\n:meth:`~django.contrib.admin.ModelAdmin.save_model` hook, you can update an\nobject to reflect the user that edited it. See :ref:`the documentation on\nModelAdmin methods <model-admin-methods>` for an example.\n\nHow do I limit admin access so that objects can only be edited by the users who created them?\n=============================================================================================\n\nThe :class:`~django.contrib.admin.ModelAdmin` class also provides customization\nhooks that allow you to control the visibility and editability of objects in the\nadmin. Using the same trick of extracting the user from the request, the\n:meth:`~django.contrib.admin.ModelAdmin.get_queryset` and\n:meth:`~django.contrib.admin.ModelAdmin.has_change_permission` can be used to\ncontrol the visibility and editability of objects in the admin.\n\nMy admin-site CSS and images showed up fine using the development server, but they're not displaying when using mod_wsgi.\n=========================================================================================================================\n\nSee :ref:`serving the admin files <serving-the-admin-files>`\nin the \"How to use Django with mod_wsgi\" documentation.\n\nMy \"list_filter\" contains a ManyToManyField, but the filter doesn't display.\n============================================================================\n\nDjango won't bother displaying the filter for a ``ManyToManyField`` if there\nare fewer than two related objects.\n\nFor example, if your :attr:`~django.contrib.admin.ModelAdmin.list_filter`\nincludes :doc:`sites </ref/contrib/sites>`, and there's only one site in your\ndatabase, it won't display a \"Site\" filter. In that case, filtering by site\nwould be meaningless.\n\nSome objects aren't appearing in the admin.\n===========================================\n\nInconsistent row counts may be caused by missing foreign key values or a\nforeign key field incorrectly set to :attr:`null=False\n<django.db.models.Field.null>`. If you have a record with a\n:class:`~django.db.models.ForeignKey` pointing to a nonexistent object and\nthat foreign key is included is\n:attr:`~django.contrib.admin.ModelAdmin.list_display`, the record will not be\nshown in the admin changelist because the Django model is declaring an\nintegrity constraint that is not implemented at the database level.\n\nHow can I customize the functionality of the admin interface?\n=============================================================\n\nYou've got several options. If you want to piggyback on top of an add/change\nform that Django automatically generates, you can attach arbitrary JavaScript\nmodules to the page via the model's class Admin :ref:`js parameter\n<modeladmin-asset-definitions>`. That parameter is a list of URLs, as strings,\npointing to JavaScript modules that will be included within the admin form via\na ``<script>`` tag.\n\nIf you want more flexibility than is feasible by tweaking the auto-generated\nforms, feel free to write custom views for the admin. The admin is powered by\nDjango itself, and you can write custom views that hook into the authentication\nsystem, check permissions and do whatever else they need to do.\n\nIf you want to customize the look-and-feel of the admin interface, read the\nnext question.\n\nThe dynamically-generated admin site is ugly! How can I change it?\n==================================================================\n\nWe like it, but if you don't agree, you can modify the admin site's\npresentation by editing the CSS stylesheet and/or associated image files. The\nsite is built using semantic HTML and plenty of CSS hooks, so any changes you'd\nlike to make should be possible by editing the stylesheet.\n\n.. _admin-browser-support:\n\nWhat browsers are supported for using the admin?\n================================================\n\nThe admin provides a fully-functional experience to the recent versions of\nmodern, web standards compliant browsers. On desktop this means Chrome, Edge,\nFirefox, Opera, Safari, and others.\n\nOn mobile and tablet devices, the admin provides a responsive experience for\nweb standards compliant browsers. This includes the major browsers on both\nAndroid and iOS.\n\nDepending on feature support, there *may* be minor stylistic differences\nbetween browsers. These are considered acceptable variations in rendering.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":27,"nodeType":"TextFile","repoName":null,"name":"csrf.txt","path":"docs/ref","text":"=====================================\nCross Site Request Forgery protection\n=====================================\n\n.. module:: django.middleware.csrf\n   :synopsis: Protects against Cross Site Request Forgeries\n\nThe CSRF middleware and template tag provides easy-to-use protection against\n`Cross Site Request Forgeries`_.  This type of attack occurs when a malicious\nwebsite contains a link, a form button or some JavaScript that is intended to\nperform some action on your website, using the credentials of a logged-in user\nwho visits the malicious site in their browser.  A related type of attack,\n'login CSRF', where an attacking site tricks a user's browser into logging into\na site with someone else's credentials, is also covered.\n\nThe first defense against CSRF attacks is to ensure that GET requests (and other\n'safe' methods, as defined by :rfc:`7231#section-4.2.1`) are side effect free.\nRequests via 'unsafe' methods, such as POST, PUT, and DELETE, can then be\nprotected by following the steps below.\n\n.. _Cross Site Request Forgeries: https://www.squarefree.com/securitytips/web-developers.html#CSRF\n\n.. _using-csrf:\n\nHow to use it\n=============\n\nTo take advantage of CSRF protection in your views, follow these steps:\n\n#. The CSRF middleware is activated by default in the :setting:`MIDDLEWARE`\n   setting. If you override that setting, remember that\n   ``'django.middleware.csrf.CsrfViewMiddleware'`` should come before any view\n   middleware that assume that CSRF attacks have been dealt with.\n\n   If you disabled it, which is not recommended, you can use\n   :func:`~django.views.decorators.csrf.csrf_protect` on particular views\n   you want to protect (see below).\n\n#. In any template that uses a POST form, use the :ttag:`csrf_token` tag inside\n   the ``<form>`` element if the form is for an internal URL, e.g.:\n\n   .. code-block:: html+django\n\n       <form method=\"post\">{% csrf_token %}\n\n   This should not be done for POST forms that target external URLs, since\n   that would cause the CSRF token to be leaked, leading to a vulnerability.\n\n#. In the corresponding view functions, ensure that\n   :class:`~django.template.RequestContext` is used to render the response so\n   that ``{% csrf_token %}`` will work properly. If you're using the\n   :func:`~django.shortcuts.render` function, generic views, or contrib apps,\n   you are covered already since these all use ``RequestContext``.\n\n.. _csrf-ajax:\n\nAJAX\n----\n\nWhile the above method can be used for AJAX POST requests, it has some\ninconveniences: you have to remember to pass the CSRF token in as POST data with\nevery POST request. For this reason, there is an alternative method: on each\nXMLHttpRequest, set a custom ``X-CSRFToken`` header (as specified by the\n:setting:`CSRF_HEADER_NAME` setting) to the value of the CSRF token. This is\noften easier because many JavaScript frameworks provide hooks that allow\nheaders to be set on every request.\n\nFirst, you must get the CSRF token. How to do that depends on whether or not\nthe :setting:`CSRF_USE_SESSIONS` and :setting:`CSRF_COOKIE_HTTPONLY` settings\nare enabled.\n\n.. _acquiring-csrf-token-from-cookie:\n\nAcquiring the token if :setting:`CSRF_USE_SESSIONS` and :setting:`CSRF_COOKIE_HTTPONLY` are ``False``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe recommended source for the token is the ``csrftoken`` cookie, which will be\nset if you've enabled CSRF protection for your views as outlined above.\n\nThe CSRF token cookie is named ``csrftoken`` by default, but you can control\nthe cookie name via the :setting:`CSRF_COOKIE_NAME` setting.\n\nYou can acquire the token like this:\n\n.. code-block:: javascript\n\n    function getCookie(name) {\n        var cookieValue = null;\n        if (document.cookie && document.cookie !== '') {\n            var cookies = document.cookie.split(';');\n            for (var i = 0; i < cookies.length; i++) {\n                var cookie = cookies[i].trim();\n                // Does this cookie string begin with the name we want?\n                if (cookie.substring(0, name.length + 1) === (name + '=')) {\n                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));\n                    break;\n                }\n            }\n        }\n        return cookieValue;\n    }\n    var csrftoken = getCookie('csrftoken');\n\nThe above code could be simplified by using the `JavaScript Cookie library\n<https://github.com/js-cookie/js-cookie/>`_ to replace ``getCookie``:\n\n.. code-block:: javascript\n\n    var csrftoken = Cookies.get('csrftoken');\n\n.. note::\n\n    The CSRF token is also present in the DOM, but only if explicitly included\n    using :ttag:`csrf_token` in a template. The cookie contains the canonical\n    token; the ``CsrfViewMiddleware`` will prefer the cookie to the token in\n    the DOM. Regardless, you're guaranteed to have the cookie if the token is\n    present in the DOM, so you should use the cookie!\n\n.. warning::\n\n    If your view is not rendering a template containing the :ttag:`csrf_token`\n    template tag, Django might not set the CSRF token cookie. This is common in\n    cases where forms are dynamically added to the page. To address this case,\n    Django provides a view decorator which forces setting of the cookie:\n    :func:`~django.views.decorators.csrf.ensure_csrf_cookie`.\n\n.. _acquiring-csrf-token-from-html:\n\nAcquiring the token if :setting:`CSRF_USE_SESSIONS` or :setting:`CSRF_COOKIE_HTTPONLY` is ``True``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf you activate :setting:`CSRF_USE_SESSIONS` or\n:setting:`CSRF_COOKIE_HTTPONLY`, you must include the CSRF token in your HTML\nand read the token from the DOM with JavaScript:\n\n.. code-block:: html+django\n\n    {% csrf_token %}\n    <script>\n    var csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;\n    </script>\n\nSetting the token on the AJAX request\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nFinally, you'll need to set the header on your AJAX request. Using the\n`fetch()`_ API:\n\n.. code-block:: javascript\n\n    var request = new Request(\n        /* URL */,\n        {headers: {'X-CSRFToken': csrftoken}}\n    );\n    fetch(request, {\n        method: 'POST',\n        mode: 'same-origin'  // Do not send CSRF token to another domain.\n    }).then(function(response) {\n        // ...\n    });\n\n.. _fetch(): https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch\n\nUsing CSRF in Jinja2 templates\n------------------------------\n\nDjango's :class:`~django.template.backends.jinja2.Jinja2` template backend\nadds ``{{ csrf_input }}`` to the context of all templates which is equivalent\nto ``{% csrf_token %}`` in the Django template language. For example:\n\n.. code-block:: html+jinja\n\n    <form method=\"post\">{{ csrf_input }}\n\nThe decorator method\n--------------------\n\n.. module:: django.views.decorators.csrf\n\nRather than adding ``CsrfViewMiddleware`` as a blanket protection, you can use\nthe ``csrf_protect`` decorator, which has exactly the same functionality, on\nparticular views that need the protection. It must be used **both** on views\nthat insert the CSRF token in the output, and on those that accept the POST form\ndata. (These are often the same view function, but not always).\n\nUse of the decorator by itself is **not recommended**, since if you forget to\nuse it, you will have a security hole. The 'belt and braces' strategy of using\nboth is fine, and will incur minimal overhead.\n\n.. function:: csrf_protect(view)\n\n    Decorator that provides the protection of ``CsrfViewMiddleware`` to a view.\n\n    Usage::\n\n        from django.shortcuts import render\n        from django.views.decorators.csrf import csrf_protect\n\n        @csrf_protect\n        def my_view(request):\n            c = {}\n            # ...\n            return render(request, \"a_template.html\", c)\n\n    If you are using class-based views, you can refer to\n    :ref:`Decorating class-based views<decorating-class-based-views>`.\n\n.. _csrf-rejected-requests:\n\nRejected requests\n=================\n\nBy default, a '403 Forbidden' response is sent to the user if an incoming\nrequest fails the checks performed by ``CsrfViewMiddleware``.  This should\nusually only be seen when there is a genuine Cross Site Request Forgery, or\nwhen, due to a programming error, the CSRF token has not been included with a\nPOST form.\n\nThe error page, however, is not very friendly, so you may want to provide your\nown view for handling this condition.  To do this, set the\n:setting:`CSRF_FAILURE_VIEW` setting.\n\nCSRF failures are logged as warnings to the :ref:`django.security.csrf\n<django-security-logger>` logger.\n\n.. _how-csrf-works:\n\nHow it works\n============\n\nThe CSRF protection is based on the following things:\n\n#. A CSRF cookie that is based on a random secret value, which other sites\n   will not have access to.\n\n   This cookie is set by ``CsrfViewMiddleware``. It is sent with every\n   response that has called ``django.middleware.csrf.get_token()`` (the\n   function used internally to retrieve the CSRF token), if it wasn't already\n   set on the request.\n\n   In order to protect against `BREACH`_ attacks, the token is not simply the\n   secret; a random mask is prepended to the secret and used to scramble it.\n\n   For security reasons, the value of the secret is changed each time a\n   user logs in.\n\n#. A hidden form field with the name 'csrfmiddlewaretoken' present in all\n   outgoing POST forms. The value of this field is, again, the value of the\n   secret, with a mask which is both added to it and used to scramble it. The\n   mask is regenerated on every call to ``get_token()`` so that the form field\n   value is changed in every such response.\n\n   This part is done by the template tag.\n\n#. For all incoming requests that are not using HTTP GET, HEAD, OPTIONS or\n   TRACE, a CSRF cookie must be present, and the 'csrfmiddlewaretoken' field\n   must be present and correct. If it isn't, the user will get a 403 error.\n\n   When validating the 'csrfmiddlewaretoken' field value, only the secret,\n   not the full token, is compared with the secret in the cookie value.\n   This allows the use of ever-changing tokens. While each request may use its\n   own token, the secret remains common to all.\n\n   This check is done by ``CsrfViewMiddleware``.\n\n#. In addition, for HTTPS requests, strict referer checking is done by\n   ``CsrfViewMiddleware``. This means that even if a subdomain can set or\n   modify cookies on your domain, it can't force a user to post to your\n   application since that request won't come from your own exact domain.\n\n   This also addresses a man-in-the-middle attack that's possible under HTTPS\n   when using a session independent secret, due to the fact that HTTP\n   ``Set-Cookie`` headers are (unfortunately) accepted by clients even when\n   they are talking to a site under HTTPS. (Referer checking is not done for\n   HTTP requests because the presence of the ``Referer`` header isn't reliable\n   enough under HTTP.)\n\n   If the :setting:`CSRF_COOKIE_DOMAIN` setting is set, the referer is compared\n   against it. This setting supports subdomains. For example,\n   ``CSRF_COOKIE_DOMAIN = '.example.com'`` will allow POST requests from\n   ``www.example.com`` and ``api.example.com``. If the setting is not set, then\n   the referer must match the HTTP ``Host`` header.\n\n   Expanding the accepted referers beyond the current host or cookie domain can\n   be done with the :setting:`CSRF_TRUSTED_ORIGINS` setting.\n\nThis ensures that only forms that have originated from trusted domains can be\nused to POST data back.\n\nIt deliberately ignores GET requests (and other requests that are defined as\n'safe' by :rfc:`7231#section-4.2.1`). These requests ought never to have any\npotentially dangerous side effects, and so a CSRF attack with a GET request\nought to be harmless. :rfc:`7231#section-4.2.1` defines POST, PUT, and DELETE\nas 'unsafe', and all other methods are also assumed to be unsafe, for maximum\nprotection.\n\nThe CSRF protection cannot protect against man-in-the-middle attacks, so use\n:ref:`HTTPS <security-recommendation-ssl>` with\n:ref:`http-strict-transport-security`. It also assumes :ref:`validation of\nthe HOST header <host-headers-virtual-hosting>` and that there aren't any\n:ref:`cross-site scripting vulnerabilities <cross-site-scripting>` on your site\n(because XSS vulnerabilities already let an attacker do anything a CSRF\nvulnerability allows and much worse).\n\n.. admonition:: Removing the ``Referer`` header\n\n    To avoid disclosing the referrer URL to third-party sites, you might want\n    to `disable the referer`_ on your site's ``<a>`` tags. For example, you\n    might use the ``<meta name=\"referrer\" content=\"no-referrer\">`` tag or\n    include the ``Referrer-Policy: no-referrer`` header. Due to the CSRF\n    protection's strict referer checking on HTTPS requests, those techniques\n    cause a CSRF failure on requests with 'unsafe' methods. Instead, use\n    alternatives like ``<a rel=\"noreferrer\" ...>\"`` for links to third-party\n    sites.\n\n.. _BREACH: http://breachattack.com/\n.. _disable the referer: https://www.w3.org/TR/referrer-policy/#referrer-policy-delivery\n\nCaching\n=======\n\nIf the :ttag:`csrf_token` template tag is used by a template (or the\n``get_token`` function is called some other way), ``CsrfViewMiddleware`` will\nadd a cookie and a ``Vary: Cookie`` header to the response. This means that the\nmiddleware will play well with the cache middleware if it is used as instructed\n(``UpdateCacheMiddleware`` goes before all other middleware).\n\nHowever, if you use cache decorators on individual views, the CSRF middleware\nwill not yet have been able to set the Vary header or the CSRF cookie, and the\nresponse will be cached without either one. In this case, on any views that\nwill require a CSRF token to be inserted you should use the\n:func:`django.views.decorators.csrf.csrf_protect` decorator first::\n\n  from django.views.decorators.cache import cache_page\n  from django.views.decorators.csrf import csrf_protect\n\n  @cache_page(60 * 15)\n  @csrf_protect\n  def my_view(request):\n      ...\n\nIf you are using class-based views, you can refer to :ref:`Decorating\nclass-based views<decorating-class-based-views>`.\n\nTesting\n=======\n\nThe ``CsrfViewMiddleware`` will usually be a big hindrance to testing view\nfunctions, due to the need for the CSRF token which must be sent with every POST\nrequest.  For this reason, Django's HTTP client for tests has been modified to\nset a flag on requests which relaxes the middleware and the ``csrf_protect``\ndecorator so that they no longer rejects requests.  In every other respect\n(e.g. sending cookies etc.), they behave the same.\n\nIf, for some reason, you *want* the test client to perform CSRF\nchecks, you can create an instance of the test client that enforces\nCSRF checks::\n\n    >>> from django.test import Client\n    >>> csrf_client = Client(enforce_csrf_checks=True)\n\n.. _csrf-limitations:\n\nLimitations\n===========\n\nSubdomains within a site will be able to set cookies on the client for the whole\ndomain.  By setting the cookie and using a corresponding token, subdomains will\nbe able to circumvent the CSRF protection.  The only way to avoid this is to\nensure that subdomains are controlled by trusted users (or, are at least unable\nto set cookies).  Note that even without CSRF, there are other vulnerabilities,\nsuch as session fixation, that make giving subdomains to untrusted parties a bad\nidea, and these vulnerabilities cannot easily be fixed with current browsers.\n\nEdge cases\n==========\n\nCertain views can have unusual requirements that mean they don't fit the normal\npattern envisaged here. A number of utilities can be useful in these\nsituations. The scenarios they might be needed in are described in the following\nsection.\n\nUtilities\n---------\n\nThe examples below assume you are using function-based views. If you\nare working with class-based views, you can refer to :ref:`Decorating\nclass-based views<decorating-class-based-views>`.\n\n.. function:: csrf_exempt(view)\n\n    This decorator marks a view as being exempt from the protection ensured by\n    the middleware. Example::\n\n        from django.http import HttpResponse\n        from django.views.decorators.csrf import csrf_exempt\n\n        @csrf_exempt\n        def my_view(request):\n            return HttpResponse('Hello world')\n\n.. function:: requires_csrf_token(view)\n\n    Normally the :ttag:`csrf_token` template tag will not work if\n    ``CsrfViewMiddleware.process_view`` or an equivalent like ``csrf_protect``\n    has not run. The view decorator ``requires_csrf_token`` can be used to\n    ensure the template tag does work. This decorator works similarly to\n    ``csrf_protect``, but never rejects an incoming request.\n\n    Example::\n\n        from django.shortcuts import render\n        from django.views.decorators.csrf import requires_csrf_token\n\n        @requires_csrf_token\n        def my_view(request):\n            c = {}\n            # ...\n            return render(request, \"a_template.html\", c)\n\n.. function:: ensure_csrf_cookie(view)\n\n    This decorator forces a view to send the CSRF cookie.\n\nScenarios\n---------\n\nCSRF protection should be disabled for just a few views\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nMost views requires CSRF protection, but a few do not.\n\nSolution: rather than disabling the middleware and applying ``csrf_protect`` to\nall the views that need it, enable the middleware and use\n:func:`~django.views.decorators.csrf.csrf_exempt`.\n\nCsrfViewMiddleware.process_view not used\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThere are cases when ``CsrfViewMiddleware.process_view`` may not have run\nbefore your view is run - 404 and 500 handlers, for example - but you still\nneed the CSRF token in a form.\n\nSolution: use :func:`~django.views.decorators.csrf.requires_csrf_token`\n\nUnprotected view needs the CSRF token\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThere may be some views that are unprotected and have been exempted by\n``csrf_exempt``, but still need to include the CSRF token.\n\nSolution: use :func:`~django.views.decorators.csrf.csrf_exempt` followed by\n:func:`~django.views.decorators.csrf.requires_csrf_token`. (i.e. ``requires_csrf_token``\nshould be the innermost decorator).\n\nView needs protection for one path\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nA view needs CSRF protection under one set of conditions only, and mustn't have\nit for the rest of the time.\n\nSolution: use :func:`~django.views.decorators.csrf.csrf_exempt` for the whole\nview function, and :func:`~django.views.decorators.csrf.csrf_protect` for the\npath within it that needs protection. Example::\n\n    from django.views.decorators.csrf import csrf_exempt, csrf_protect\n\n    @csrf_exempt\n    def my_view(request):\n\n        @csrf_protect\n        def protected_path(request):\n            do_something()\n\n        if some_condition():\n           return protected_path(request)\n        else:\n           do_something_else()\n\nPage uses AJAX without any HTML form\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nA page makes a POST request via AJAX, and the page does not have an HTML form\nwith a :ttag:`csrf_token` that would cause the required CSRF cookie to be sent.\n\nSolution: use :func:`~django.views.decorators.csrf.ensure_csrf_cookie` on the\nview that sends the page.\n\nContrib and reusable apps\n=========================\n\nBecause it is possible for the developer to turn off the ``CsrfViewMiddleware``,\nall relevant views in contrib apps use the ``csrf_protect`` decorator to ensure\nthe security of these applications against CSRF.  It is recommended that the\ndevelopers of other reusable apps that want the same guarantees also use the\n``csrf_protect`` decorator on their views.\n\nSettings\n========\n\nA number of settings can be used to control Django's CSRF behavior:\n\n* :setting:`CSRF_COOKIE_AGE`\n* :setting:`CSRF_COOKIE_DOMAIN`\n* :setting:`CSRF_COOKIE_HTTPONLY`\n* :setting:`CSRF_COOKIE_NAME`\n* :setting:`CSRF_COOKIE_PATH`\n* :setting:`CSRF_COOKIE_SAMESITE`\n* :setting:`CSRF_COOKIE_SECURE`\n* :setting:`CSRF_FAILURE_VIEW`\n* :setting:`CSRF_HEADER_NAME`\n* :setting:`CSRF_TRUSTED_ORIGINS`\n* :setting:`CSRF_USE_SESSIONS`\n\nFrequently Asked Questions\n==========================\n\nIs posting an arbitrary CSRF token pair (cookie and POST data) a vulnerability?\n-------------------------------------------------------------------------------\n\nNo, this is by design. Without a man-in-the-middle attack, there is no way for\nan attacker to send a CSRF token cookie to a victim's browser, so a successful\nattack would need to obtain the victim's browser's cookie via XSS or similar,\nin which case an attacker usually doesn't need CSRF attacks.\n\nSome security audit tools flag this as a problem but as mentioned before, an\nattacker cannot steal a user's browser's CSRF cookie. \"Stealing\" or modifying\n*your own* token using Firebug, Chrome dev tools, etc. isn't a vulnerability.\n\nIs it a problem that Django's CSRF protection isn't linked to a session by default?\n-----------------------------------------------------------------------------------\n\nNo, this is by design. Not linking CSRF protection to a session allows using\nthe protection on sites such as a *pastebin* that allow submissions from\nanonymous users which don't have a session.\n\nIf you wish to store the CSRF token in the user's session, use the\n:setting:`CSRF_USE_SESSIONS` setting.\n\nWhy might a user encounter a CSRF validation failure after logging in?\n----------------------------------------------------------------------\n\nFor security reasons, CSRF tokens are rotated each time a user logs in. Any\npage with a form generated before a login will have an old, invalid CSRF token\nand need to be reloaded. This might happen if a user uses the back button after\na login or if they log in a different browser tab.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":28,"nodeType":"TextFile","repoName":null,"name":"django-admin.txt","path":"docs/ref","text":"==================================\n``django-admin`` and ``manage.py``\n==================================\n\n``django-admin`` is Django's command-line utility for administrative tasks.\nThis document outlines all it can do.\n\nIn addition, ``manage.py`` is automatically created in each Django project. It\ndoes the same thing as ``django-admin`` but also sets the\n:envvar:`DJANGO_SETTINGS_MODULE` environment variable so that it points to your\nproject's ``settings.py`` file.\n\nThe ``django-admin`` script should be on your system path if you installed\nDjango via ``pip``. If it's not in your path, ensure you have your virtual\nenvironment activated.\n\nGenerally, when working on a single Django project, it's easier to use\n``manage.py`` than ``django-admin``. If you need to switch between multiple\nDjango settings files, use ``django-admin`` with\n:envvar:`DJANGO_SETTINGS_MODULE` or the :option:`--settings` command line\noption.\n\nThe command-line examples throughout this document use ``django-admin`` to\nbe consistent, but any example can use ``manage.py`` or ``python -m django``\njust as well.\n\nUsage\n=====\n\n.. console::\n\n    $ django-admin <command> [options]\n    $ manage.py <command> [options]\n    $ python -m django <command> [options]\n\n``command`` should be one of the commands listed in this document.\n``options``, which is optional, should be zero or more of the options available\nfor the given command.\n\nGetting runtime help\n--------------------\n\n.. django-admin:: help\n\nRun ``django-admin help`` to display usage information and a list of the\ncommands provided by each application.\n\nRun ``django-admin help --commands`` to display a list of all available\ncommands.\n\nRun ``django-admin help <command>`` to display a description of the given\ncommand and a list of its available options.\n\nApp names\n---------\n\nMany commands take a list of \"app names.\" An \"app name\" is the basename of\nthe package containing your models. For example, if your :setting:`INSTALLED_APPS`\ncontains the string ``'mysite.blog'``, the app name is ``blog``.\n\nDetermining the version\n-----------------------\n\n.. django-admin:: version\n\nRun ``django-admin version`` to display the current Django version.\n\nThe output follows the schema described in :pep:`440`::\n\n    1.4.dev17026\n    1.4a1\n    1.4\n\nDisplaying debug output\n-----------------------\n\n.. program:: None\n\nUse :option:`--verbosity` to specify the amount of notification and debug\ninformation that ``django-admin`` prints to the console.\n\nAvailable commands\n==================\n\n``check``\n---------\n\n.. django-admin:: check [app_label [app_label ...]]\n\nUses the :doc:`system check framework </ref/checks>` to inspect the entire\nDjango project for common problems.\n\nBy default, all apps will be checked. You can check a subset of apps by\nproviding a list of app labels as arguments::\n\n    django-admin check auth admin myapp\n\nIf you do not specify any app, all apps will be checked.\n\n.. django-admin-option:: --tag TAGS, -t TAGS\n\nThe system check framework performs many different types of checks that are\n:ref:`categorized with tags <system-check-builtin-tags>`. You can use these\ntags to restrict the checks performed to just those in a particular category.\nFor example, to perform only models and compatibility checks, run::\n\n    django-admin check --tag models --tag compatibility\n\n.. django-admin-option:: --database DATABASE\n\n.. versionadded:: 3.1\n\nSpecifies the database to run checks requiring database access::\n\n    django-admin check --database default --database other\n\nBy default, these checks will not be run.\n\n.. django-admin-option:: --list-tags\n\nLists all available tags.\n\n.. django-admin-option:: --deploy\n\nActivates some additional checks that are only relevant in a deployment setting.\n\nYou can use this option in your local development environment, but since your\nlocal development settings module may not have many of your production settings,\nyou will probably want to point the ``check`` command at a different settings\nmodule, either by setting the :envvar:`DJANGO_SETTINGS_MODULE` environment\nvariable, or by passing the ``--settings`` option::\n\n    django-admin check --deploy --settings=production_settings\n\nOr you could run it directly on a production or staging deployment to verify\nthat the correct settings are in use (omitting ``--settings``). You could even\nmake it part of your integration test suite.\n\n.. django-admin-option:: --fail-level {CRITICAL,ERROR,WARNING,INFO,DEBUG}\n\nSpecifies the message level that will cause the command to exit with a non-zero\nstatus. Default is ``ERROR``.\n\n``compilemessages``\n-------------------\n\n.. django-admin:: compilemessages\n\nCompiles ``.po`` files created by :djadmin:`makemessages` to ``.mo`` files for\nuse with the built-in gettext support. See :doc:`/topics/i18n/index`.\n\n.. django-admin-option:: --locale LOCALE, -l LOCALE\n\nSpecifies the locale(s) to process. If not provided, all locales are processed.\n\n.. django-admin-option:: --exclude EXCLUDE, -x EXCLUDE\n\nSpecifies the locale(s) to exclude from processing. If not provided, no locales\nare excluded.\n\n.. django-admin-option:: --use-fuzzy, -f\n\nIncludes fuzzy translations into compiled files.\n\nExample usage::\n\n    django-admin compilemessages --locale=pt_BR\n    django-admin compilemessages --locale=pt_BR --locale=fr -f\n    django-admin compilemessages -l pt_BR\n    django-admin compilemessages -l pt_BR -l fr --use-fuzzy\n    django-admin compilemessages --exclude=pt_BR\n    django-admin compilemessages --exclude=pt_BR --exclude=fr\n    django-admin compilemessages -x pt_BR\n    django-admin compilemessages -x pt_BR -x fr\n\n.. django-admin-option:: --ignore PATTERN, -i PATTERN\n\nIgnores directories matching the given :mod:`glob`-style pattern. Use\nmultiple times to ignore more.\n\nExample usage::\n\n    django-admin compilemessages --ignore=cache --ignore=outdated/*/locale\n\n``createcachetable``\n--------------------\n\n.. django-admin:: createcachetable\n\nCreates the cache tables for use with the database cache backend using the\ninformation from your settings file. See :doc:`/topics/cache` for more\ninformation.\n\n.. django-admin-option:: --database DATABASE\n\nSpecifies the database in which the cache table(s) will be created. Defaults to\n``default``.\n\n.. django-admin-option:: --dry-run\n\nPrints the SQL that would be run without actually running it, so you can\ncustomize it or use the migrations framework.\n\n``dbshell``\n-----------\n\n.. django-admin:: dbshell\n\nRuns the command-line client for the database engine specified in your\n:setting:`ENGINE <DATABASE-ENGINE>` setting, with the connection parameters\nspecified in your :setting:`USER`, :setting:`PASSWORD`, etc., settings.\n\n* For PostgreSQL, this runs the ``psql`` command-line client.\n* For MySQL, this runs the ``mysql`` command-line client.\n* For SQLite, this runs the ``sqlite3`` command-line client.\n* For Oracle, this runs the ``sqlplus`` command-line client.\n\nThis command assumes the programs are on your ``PATH`` so that a call to\nthe program name (``psql``, ``mysql``, ``sqlite3``, ``sqlplus``) will find the\nprogram in the right place. There's no way to specify the location of the\nprogram manually.\n\n.. django-admin-option:: --database DATABASE\n\nSpecifies the database onto which to open a shell. Defaults to ``default``.\n\n.. django-admin-option:: -- ARGUMENTS\n\n.. versionadded:: 3.1\n\nAny arguments following a ``--`` divider will be passed on to the underlying\ncommand-line client. For example, with PostgreSQL you can use the ``psql``\ncommand's ``-c`` flag to execute a raw SQL query directly:\n\n.. console::\n\n    $ django-admin dbshell -- -c 'select current_user'\n     current_user\n    --------------\n     postgres\n    (1 row)\n\nOn MySQL/MariaDB, you can do this with the ``mysql`` command's ``-e`` flag:\n\n.. console::\n\n    $ django-admin dbshell -- -e \"select user()\"\n    +----------------------+\n    | user()               |\n    +----------------------+\n    | djangonaut@localhost |\n    +----------------------+\n\n.. note::\n\n    Be aware that not all options set in the :setting:`OPTIONS` part of your\n    database configuration in :setting:`DATABASES` are passed to the\n    command-line client, e.g. ``'isolation_level'``.\n\n``diffsettings``\n----------------\n\n.. django-admin:: diffsettings\n\nDisplays differences between the current settings file and Django's default\nsettings (or another settings file specified by :option:`--default`).\n\nSettings that don't appear in the defaults are followed by ``\"###\"``. For\nexample, the default settings don't define :setting:`ROOT_URLCONF`, so\n:setting:`ROOT_URLCONF` is followed by ``\"###\"`` in the output of\n``diffsettings``.\n\n.. django-admin-option:: --all\n\nDisplays all settings, even if they have Django's default value. Such settings\nare prefixed by ``\"###\"``.\n\n.. django-admin-option:: --default MODULE\n\nThe settings module to compare the current settings against. Leave empty to\ncompare against Django's default settings.\n\n.. django-admin-option:: --output {hash,unified}\n\nSpecifies the output format. Available values are ``hash`` and ``unified``.\n``hash`` is the default mode that displays the output that's described above.\n``unified`` displays the output similar to ``diff -u``. Default settings are\nprefixed with a minus sign, followed by the changed setting prefixed with a\nplus sign.\n\n``dumpdata``\n------------\n\n.. django-admin:: dumpdata [app_label[.ModelName] [app_label[.ModelName] ...]]\n\nOutputs to standard output all data in the database associated with the named\napplication(s).\n\nIf no application name is provided, all installed applications will be dumped.\n\nThe output of ``dumpdata`` can be used as input for :djadmin:`loaddata`.\n\nNote that ``dumpdata`` uses the default manager on the model for selecting the\nrecords to dump. If you're using a :ref:`custom manager <custom-managers>` as\nthe default manager and it filters some of the available records, not all of the\nobjects will be dumped.\n\n.. django-admin-option:: --all, -a\n\nUses Django's base manager, dumping records which might otherwise be filtered\nor modified by a custom manager.\n\n.. django-admin-option:: --format FORMAT\n\nSpecifies the serialization format of the output. Defaults to JSON. Supported\nformats are listed in :ref:`serialization-formats`.\n\n.. django-admin-option:: --indent INDENT\n\nSpecifies the number of indentation spaces to use in the output. Defaults to\n``None`` which displays all data on single line.\n\n.. django-admin-option:: --exclude EXCLUDE, -e EXCLUDE\n\nPrevents specific applications or models (specified in the form of\n``app_label.ModelName``) from being dumped. If you specify a model name, the\noutput will be restricted to that model, rather than the entire application.\nYou can also mix application names and model names.\n\nIf you want to exclude multiple applications, pass ``--exclude`` more than\nonce::\n\n    django-admin dumpdata --exclude=auth --exclude=contenttypes\n\n.. django-admin-option:: --database DATABASE\n\nSpecifies the database from which data will be dumped. Defaults to ``default``.\n\n.. django-admin-option:: --natural-foreign\n\nUses the ``natural_key()`` model method to serialize any foreign key and\nmany-to-many relationship to objects of the type that defines the method. If\nyou're dumping ``contrib.auth`` ``Permission`` objects or\n``contrib.contenttypes`` ``ContentType`` objects, you should probably use this\nflag. See the :ref:`natural keys <topics-serialization-natural-keys>`\ndocumentation for more details on this and the next option.\n\n.. django-admin-option:: --natural-primary\n\nOmits the primary key in the serialized data of this object since it can be\ncalculated during deserialization.\n\n.. django-admin-option:: --pks PRIMARY_KEYS\n\nOutputs only the objects specified by a comma separated list of primary keys.\nThis is only available when dumping one model. By default, all the records of\nthe model are output.\n\n.. django-admin-option:: --output OUTPUT, -o OUTPUT\n\nSpecifies a file to write the serialized data to. By default, the data goes to\nstandard output.\n\nWhen this option is set and ``--verbosity`` is greater than 0 (the default), a\nprogress bar is shown in the terminal.\n\n``flush``\n---------\n\n.. django-admin:: flush\n\nRemoves all data from the database and re-executes any post-synchronization\nhandlers. The table of which migrations have been applied is not cleared.\n\nIf you would rather start from an empty database and re-run all migrations, you\nshould drop and recreate the database and then run :djadmin:`migrate` instead.\n\n.. django-admin-option:: --noinput, --no-input\n\nSuppresses all user prompts.\n\n.. django-admin-option:: --database DATABASE\n\nSpecifies the database to flush. Defaults to ``default``.\n\n``inspectdb``\n-------------\n\n.. django-admin:: inspectdb [table [table ...]]\n\nIntrospects the database tables in the database pointed-to by the\n:setting:`NAME` setting and outputs a Django model module (a ``models.py``\nfile) to standard output.\n\nYou may choose what tables or views to inspect by passing their names as\narguments. If no arguments are provided, models are created for views only if\nthe :option:`--include-views` option is used. Models for partition tables are\ncreated on PostgreSQL if the :option:`--include-partitions` option is used.\n\nUse this if you have a legacy database with which you'd like to use Django.\nThe script will inspect the database and create a model for each table within\nit.\n\nAs you might expect, the created models will have an attribute for every field\nin the table. Note that ``inspectdb`` has a few special cases in its field-name\noutput:\n\n* If ``inspectdb`` cannot map a column's type to a model field type, it'll\n  use ``TextField`` and will insert the Python comment\n  ``'This field type is a guess.'`` next to the field in the generated\n  model. The recognized fields may depend on apps listed in\n  :setting:`INSTALLED_APPS`. For example, :mod:`django.contrib.postgres` adds\n  recognition for several PostgreSQL-specific field types.\n\n* If the database column name is a Python reserved word (such as\n  ``'pass'``, ``'class'`` or ``'for'``), ``inspectdb`` will append\n  ``'_field'`` to the attribute name. For example, if a table has a column\n  ``'for'``, the generated model will have a field ``'for_field'``, with\n  the ``db_column`` attribute set to ``'for'``. ``inspectdb`` will insert\n  the Python comment\n  ``'Field renamed because it was a Python reserved word.'`` next to the\n  field.\n\nThis feature is meant as a shortcut, not as definitive model generation. After\nyou run it, you'll want to look over the generated models yourself to make\ncustomizations. In particular, you'll need to rearrange models' order, so that\nmodels that refer to other models are ordered properly.\n\nDjango doesn't create database defaults when a\n:attr:`~django.db.models.Field.default` is specified on a model field.\nSimilarly, database defaults aren't translated to model field defaults or\ndetected in any fashion by ``inspectdb``.\n\nBy default, ``inspectdb`` creates unmanaged models. That is, ``managed = False``\nin the model's ``Meta`` class tells Django not to manage each table's creation,\nmodification, and deletion. If you do want to allow Django to manage the\ntable's lifecycle, you'll need to change the\n:attr:`~django.db.models.Options.managed` option to ``True`` (or remove\nit because ``True`` is its default value).\n\nDatabase-specific notes\n~~~~~~~~~~~~~~~~~~~~~~~\n\nOracle\n^^^^^^\n\n* Models are created for materialized views if :option:`--include-views` is\n  used.\n\nPostgreSQL\n^^^^^^^^^^\n\n* Models are created for foreign tables.\n* Models are created for materialized views if\n  :option:`--include-views` is used.\n* Models are created for partition tables if\n  :option:`--include-partitions` is used.\n\n.. django-admin-option:: --database DATABASE\n\nSpecifies the database to introspect. Defaults to ``default``.\n\n.. django-admin-option:: --include-partitions\n\nIf this option is provided, models are also created for partitions.\n\nOnly support for PostgreSQL is implemented.\n\n.. django-admin-option:: --include-views\n\nIf this option is provided, models are also created for database views.\n\n``loaddata``\n------------\n\n.. django-admin:: loaddata fixture [fixture ...]\n\nSearches for and loads the contents of the named fixture into the database.\n\n.. django-admin-option:: --database DATABASE\n\nSpecifies the database into which the data will be loaded. Defaults to\n``default``.\n\n.. django-admin-option:: --ignorenonexistent, -i\n\nIgnores fields and models that may have been removed since the fixture was\noriginally generated.\n\n.. django-admin-option:: --app APP_LABEL\n\nSpecifies a single app to look for fixtures in rather than looking in all apps.\n\n.. django-admin-option:: --format FORMAT\n\nSpecifies the :ref:`serialization format <serialization-formats>` (e.g.,\n``json`` or ``xml``) for fixtures :ref:`read from stdin\n<loading-fixtures-stdin>`.\n\n.. django-admin-option:: --exclude EXCLUDE, -e EXCLUDE\n\nExcludes loading the fixtures from the given applications and/or models (in the\nform of ``app_label`` or ``app_label.ModelName``). Use the option multiple\ntimes to exclude more than one app or model.\n\nWhat's a \"fixture\"?\n~~~~~~~~~~~~~~~~~~~\n\nA *fixture* is a collection of files that contain the serialized contents of\nthe database. Each fixture has a unique name, and the files that comprise the\nfixture can be distributed over multiple directories, in multiple applications.\n\nDjango will search in three locations for fixtures:\n\n1. In the ``fixtures`` directory of every installed application\n2. In any directory named in the :setting:`FIXTURE_DIRS` setting\n3. In the literal path named by the fixture\n\nDjango will load any and all fixtures it finds in these locations that match\nthe provided fixture names.\n\nIf the named fixture has a file extension, only fixtures of that type\nwill be loaded. For example::\n\n    django-admin loaddata mydata.json\n\nwould only load JSON fixtures called ``mydata``. The fixture extension\nmust correspond to the registered name of a\n:ref:`serializer <serialization-formats>` (e.g., ``json`` or ``xml``).\n\nIf you omit the extensions, Django will search all available fixture types\nfor a matching fixture. For example::\n\n    django-admin loaddata mydata\n\nwould look for any fixture of any fixture type called ``mydata``. If a fixture\ndirectory contained ``mydata.json``, that fixture would be loaded\nas a JSON fixture.\n\nThe fixtures that are named can include directory components. These\ndirectories will be included in the search path. For example::\n\n    django-admin loaddata foo/bar/mydata.json\n\nwould search ``<app_label>/fixtures/foo/bar/mydata.json`` for each installed\napplication,  ``<dirname>/foo/bar/mydata.json`` for each directory in\n:setting:`FIXTURE_DIRS`, and the literal path ``foo/bar/mydata.json``.\n\nWhen fixture files are processed, the data is saved to the database as is.\nModel defined :meth:`~django.db.models.Model.save` methods are not called, and\nany :data:`~django.db.models.signals.pre_save` or\n:data:`~django.db.models.signals.post_save` signals will be called with\n``raw=True`` since the instance only contains attributes that are local to the\nmodel. You may, for example, want to disable handlers that access\nrelated fields that aren't present during fixture loading and would otherwise\nraise an exception::\n\n    from django.db.models.signals import post_save\n    from .models import MyModel\n\n    def my_handler(**kwargs):\n        # disable the handler during fixture loading\n        if kwargs['raw']:\n            return\n        ...\n\n    post_save.connect(my_handler, sender=MyModel)\n\nYou could also write a decorator to encapsulate this logic::\n\n    from functools import wraps\n\n    def disable_for_loaddata(signal_handler):\n        \"\"\"\n        Decorator that turns off signal handlers when loading fixture data.\n        \"\"\"\n        @wraps(signal_handler)\n        def wrapper(*args, **kwargs):\n            if kwargs['raw']:\n                return\n            signal_handler(*args, **kwargs)\n        return wrapper\n\n    @disable_for_loaddata\n    def my_handler(**kwargs):\n        ...\n\nJust be aware that this logic will disable the signals whenever fixtures are\ndeserialized, not just during ``loaddata``.\n\nNote that the order in which fixture files are processed is undefined. However,\nall fixture data is installed as a single transaction, so data in\none fixture can reference data in another fixture. If the database backend\nsupports row-level constraints, these constraints will be checked at the\nend of the transaction.\n\nThe :djadmin:`dumpdata` command can be used to generate input for ``loaddata``.\n\nCompressed fixtures\n~~~~~~~~~~~~~~~~~~~\n\nFixtures may be compressed in ``zip``, ``gz``, ``bz2``, ``lzma``, or ``xz``\nformat. For example::\n\n    django-admin loaddata mydata.json\n\nwould look for any of ``mydata.json``, ``mydata.json.zip``, ``mydata.json.gz``,\n``mydata.json.bz2``, ``mydata.json.lzma``, or ``mydata.json.xz``. The first\nfile contained within a compressed archive is used.\n\nNote that if two fixtures with the same name but different\nfixture type are discovered (for example, if ``mydata.json`` and\n``mydata.xml.gz`` were found in the same fixture directory), fixture\ninstallation will be aborted, and any data installed in the call to\n``loaddata`` will be removed from the database.\n\n.. admonition:: MySQL with MyISAM and fixtures\n\n    The MyISAM storage engine of MySQL doesn't support transactions or\n    constraints, so if you use MyISAM, you won't get validation of fixture\n    data, or a rollback if multiple transaction files are found.\n\n.. versionchanged:: 3.2\n\n    Support for XZ archives (``.xz``) and LZMA archives (``.lzma``) was added.\n\nDatabase-specific fixtures\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf you're in a multi-database setup, you might have fixture data that\nyou want to load onto one database, but not onto another. In this\nsituation, you can add a database identifier into the names of your fixtures.\n\nFor example, if your :setting:`DATABASES` setting has a 'master' database\ndefined, name the fixture ``mydata.master.json`` or\n``mydata.master.json.gz`` and the fixture will only be loaded when you\nspecify you want to load data into the ``master`` database.\n\n.. _loading-fixtures-stdin:\n\nLoading fixtures from ``stdin``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nYou can use a dash as the fixture name to load input from ``sys.stdin``. For\nexample::\n\n    django-admin loaddata --format=json -\n\nWhen reading from ``stdin``, the :option:`--format <loaddata --format>` option\nis required to specify the :ref:`serialization format <serialization-formats>`\nof the input (e.g., ``json`` or ``xml``).\n\nLoading from ``stdin`` is useful with standard input and output redirections.\nFor example::\n\n    django-admin dumpdata --format=json --database=test app_label.ModelName | django-admin loaddata --format=json --database=prod -\n\n``makemessages``\n----------------\n\n.. django-admin:: makemessages\n\nRuns over the entire source tree of the current directory and pulls out all\nstrings marked for translation. It creates (or updates) a message file in the\nconf/locale (in the Django tree) or locale (for project and application)\ndirectory. After making changes to the messages files you need to compile them\nwith :djadmin:`compilemessages` for use with the builtin gettext support. See\nthe :ref:`i18n documentation <how-to-create-language-files>` for details.\n\nThis command doesn't require configured settings. However, when settings aren't\nconfigured, the command can't ignore the :setting:`MEDIA_ROOT` and\n:setting:`STATIC_ROOT` directories or include :setting:`LOCALE_PATHS`.\n\n.. django-admin-option:: --all, -a\n\nUpdates the message files for all available languages.\n\n.. django-admin-option:: --extension EXTENSIONS, -e EXTENSIONS\n\nSpecifies a list of file extensions to examine (default: ``html``, ``txt``,\n``py`` or ``js`` if :option:`--domain` is ``js``).\n\nExample usage::\n\n    django-admin makemessages --locale=de --extension xhtml\n\nSeparate multiple extensions with commas or use ``-e`` or ``--extension``\nmultiple times::\n\n    django-admin makemessages --locale=de --extension=html,txt --extension xml\n\n.. django-admin-option:: --locale LOCALE, -l LOCALE\n\nSpecifies the locale(s) to process.\n\n.. django-admin-option:: --exclude EXCLUDE, -x EXCLUDE\n\nSpecifies the locale(s) to exclude from processing. If not provided, no locales\nare excluded.\n\nExample usage::\n\n    django-admin makemessages --locale=pt_BR\n    django-admin makemessages --locale=pt_BR --locale=fr\n    django-admin makemessages -l pt_BR\n    django-admin makemessages -l pt_BR -l fr\n    django-admin makemessages --exclude=pt_BR\n    django-admin makemessages --exclude=pt_BR --exclude=fr\n    django-admin makemessages -x pt_BR\n    django-admin makemessages -x pt_BR -x fr\n\n.. django-admin-option:: --domain DOMAIN, -d DOMAIN\n\nSpecifies the domain of the messages files. Supported options are:\n\n* ``django`` for all ``*.py``, ``*.html`` and ``*.txt`` files (default)\n* ``djangojs`` for ``*.js`` files\n\n.. django-admin-option:: --symlinks, -s\n\nFollows symlinks to directories when looking for new translation strings.\n\nExample usage::\n\n    django-admin makemessages --locale=de --symlinks\n\n.. django-admin-option:: --ignore PATTERN, -i PATTERN\n\nIgnores files or directories matching the given :mod:`glob`-style pattern. Use\nmultiple times to ignore more.\n\nThese patterns are used by default: ``'CVS'``, ``'.*'``, ``'*~'``, ``'*.pyc'``.\n\nExample usage::\n\n    django-admin makemessages --locale=en_US --ignore=apps/* --ignore=secret/*.html\n\n.. django-admin-option:: --no-default-ignore\n\nDisables the default values of ``--ignore``.\n\n.. django-admin-option:: --no-wrap\n\nDisables breaking long message lines into several lines in language files.\n\n.. django-admin-option:: --no-location\n\nSuppresses writing '``#: filename:line``’ comment lines in language files.\nUsing this option makes it harder for technically skilled translators to\nunderstand each message's context.\n\n.. django-admin-option:: --add-location [{full,file,never}]\n\nControls ``#: filename:line`` comment lines in language files. If the option\nis:\n\n* ``full`` (the default if not given): the lines include both file name and\n  line number.\n* ``file``: the line number is omitted.\n* ``never``: the lines are suppressed (same as :option:`--no-location`).\n\nRequires ``gettext`` 0.19 or newer.\n\n.. django-admin-option:: --keep-pot\n\nPrevents deleting the temporary ``.pot`` files generated before creating the\n``.po`` file. This is useful for debugging errors which may prevent the final\nlanguage files from being created.\n\n.. seealso::\n\n    See :ref:`customizing-makemessages` for instructions on how to customize\n    the keywords that :djadmin:`makemessages` passes to ``xgettext``.\n\n``makemigrations``\n------------------\n\n.. django-admin:: makemigrations [app_label [app_label ...]]\n\nCreates new migrations based on the changes detected to your models.\nMigrations, their relationship with apps and more are covered in depth in\n:doc:`the migrations documentation</topics/migrations>`.\n\nProviding one or more app names as arguments will limit the migrations created\nto the app(s) specified and any dependencies needed (the table at the other end\nof a ``ForeignKey``, for example).\n\nTo add migrations to an app that doesn't have a ``migrations`` directory, run\n``makemigrations`` with the app's ``app_label``.\n\n.. django-admin-option:: --noinput, --no-input\n\nSuppresses all user prompts. If a suppressed prompt cannot be resolved\nautomatically, the command will exit with error code 3.\n\n.. django-admin-option:: --empty\n\nOutputs an empty migration for the specified apps, for manual editing. This is\nfor advanced users and should not be used unless you are familiar with the\nmigration format, migration operations, and the dependencies between your\nmigrations.\n\n.. django-admin-option:: --dry-run\n\nShows what migrations would be made without actually writing any migrations\nfiles to disk. Using this option along with ``--verbosity 3`` will also show\nthe complete migrations files that would be written.\n\n.. django-admin-option:: --merge\n\nEnables fixing of migration conflicts.\n\n.. django-admin-option:: --name NAME, -n NAME\n\nAllows naming the generated migration(s) instead of using a generated name. The\nname must be a valid Python :ref:`identifier <python:identifiers>`.\n\n.. django-admin-option:: --no-header\n\nGenerate migration files without Django version and timestamp header.\n\n.. django-admin-option:: --check\n\nMakes ``makemigrations`` exit with a non-zero status when model changes without\nmigrations are detected.\n\n.. versionchanged:: 3.2\n\n    Support for calling ``makemigrations`` without an active database\n    connection was added. In that case, check for a consistent migration\n    history is skipped.\n\n``migrate``\n-----------\n\n.. django-admin:: migrate [app_label] [migration_name]\n\nSynchronizes the database state with the current set of models and migrations.\nMigrations, their relationship with apps and more are covered in depth in\n:doc:`the migrations documentation</topics/migrations>`.\n\nThe behavior of this command changes depending on the arguments provided:\n\n* No arguments: All apps have all of their migrations run.\n* ``<app_label>``: The specified app has its migrations run, up to the most\n  recent migration. This may involve running other apps' migrations too, due\n  to dependencies.\n* ``<app_label> <migrationname>``: Brings the database schema to a state where\n  the named migration is applied, but no later migrations in the same app are\n  applied. This may involve unapplying migrations if you have previously\n  migrated past the named migration. You can use a prefix of the migration\n  name, e.g. ``0001``, as long as it's unique for the given app name. Use the\n  name ``zero`` to migrate all the way back i.e. to revert all applied\n  migrations for an app.\n\n.. warning::\n\n    When unapplying migrations, all dependent migrations will also be\n    unapplied, regardless of ``<app_label>``. You can use ``--plan`` to check\n    which migrations will be unapplied.\n\n.. django-admin-option:: --database DATABASE\n\nSpecifies the database to migrate. Defaults to ``default``.\n\n.. django-admin-option:: --fake\n\nMarks the migrations up to the target one (following the rules above) as\napplied, but without actually running the SQL to change your database schema.\n\nThis is intended for advanced users to manipulate the\ncurrent migration state directly if they're manually applying changes;\nbe warned that using ``--fake`` runs the risk of putting the migration state\ntable into a state where manual recovery will be needed to make migrations\nrun correctly.\n\n.. django-admin-option:: --fake-initial\n\nAllows Django to skip an app's initial migration if all database tables with\nthe names of all models created by all\n:class:`~django.db.migrations.operations.CreateModel` operations in that\nmigration already exist. This option is intended for use when first running\nmigrations against a database that preexisted the use of migrations. This\noption does not, however, check for matching database schema beyond matching\ntable names and so is only safe to use if you are confident that your existing\nschema matches what is recorded in your initial migration.\n\n.. django-admin-option:: --plan\n\nShows the migration operations that will be performed for the given ``migrate``\ncommand.\n\n.. django-admin-option:: --run-syncdb\n\nAllows creating tables for apps without migrations. While this isn't\nrecommended, the migrations framework is sometimes too slow on large projects\nwith hundreds of models.\n\n.. django-admin-option:: --noinput, --no-input\n\nSuppresses all user prompts. An example prompt is asking about removing stale\ncontent types.\n\n.. django-admin-option:: --check\n\n.. versionadded:: 3.1\n\nMakes ``migrate`` exit with a non-zero status when unapplied migrations are\ndetected.\n\n``runserver``\n-------------\n\n.. django-admin:: runserver [addrport]\n\nStarts a lightweight development Web server on the local machine. By default,\nthe server runs on port 8000 on the IP address ``127.0.0.1``. You can pass in an\nIP address and port number explicitly.\n\nIf you run this script as a user with normal privileges (recommended), you\nmight not have access to start a port on a low port number. Low port numbers\nare reserved for the superuser (root).\n\nThis server uses the WSGI application object specified by the\n:setting:`WSGI_APPLICATION` setting.\n\nDO NOT USE THIS SERVER IN A PRODUCTION SETTING. It has not gone through\nsecurity audits or performance tests. (And that's how it's gonna stay. We're in\nthe business of making Web frameworks, not Web servers, so improving this\nserver to be able to handle a production environment is outside the scope of\nDjango.)\n\nThe development server automatically reloads Python code for each request, as\nneeded. You don't need to restart the server for code changes to take effect.\nHowever, some actions like adding files don't trigger a restart, so you'll\nhave to restart the server in these cases.\n\nIf you're using Linux or MacOS and install both `pywatchman`_ and the\n`Watchman`_ service, kernel signals will be used to autoreload the server\n(rather than polling file modification timestamps each second). This offers\nbetter performance on large projects, reduced response time after code changes,\nmore robust change detection, and a reduction in power usage. Django supports\n``pywatchman`` 1.2.0 and higher.\n\n.. admonition:: Large directories with many files may cause performance issues\n\n    When using Watchman with a project that includes large non-Python\n    directories like ``node_modules``, it's advisable to ignore this directory\n    for optimal performance. See the `watchman documentation`_ for information\n    on how to do this.\n\n.. admonition:: Watchman timeout\n\n    .. envvar:: DJANGO_WATCHMAN_TIMEOUT\n\n    The default timeout of ``Watchman`` client is 5 seconds. You can change it\n    by setting the :envvar:`DJANGO_WATCHMAN_TIMEOUT` environment variable.\n\n.. _Watchman: https://facebook.github.io/watchman/\n.. _pywatchman: https://pypi.org/project/pywatchman/\n.. _watchman documentation: https://facebook.github.io/watchman/docs/config#ignore_dirs\n\nWhen you start the server, and each time you change Python code while the\nserver is running, the system check framework will check your entire Django\nproject for some common errors (see the :djadmin:`check` command). If any\nerrors are found, they will be printed to standard output.\n\nYou can run as many concurrent servers as you want, as long as they're on\nseparate ports by executing ``django-admin runserver`` more than once.\n\nNote that the default IP address, ``127.0.0.1``, is not accessible from other\nmachines on your network. To make your development server viewable to other\nmachines on the network, use its own IP address (e.g. ``192.168.2.1``) or\n``0.0.0.0`` or ``::`` (with IPv6 enabled).\n\nYou can provide an IPv6 address surrounded by brackets\n(e.g. ``[200a::1]:8000``). This will automatically enable IPv6 support.\n\nA hostname containing ASCII-only characters can also be used.\n\nIf the :doc:`staticfiles</ref/contrib/staticfiles>` contrib app is enabled\n(default in new projects) the :djadmin:`runserver` command will be overridden\nwith its own :ref:`runserver<staticfiles-runserver>` command.\n\nLogging of each request and response of the server is sent to the\n:ref:`django-server-logger` logger.\n\n.. django-admin-option:: --noreload\n\nDisables the auto-reloader. This means any Python code changes you make while\nthe server is running will *not* take effect if the particular Python modules\nhave already been loaded into memory.\n\n.. django-admin-option:: --nothreading\n\nDisables use of threading in the development server. The server is\nmultithreaded by default.\n\n.. django-admin-option:: --ipv6, -6\n\nUses IPv6 for the development server. This changes the default IP address from\n``127.0.0.1`` to ``::1``.\n\nExamples of using different ports and addresses\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nPort 8000 on IP address ``127.0.0.1``::\n\n    django-admin runserver\n\nPort 8000 on IP address ``1.2.3.4``::\n\n    django-admin runserver 1.2.3.4:8000\n\nPort 7000 on IP address ``127.0.0.1``::\n\n    django-admin runserver 7000\n\nPort 7000 on IP address ``1.2.3.4``::\n\n    django-admin runserver 1.2.3.4:7000\n\nPort 8000 on IPv6 address ``::1``::\n\n    django-admin runserver -6\n\nPort 7000 on IPv6 address ``::1``::\n\n    django-admin runserver -6 7000\n\nPort 7000 on IPv6 address ``2001:0db8:1234:5678::9``::\n\n    django-admin runserver [2001:0db8:1234:5678::9]:7000\n\nPort 8000 on IPv4 address of host ``localhost``::\n\n    django-admin runserver localhost:8000\n\nPort 8000 on IPv6 address of host ``localhost``::\n\n    django-admin runserver -6 localhost:8000\n\nServing static files with the development server\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nBy default, the development server doesn't serve any static files for your site\n(such as CSS files, images, things under :setting:`MEDIA_URL` and so forth). If\nyou want to configure Django to serve static media, read\n:doc:`/howto/static-files/index`.\n\n``sendtestemail``\n-----------------\n\n.. django-admin:: sendtestemail [email [email ...]]\n\nSends a test email (to confirm email sending through Django is working) to the\nrecipient(s) specified. For example::\n\n    django-admin sendtestemail foo@example.com bar@example.com\n\nThere are a couple of options, and you may use any combination of them\ntogether:\n\n.. django-admin-option:: --managers\n\nMails the email addresses specified in :setting:`MANAGERS` using\n:meth:`~django.core.mail.mail_managers()`.\n\n.. django-admin-option:: --admins\n\nMails the email addresses specified in :setting:`ADMINS` using\n:meth:`~django.core.mail.mail_admins()`.\n\n``shell``\n---------\n\n.. django-admin:: shell\n\nStarts the Python interactive interpreter.\n\n.. django-admin-option:: --interface {ipython,bpython,python}, -i {ipython,bpython,python}\n\nSpecifies the shell to use. By default, Django will use IPython_ or bpython_ if\neither is installed. If both are installed, specify which one you want like so:\n\nIPython::\n\n    django-admin shell -i ipython\n\nbpython::\n\n    django-admin shell -i bpython\n\nIf you have a \"rich\" shell installed but want to force use of the \"plain\"\nPython interpreter, use ``python`` as the interface name, like so::\n\n    django-admin shell -i python\n\n.. _IPython: https://ipython.org/\n.. _bpython: https://bpython-interpreter.org/\n\n.. django-admin-option:: --nostartup\n\nDisables reading the startup script for the \"plain\" Python interpreter. By\ndefault, the script pointed to by the :envvar:`PYTHONSTARTUP` environment\nvariable or the ``~/.pythonrc.py`` script is read.\n\n.. django-admin-option:: --command COMMAND, -c COMMAND\n\nLets you pass a command as a string to execute it as Django, like so::\n\n    django-admin shell --command=\"import django; print(django.__version__)\"\n\nYou can also pass code in on standard input to execute it. For example:\n\n.. code-block:: console\n\n    $ django-admin shell <<EOF\n    > import django\n    > print(django.__version__)\n    > EOF\n\nOn Windows, the REPL is output due to implementation limits of\n:func:`select.select` on that platform.\n\n``showmigrations``\n------------------\n\n.. django-admin:: showmigrations [app_label [app_label ...]]\n\nShows all migrations in a project. You can choose from one of two formats:\n\n.. django-admin-option:: --list, -l\n\nLists all of the apps Django knows about, the migrations available for each\napp, and whether or not each migration is applied (marked by an ``[X]`` next to\nthe migration name). For a ``--verbosity`` of 2 and above, the applied\ndatetimes are also shown.\n\nApps without migrations are also listed, but have ``(no migrations)`` printed\nunder them.\n\nThis is the default output format.\n\n.. django-admin-option:: --plan, -p\n\nShows the migration plan Django will follow to apply migrations. Like\n``--list``, applied migrations are marked by an ``[X]``. For a ``--verbosity``\nof 2 and above, all dependencies of a migration will also be shown.\n\n``app_label``\\s arguments limit the output, however, dependencies of provided\napps may also be included.\n\n.. django-admin-option:: --database DATABASE\n\nSpecifies the database to examine. Defaults to ``default``.\n\n``sqlflush``\n------------\n\n.. django-admin:: sqlflush\n\nPrints the SQL statements that would be executed for the :djadmin:`flush`\ncommand.\n\n.. django-admin-option:: --database DATABASE\n\nSpecifies the database for which to print the SQL. Defaults to ``default``.\n\n``sqlmigrate``\n--------------\n\n.. django-admin:: sqlmigrate app_label migration_name\n\nPrints the SQL for the named migration. This requires an active database\nconnection, which it will use to resolve constraint names; this means you must\ngenerate the SQL against a copy of the database you wish to later apply it on.\n\nNote that ``sqlmigrate`` doesn't colorize its output.\n\n.. django-admin-option:: --backwards\n\nGenerates the SQL for unapplying the migration. By default, the SQL created is\nfor running the migration in the forwards direction.\n\n.. django-admin-option:: --database DATABASE\n\nSpecifies the database for which to generate the SQL. Defaults to ``default``.\n\n``sqlsequencereset``\n--------------------\n\n.. django-admin:: sqlsequencereset app_label [app_label ...]\n\nPrints the SQL statements for resetting sequences for the given app name(s).\n\nSequences are indexes used by some database engines to track the next available\nnumber for automatically incremented fields.\n\nUse this command to generate SQL which will fix cases where a sequence is out\nof sync with its automatically incremented field data.\n\n.. django-admin-option:: --database DATABASE\n\nSpecifies the database for which to print the SQL. Defaults to ``default``.\n\n``squashmigrations``\n--------------------\n\n.. django-admin:: squashmigrations app_label [start_migration_name] migration_name\n\nSquashes the migrations for ``app_label`` up to and including ``migration_name``\ndown into fewer migrations, if possible. The resulting squashed migrations\ncan live alongside the unsquashed ones safely. For more information,\nplease read :ref:`migration-squashing`.\n\nWhen ``start_migration_name`` is given, Django will only include migrations\nstarting from and including this migration. This helps to mitigate the\nsquashing limitation of :class:`~django.db.migrations.operations.RunPython` and\n:class:`django.db.migrations.operations.RunSQL` migration operations.\n\n.. django-admin-option:: --no-optimize\n\nDisables the optimizer when generating a squashed migration. By default, Django\nwill try to optimize the operations in your migrations to reduce the size of\nthe resulting file. Use this option if this process is failing or creating\nincorrect migrations, though please also file a Django bug report about the\nbehavior, as optimization is meant to be safe.\n\n.. django-admin-option:: --noinput, --no-input\n\nSuppresses all user prompts.\n\n.. django-admin-option:: --squashed-name SQUASHED_NAME\n\nSets the name of the squashed migration. When omitted, the name is based on the\nfirst and last migration, with ``_squashed_`` in between.\n\n.. django-admin-option:: --no-header\n\nGenerate squashed migration file without Django version and timestamp header.\n\n``startapp``\n------------\n\n.. django-admin:: startapp name [directory]\n\nCreates a Django app directory structure for the given app name in the current\ndirectory or the given destination.\n\nBy default, :source:`the new directory <django/conf/app_template>` contains a\n``models.py`` file and other app template files. If only the app name is given,\nthe app directory will be created in the current working directory.\n\nIf the optional destination is provided, Django will use that existing\ndirectory rather than creating a new one. You can use '.' to denote the current\nworking directory.\n\nFor example::\n\n    django-admin startapp myapp /Users/jezdez/Code/myapp\n\n.. _custom-app-and-project-templates:\n\n.. django-admin-option:: --template TEMPLATE\n\nProvides the path to a directory with a custom app template file, or a path to\nan uncompressed archive (``.tar``) or a compressed archive (``.tar.gz``,\n``.tar.bz2``, ``.tar.xz``, ``.tar.lzma``, ``.tgz``, ``.tbz2``, ``.txz``,\n``.tlz``, ``.zip``) containing the app template files.\n\nFor example, this would look for an app template in the given directory when\ncreating the ``myapp`` app::\n\n    django-admin startapp --template=/Users/jezdez/Code/my_app_template myapp\n\nDjango will also accept URLs (``http``, ``https``, ``ftp``) to compressed\narchives with the app template files, downloading and extracting them on the\nfly.\n\nFor example, taking advantage of GitHub's feature to expose repositories as\nzip files, you can use a URL like::\n\n    django-admin startapp --template=https://github.com/githubuser/django-app-template/archive/master.zip myapp\n\n.. django-admin-option:: --extension EXTENSIONS, -e EXTENSIONS\n\nSpecifies which file extensions in the app template should be rendered with the\ntemplate engine. Defaults to ``py``.\n\n.. django-admin-option:: --name FILES, -n FILES\n\nSpecifies which files in the app template (in addition to those matching\n``--extension``) should be rendered with the template engine. Defaults to an\nempty list.\n\nThe :class:`template context <django.template.Context>` used for all matching\nfiles is:\n\n- Any option passed to the ``startapp`` command (among the command's supported\n  options)\n- ``app_name`` -- the app name as passed to the command\n- ``app_directory`` -- the full path of the newly created app\n- ``camel_case_app_name`` -- the app name in camel case format\n- ``docs_version`` -- the version of the documentation: ``'dev'`` or ``'1.x'``\n- ``django_version`` -- the version of Django, e.g. ``'2.0.3'``\n\n.. _render_warning:\n\n.. warning::\n\n    When the app template files are rendered with the Django template\n    engine (by default all ``*.py`` files), Django will also replace all\n    stray template variables contained. For example, if one of the Python files\n    contains a docstring explaining a particular feature related\n    to template rendering, it might result in an incorrect example.\n\n    To work around this problem, you can use the :ttag:`templatetag`\n    template tag to \"escape\" the various parts of the template syntax.\n\n    In addition, to allow Python template files that contain Django template\n    language syntax while also preventing packaging systems from trying to\n    byte-compile invalid ``*.py`` files, template files ending with ``.py-tpl``\n    will be renamed to ``.py``.\n\n``startproject``\n----------------\n\n.. django-admin:: startproject name [directory]\n\nCreates a Django project directory structure for the given project name in\nthe current directory or the given destination.\n\nBy default, :source:`the new directory <django/conf/project_template>` contains\n``manage.py`` and a project package (containing a ``settings.py`` and other\nfiles).\n\nIf only the project name is given, both the project directory and project\npackage will be named ``<projectname>`` and the project directory\nwill be created in the current working directory.\n\nIf the optional destination is provided, Django will use that existing\ndirectory as the project directory, and create ``manage.py`` and the project\npackage within it. Use '.' to denote the current working directory.\n\nFor example::\n\n    django-admin startproject myproject /Users/jezdez/Code/myproject_repo\n\n.. django-admin-option:: --template TEMPLATE\n\nSpecifies a directory, file path, or URL of a custom project template. See the\n:option:`startapp --template` documentation for examples and usage.\n\n.. django-admin-option:: --extension EXTENSIONS, -e EXTENSIONS\n\nSpecifies which file extensions in the project template should be rendered with\nthe template engine. Defaults to ``py``.\n\n.. django-admin-option:: --name FILES, -n FILES\n\nSpecifies which files in the project template (in addition to those matching\n``--extension``) should be rendered with the template engine. Defaults to an\nempty list.\n\nThe :class:`template context <django.template.Context>` used is:\n\n- Any option passed to the ``startproject`` command (among the command's\n  supported options)\n- ``project_name`` -- the project name as passed to the command\n- ``project_directory`` -- the full path of the newly created project\n- ``secret_key`` -- a random key for the :setting:`SECRET_KEY` setting\n- ``docs_version`` -- the version of the documentation: ``'dev'`` or ``'1.x'``\n- ``django_version`` -- the version of Django, e.g. ``'2.0.3'``\n\nPlease also see the :ref:`rendering warning <render_warning>` as mentioned\nfor :djadmin:`startapp`.\n\n``test``\n--------\n\n.. django-admin:: test [test_label [test_label ...]]\n\nRuns tests for all installed apps. See :doc:`/topics/testing/index` for more\ninformation.\n\n.. django-admin-option:: --failfast\n\nStops running tests and reports the failure immediately after a test fails.\n\n.. django-admin-option:: --testrunner TESTRUNNER\n\nControls the test runner class that is used to execute tests. This value\noverrides the value provided by the :setting:`TEST_RUNNER` setting.\n\n.. django-admin-option:: --noinput, --no-input\n\nSuppresses all user prompts. A typical prompt is a warning about deleting an\nexisting test database.\n\nTest runner options\n~~~~~~~~~~~~~~~~~~~\n\nThe ``test`` command receives options on behalf of the specified\n:option:`--testrunner`. These are the options of the default test runner:\n:class:`~django.test.runner.DiscoverRunner`.\n\n.. django-admin-option:: --keepdb\n\nPreserves the test database between test runs. This has the advantage of\nskipping both the create and destroy actions which can greatly decrease the\ntime to run tests, especially those in a large test suite. If the test database\ndoes not exist, it will be created on the first run and then preserved for each\nsubsequent run. Unless the :setting:`MIGRATE <TEST_MIGRATE>` test setting is\n``False``, any unapplied migrations will also be applied to the test database\nbefore running the test suite.\n\n.. django-admin-option:: --reverse, -r\n\nSorts test cases in the opposite execution order. This may help in debugging\nthe side effects of tests that aren't properly isolated. :ref:`Grouping by test\nclass <order-of-tests>` is preserved when using this option.\n\n.. django-admin-option:: --debug-mode\n\nSets the :setting:`DEBUG` setting to ``True`` prior to running tests. This may\nhelp troubleshoot test failures.\n\n.. django-admin-option:: --debug-sql, -d\n\nEnables :ref:`SQL logging <django-db-logger>` for failing tests. If\n``--verbosity`` is ``2``, then queries in passing tests are also output.\n\n.. django-admin-option:: --parallel [N]\n\n.. envvar:: DJANGO_TEST_PROCESSES\n\nRuns tests in separate parallel processes. Since modern processors have\nmultiple cores, this allows running tests significantly faster.\n\nBy default ``--parallel`` runs one process per core according to\n:func:`multiprocessing.cpu_count()`. You can adjust the number of processes\neither by providing it as the option's value, e.g. ``--parallel=4``, or by\nsetting the :envvar:`DJANGO_TEST_PROCESSES` environment variable.\n\nDjango distributes test cases — :class:`unittest.TestCase` subclasses — to\nsubprocesses. If there are fewer test cases than configured processes, Django\nwill reduce the number of processes accordingly.\n\nEach process gets its own database. You must ensure that different test cases\ndon't access the same resources. For instance, test cases that touch the\nfilesystem should create a temporary directory for their own use.\n\n.. note::\n\n    If you have test classes that cannot be run in parallel, you can use\n    ``SerializeMixin`` to run them sequentially. See :ref:`Enforce running test\n    classes sequentially <topics-testing-enforce-run-sequentially>`.\n\nThis option requires the third-party ``tblib`` package to display tracebacks\ncorrectly:\n\n.. code-block:: console\n\n    $ python -m pip install tblib\n\nThis feature isn't available on Windows. It doesn't work with the Oracle\ndatabase backend either.\n\nIf you want to use :mod:`pdb` while debugging tests, you must disable parallel\nexecution (``--parallel=1``). You'll see something like ``bdb.BdbQuit`` if you\ndon't.\n\n.. warning::\n\n    When test parallelization is enabled and a test fails, Django may be\n    unable to display the exception traceback. This can make debugging\n    difficult. If you encounter this problem, run the affected test without\n    parallelization to see the traceback of the failure.\n\n    This is a known limitation. It arises from the need to serialize objects\n    in order to exchange them between processes. See\n    :ref:`python:pickle-picklable` for details.\n\n.. option:: --tag TAGS\n\nRuns only tests :ref:`marked with the specified tags <topics-tagging-tests>`.\nMay be specified multiple times and combined with :option:`test --exclude-tag`.\n\n.. option:: --exclude-tag EXCLUDE_TAGS\n\nExcludes tests :ref:`marked with the specified tags <topics-tagging-tests>`.\nMay be specified multiple times and combined with :option:`test --tag`.\n\n.. django-admin-option:: -k TEST_NAME_PATTERNS\n\nRuns test methods and classes matching test name patterns, in the same way as\n:option:`unittest's -k option<unittest.-k>`. Can be specified multiple times.\n\n.. admonition:: Python 3.7 and later\n\n    This feature is only available for Python 3.7 and later.\n\n.. django-admin-option:: --pdb\n\nSpawns a ``pdb`` debugger at each test error or failure. If you have it\ninstalled, ``ipdb`` is used instead.\n\n.. django-admin-option:: --buffer, -b\n\n.. versionadded:: 3.1\n\nDiscards output (``stdout`` and ``stderr``) for passing tests, in the same way\nas :option:`unittest's --buffer option<unittest.-b>`.\n\n``testserver``\n--------------\n\n.. django-admin:: testserver [fixture [fixture ...]]\n\nRuns a Django development server (as in :djadmin:`runserver`) using data from\nthe given fixture(s).\n\nFor example, this command::\n\n    django-admin testserver mydata.json\n\n...would perform the following steps:\n\n#. Create a test database, as described in :ref:`the-test-database`.\n#. Populate the test database with fixture data from the given fixtures.\n   (For more on fixtures, see the documentation for :djadmin:`loaddata` above.)\n#. Runs the Django development server (as in :djadmin:`runserver`), pointed at\n   this newly created test database instead of your production database.\n\nThis is useful in a number of ways:\n\n* When you're writing :doc:`unit tests </topics/testing/overview>` of how your views\n  act with certain fixture data, you can use ``testserver`` to interact with\n  the views in a Web browser, manually.\n\n* Let's say you're developing your Django application and have a \"pristine\"\n  copy of a database that you'd like to interact with. You can dump your\n  database to a fixture (using the :djadmin:`dumpdata` command, explained\n  above), then use ``testserver`` to run your Web application with that data.\n  With this arrangement, you have the flexibility of messing up your data\n  in any way, knowing that whatever data changes you're making are only\n  being made to a test database.\n\nNote that this server does *not* automatically detect changes to your Python\nsource code (as :djadmin:`runserver` does). It does, however, detect changes to\ntemplates.\n\n.. django-admin-option:: --addrport ADDRPORT\n\nSpecifies a different port, or IP address and port, from the default of\n``127.0.0.1:8000``. This value follows exactly the same format and serves\nexactly the same function as the argument to the :djadmin:`runserver` command.\n\nExamples:\n\nTo run the test server on port 7000 with ``fixture1`` and ``fixture2``::\n\n    django-admin testserver --addrport 7000 fixture1 fixture2\n    django-admin testserver fixture1 fixture2 --addrport 7000\n\n(The above statements are equivalent. We include both of them to demonstrate\nthat it doesn't matter whether the options come before or after the fixture\narguments.)\n\nTo run on 1.2.3.4:7000 with a ``test`` fixture::\n\n    django-admin testserver --addrport 1.2.3.4:7000 test\n\n.. django-admin-option:: --noinput, --no-input\n\nSuppresses all user prompts. A typical prompt is a warning about deleting an\nexisting test database.\n\nCommands provided by applications\n=================================\n\nSome commands are only available when the ``django.contrib`` application that\n:doc:`implements </howto/custom-management-commands>` them has been\n:setting:`enabled <INSTALLED_APPS>`. This section describes them grouped by\ntheir application.\n\n``django.contrib.auth``\n-----------------------\n\n``changepassword``\n~~~~~~~~~~~~~~~~~~\n\n.. django-admin:: changepassword [<username>]\n\nThis command is only available if Django's :doc:`authentication system\n</topics/auth/index>` (``django.contrib.auth``) is installed.\n\nAllows changing a user's password. It prompts you to enter a new password twice\nfor the given user. If the entries are identical, this immediately becomes the\nnew password. If you do not supply a user, the command will attempt to change\nthe password whose username matches the current user.\n\n.. django-admin-option:: --database DATABASE\n\nSpecifies the database to query for the user. Defaults to ``default``.\n\nExample usage::\n\n    django-admin changepassword ringo\n\n``createsuperuser``\n~~~~~~~~~~~~~~~~~~~\n\n.. django-admin:: createsuperuser\n\n.. envvar:: DJANGO_SUPERUSER_PASSWORD\n\nThis command is only available if Django's :doc:`authentication system\n</topics/auth/index>` (``django.contrib.auth``) is installed.\n\nCreates a superuser account (a user who has all permissions). This is\nuseful if you need to create an initial superuser account or if you need to\nprogrammatically generate superuser accounts for your site(s).\n\nWhen run interactively, this command will prompt for a password for\nthe new superuser account. When run non-interactively, you can provide\na password by setting the :envvar:`DJANGO_SUPERUSER_PASSWORD` environment\nvariable. Otherwise, no password will be set, and the superuser account will\nnot be able to log in until a password has been manually set for it.\n\nIn non-interactive mode, the\n:attr:`~django.contrib.auth.models.CustomUser.USERNAME_FIELD` and required\nfields (listed in\n:attr:`~django.contrib.auth.models.CustomUser.REQUIRED_FIELDS`) fall back to\n``DJANGO_SUPERUSER_<uppercase_field_name>`` environment variables, unless they\nare overridden by a command line argument. For example, to provide an ``email``\nfield, you can use ``DJANGO_SUPERUSER_EMAIL`` environment variable.\n\n.. django-admin-option:: --noinput, --no-input\n\nSuppresses all user prompts. If a suppressed prompt cannot be resolved\nautomatically, the command will exit with error code 1.\n\n.. django-admin-option:: --username USERNAME\n.. django-admin-option:: --email EMAIL\n\nThe username and email address for the new account can be supplied by\nusing the ``--username`` and ``--email`` arguments on the command\nline. If either of those is not supplied, ``createsuperuser`` will prompt for\nit when running interactively.\n\n.. django-admin-option:: --database DATABASE\n\nSpecifies the database into which the superuser object will be saved.\n\nYou can subclass the management command and override ``get_input_data()`` if you\nwant to customize data input and validation. Consult the source code for\ndetails on the existing implementation and the method's parameters. For example,\nit could be useful if you have a ``ForeignKey`` in\n:attr:`~django.contrib.auth.models.CustomUser.REQUIRED_FIELDS` and want to\nallow creating an instance instead of entering the primary key of an existing\ninstance.\n\n``django.contrib.contenttypes``\n-------------------------------\n\n``remove_stale_contenttypes``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. django-admin:: remove_stale_contenttypes\n\nThis command is only available if Django's :doc:`contenttypes app\n</ref/contrib/contenttypes>` (:mod:`django.contrib.contenttypes`) is installed.\n\nDeletes stale content types (from deleted models) in your database. Any objects\nthat depend on the deleted content types will also be deleted. A list of\ndeleted objects will be displayed before you confirm it's okay to proceed with\nthe deletion.\n\n.. django-admin-option:: --database DATABASE\n\nSpecifies the database to use. Defaults to ``default``.\n\n.. django-admin-option:: --include-stale-apps\n\n.. versionadded:: 3.1\n\nDeletes stale content types including ones from previously installed apps that\nhave been removed from :setting:`INSTALLED_APPS`. Defaults to ``False``.\n\n``django.contrib.gis``\n----------------------\n\n``ogrinspect``\n~~~~~~~~~~~~~~\n\nThis command is only available if :doc:`GeoDjango </ref/contrib/gis/index>`\n(``django.contrib.gis``) is installed.\n\nPlease refer to its :djadmin:`description <ogrinspect>` in the GeoDjango\ndocumentation.\n\n``django.contrib.sessions``\n---------------------------\n\n``clearsessions``\n~~~~~~~~~~~~~~~~~\n\n.. django-admin:: clearsessions\n\nCan be run as a cron job or directly to clean out expired sessions.\n\n``django.contrib.sitemaps``\n---------------------------\n\n``ping_google``\n~~~~~~~~~~~~~~~\n\nThis command is only available if the :doc:`Sitemaps framework\n</ref/contrib/sitemaps>` (``django.contrib.sitemaps``) is installed.\n\nPlease refer to its :djadmin:`description <ping_google>` in the Sitemaps\ndocumentation.\n\n``django.contrib.staticfiles``\n------------------------------\n\n``collectstatic``\n~~~~~~~~~~~~~~~~~\n\nThis command is only available if the :doc:`static files application\n</howto/static-files/index>` (``django.contrib.staticfiles``) is installed.\n\nPlease refer to its :djadmin:`description <collectstatic>` in the\n:doc:`staticfiles </ref/contrib/staticfiles>` documentation.\n\n``findstatic``\n~~~~~~~~~~~~~~\n\nThis command is only available if the :doc:`static files application\n</howto/static-files/index>` (``django.contrib.staticfiles``) is installed.\n\nPlease refer to its :djadmin:`description <findstatic>` in the :doc:`staticfiles\n</ref/contrib/staticfiles>` documentation.\n\nDefault options\n===============\n\n.. program:: None\n\nAlthough some commands may allow their own custom options, every command\nallows for the following options:\n\n.. django-admin-option:: --pythonpath PYTHONPATH\n\nAdds the given filesystem path to the Python `import search path`_. If this\nisn't provided, ``django-admin`` will use the :envvar:`PYTHONPATH` environment\nvariable.\n\nThis option is unnecessary in ``manage.py``, because it takes care of setting\nthe Python path for you.\n\nExample usage::\n\n    django-admin migrate --pythonpath='/home/djangoprojects/myproject'\n\n.. _import search path: https://www.diveinto.org/python3/your-first-python-program.html#importsearchpath\n\n.. django-admin-option:: --settings SETTINGS\n\nSpecifies the settings module to use. The settings module should be in Python\npackage syntax, e.g. ``mysite.settings``. If this isn't provided,\n``django-admin`` will use the :envvar:`DJANGO_SETTINGS_MODULE` environment\nvariable.\n\nThis option is unnecessary in ``manage.py``, because it uses\n``settings.py`` from the current project by default.\n\nExample usage::\n\n    django-admin migrate --settings=mysite.settings\n\n.. django-admin-option:: --traceback\n\nDisplays a full stack trace when a :exc:`~django.core.management.CommandError`\nis raised. By default, ``django-admin`` will show an error message when a\n``CommandError`` occurs and a full stack trace for any other exception.\n\nExample usage::\n\n    django-admin migrate --traceback\n\n.. django-admin-option:: --verbosity {0,1,2,3}, -v {0,1,2,3}\n\nSpecifies the amount of notification and debug information that a command\nshould print to the console.\n\n* ``0`` means no output.\n* ``1`` means normal output (default).\n* ``2`` means verbose output.\n* ``3`` means *very* verbose output.\n\nExample usage::\n\n    django-admin migrate --verbosity 2\n\n.. django-admin-option:: --no-color\n\nDisables colorized command output.  Some commands format their output to be\ncolorized. For example, errors will be printed to the console in red and SQL\nstatements will be syntax highlighted.\n\nExample usage::\n\n    django-admin runserver --no-color\n\n.. django-admin-option:: --force-color\n\nForces colorization of the command output if it would otherwise be disabled\nas discussed in :ref:`syntax-coloring`. For example, you may want to pipe\ncolored output to another command.\n\n.. django-admin-option:: --skip-checks\n\nSkips running system checks prior to running the command. This option is only\navailable if the\n:attr:`~django.core.management.BaseCommand.requires_system_checks` command\nattribute is set to ``True``.\n\nExample usage::\n\n    django-admin migrate --skip-checks\n\nExtra niceties\n==============\n\n.. _syntax-coloring:\n\nSyntax coloring\n---------------\n\n.. envvar:: DJANGO_COLORS\n\nThe ``django-admin`` / ``manage.py`` commands will use pretty\ncolor-coded output if your terminal supports ANSI-colored output. It\nwon't use the color codes if you're piping the command's output to\nanother program unless the :option:`--force-color` option is used.\n\nUnder Windows, the native console doesn't support ANSI escape sequences so by\ndefault there is no color output. But you can install the `ANSICON`_\nthird-party tool, the Django commands will detect its presence and will make\nuse of its services to color output just like on Unix-based platforms.\n\nThe colors used for syntax highlighting can be customized. Django\nships with three color palettes:\n\n* ``dark``, suited to terminals that show white text on a black\n  background. This is the default palette.\n\n* ``light``, suited to terminals that show black text on a white\n  background.\n\n* ``nocolor``, which disables syntax highlighting.\n\nYou select a palette by setting a :envvar:`DJANGO_COLORS` environment\nvariable to specify the palette you want to use. For example, to\nspecify the ``light`` palette under a Unix or OS/X BASH shell, you\nwould run the following at a command prompt::\n\n    export DJANGO_COLORS=\"light\"\n\nYou can also customize the colors that are used. Django specifies a\nnumber of roles in which color is used:\n\n* ``error`` - A major error.\n* ``notice`` - A minor error.\n* ``success`` - A success.\n* ``warning`` - A warning.\n* ``sql_field`` - The name of a model field in SQL.\n* ``sql_coltype`` - The type of a model field in SQL.\n* ``sql_keyword`` - An SQL keyword.\n* ``sql_table`` - The name of a model in SQL.\n* ``http_info`` - A 1XX HTTP Informational server response.\n* ``http_success`` - A 2XX HTTP Success server response.\n* ``http_not_modified`` - A 304 HTTP Not Modified server response.\n* ``http_redirect`` - A 3XX HTTP Redirect server response other than 304.\n* ``http_not_found`` - A 404 HTTP Not Found server response.\n* ``http_bad_request`` - A 4XX HTTP Bad Request server response other than 404.\n* ``http_server_error`` - A 5XX HTTP Server Error response.\n* ``migrate_heading`` - A heading in a migrations management command.\n* ``migrate_label`` - A migration name.\n\nEach of these roles can be assigned a specific foreground and\nbackground color, from the following list:\n\n* ``black``\n* ``red``\n* ``green``\n* ``yellow``\n* ``blue``\n* ``magenta``\n* ``cyan``\n* ``white``\n\nEach of these colors can then be modified by using the following\ndisplay options:\n\n* ``bold``\n* ``underscore``\n* ``blink``\n* ``reverse``\n* ``conceal``\n\nA color specification follows one of the following patterns:\n\n* ``role=fg``\n* ``role=fg/bg``\n* ``role=fg,option,option``\n* ``role=fg/bg,option,option``\n\nwhere ``role`` is the name of a valid color role, ``fg`` is the\nforeground color, ``bg`` is the background color and each ``option``\nis one of the color modifying options. Multiple color specifications\nare then separated by a semicolon. For example::\n\n    export DJANGO_COLORS=\"error=yellow/blue,blink;notice=magenta\"\n\nwould specify that errors be displayed using blinking yellow on blue,\nand notices displayed using magenta. All other color roles would be\nleft uncolored.\n\nColors can also be specified by extending a base palette. If you put\na palette name in a color specification, all the colors implied by that\npalette will be loaded. So::\n\n    export DJANGO_COLORS=\"light;error=yellow/blue,blink;notice=magenta\"\n\nwould specify the use of all the colors in the light color palette,\n*except* for the colors for errors and notices which would be\noverridden as specified.\n\n.. _ANSICON: http://adoxa.altervista.org/ansicon/\n\nBash completion\n---------------\n\nIf you use the Bash shell, consider installing the Django bash completion\nscript, which lives in ``extras/django_bash_completion`` in the Django source\ndistribution. It enables tab-completion of ``django-admin`` and\n``manage.py`` commands, so you can, for instance...\n\n* Type ``django-admin``.\n* Press [TAB] to see all available options.\n* Type ``sql``, then [TAB], to see all available options whose names start\n  with ``sql``.\n\nSee :doc:`/howto/custom-management-commands` for how to add customized actions.\n\n==========================================\nRunning management commands from your code\n==========================================\n\n.. function:: django.core.management.call_command(name, *args, **options)\n\nTo call a management command from code use ``call_command``.\n\n``name``\n  the name of the command to call or a command object. Passing the name is\n  preferred unless the object is required for testing.\n\n``*args``\n  a list of arguments accepted by the command. Arguments are passed to the\n  argument parser, so you can use the same style as you would on the command\n  line. For example, ``call_command('flush', '--verbosity=0')``.\n\n``**options``\n  named options accepted on the command-line. Options are passed to the command\n  without triggering the argument parser, which means you'll need to pass the\n  correct type. For example, ``call_command('flush', verbosity=0)`` (zero must\n  be an integer rather than a string).\n\nExamples::\n\n      from django.core import management\n      from django.core.management.commands import loaddata\n\n      management.call_command('flush', verbosity=0, interactive=False)\n      management.call_command('loaddata', 'test_data', verbosity=0)\n      management.call_command(loaddata.Command(), 'test_data', verbosity=0)\n\nNote that command options that take no arguments are passed as keywords\nwith ``True`` or ``False``, as you can see with the ``interactive`` option above.\n\nNamed arguments can be passed by using either one of the following syntaxes::\n\n      # Similar to the command line\n      management.call_command('dumpdata', '--natural-foreign')\n\n      # Named argument similar to the command line minus the initial dashes and\n      # with internal dashes replaced by underscores\n      management.call_command('dumpdata', natural_foreign=True)\n\n      # `use_natural_foreign_keys` is the option destination variable\n      management.call_command('dumpdata', use_natural_foreign_keys=True)\n\nSome command options have different names when using ``call_command()`` instead\nof ``django-admin`` or ``manage.py``. For example, ``django-admin\ncreatesuperuser --no-input`` translates to ``call_command('createsuperuser',\ninteractive=False)``. To find what keyword argument name to use for\n``call_command()``, check the command's source code for the ``dest`` argument\npassed to ``parser.add_argument()``.\n\nCommand options which take multiple options are passed a list::\n\n      management.call_command('dumpdata', exclude=['contenttypes', 'auth'])\n\nThe return value of the ``call_command()`` function is the same as the return\nvalue of the ``handle()`` method of the command.\n\nOutput redirection\n==================\n\nNote that you can redirect standard output and error streams as all commands\nsupport the ``stdout`` and ``stderr`` options. For example, you could write::\n\n    with open('/path/to/command_output', 'w') as f:\n        management.call_command('dumpdata', stdout=f)\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":31,"nodeType":"TextFile","repoName":null,"name":"paginator.txt","path":"docs/ref","text":"=========\nPaginator\n=========\n\nDjango provides a few classes that help you manage paginated data -- that is,\ndata that's split across several pages, with \"Previous/Next\" links. These\nclasses live in :source:`django/core/paginator.py`.\n\n.. module:: django.core.paginator\n   :synopsis: Classes to help you easily manage paginated data.\n\n``Paginator`` class\n===================\n\n.. class:: Paginator(object_list, per_page, orphans=0, allow_empty_first_page=True)\n\n    A paginator acts like a sequence of :class:`Page` when using ``len()`` or\n    iterating it directly.\n\n    .. versionchanged:: 3.1\n\n        Support for iterating over ``Paginator`` was added.\n\n.. attribute:: Paginator.object_list\n\n    Required. A list, tuple, ``QuerySet``, or other sliceable object with a\n    ``count()`` or ``__len__()`` method. For consistent pagination,\n    ``QuerySet``\\s should be ordered, e.g. with an\n    :meth:`~django.db.models.query.QuerySet.order_by` clause or with a default\n    :attr:`~django.db.models.Options.ordering` on the model.\n\n    .. admonition:: Performance issues paginating large ``QuerySet``\\s\n\n        If you're using a ``QuerySet`` with a very large number of items,\n        requesting high page numbers might be slow on some databases, because\n        the resulting ``LIMIT``/``OFFSET`` query needs to count the number of\n        ``OFFSET`` records which takes longer as the page number gets higher.\n\n.. attribute:: Paginator.per_page\n\n    Required. The maximum number of items to include on a page, not including\n    orphans (see the :attr:`~Paginator.orphans` optional argument below).\n\n.. attribute:: Paginator.orphans\n\n    Optional. Use this when you don't want to have a last page with very few\n    items. If the last page would normally have a number of items less than or\n    equal to ``orphans``, then those items will be added to the previous page\n    (which becomes the last page) instead of leaving the items on a page by\n    themselves. For example, with 23 items, ``per_page=10``, and ``orphans=3``,\n    there will be two pages; the first page with 10 items and the second\n    (and last) page with 13 items. ``orphans`` defaults to zero, which means\n    pages are never combined and the last page may have one item.\n\n.. attribute:: Paginator.allow_empty_first_page\n\n    Optional. Whether or not the first page is allowed to be empty.  If\n    ``False`` and ``object_list`` is  empty, then an ``EmptyPage`` error will\n    be raised.\n\nMethods\n-------\n\n.. method:: Paginator.get_page(number)\n\n    Returns a :class:`Page` object with the given 1-based index, while also\n    handling out of range and invalid page numbers.\n\n    If the page isn't a number, it returns the first page. If the page number\n    is negative or greater than the number of pages, it returns the last page.\n\n    Raises an :exc:`EmptyPage` exception only if you specify\n    ``Paginator(..., allow_empty_first_page=False)`` and the ``object_list`` is\n    empty.\n\n.. method:: Paginator.page(number)\n\n    Returns a :class:`Page` object with the given 1-based index. Raises\n    :exc:`InvalidPage` if the given page number doesn't exist.\n\nAttributes\n----------\n\n.. attribute:: Paginator.count\n\n    The total number of objects, across all pages.\n\n    .. note::\n\n        When determining the number of objects contained in ``object_list``,\n        ``Paginator`` will first try calling ``object_list.count()``. If\n        ``object_list`` has no ``count()`` method, then ``Paginator`` will\n        fall back to using ``len(object_list)``. This allows objects, such as\n        ``QuerySet``, to use a more efficient ``count()`` method when\n        available.\n\n.. attribute:: Paginator.num_pages\n\n    The total number of pages.\n\n.. attribute:: Paginator.page_range\n\n    A 1-based range iterator of page numbers, e.g. yielding ``[1, 2, 3, 4]``.\n\n``Page`` class\n==============\n\nYou usually won't construct ``Page`` objects by hand -- you'll get them by\niterating :class:`Paginator`, or by using :meth:`Paginator.page`.\n\n.. class:: Page(object_list, number, paginator)\n\n    A page acts like a sequence of :attr:`Page.object_list` when using\n    ``len()`` or iterating it directly.\n\nMethods\n-------\n\n.. method:: Page.has_next()\n\n    Returns ``True`` if there's a next page.\n\n.. method:: Page.has_previous()\n\n    Returns ``True`` if there's a previous page.\n\n.. method:: Page.has_other_pages()\n\n    Returns ``True`` if there's a next **or** previous page.\n\n.. method:: Page.next_page_number()\n\n    Returns the next page number. Raises :exc:`InvalidPage` if next page\n    doesn't exist.\n\n.. method:: Page.previous_page_number()\n\n    Returns the previous page number. Raises :exc:`InvalidPage` if previous\n    page doesn't exist.\n\n.. method:: Page.start_index()\n\n    Returns the 1-based index of the first object on the page, relative to all\n    of the objects in the paginator's list. For example, when paginating a list\n    of 5 objects with 2 objects per page, the second page's\n    :meth:`~Page.start_index` would return ``3``.\n\n.. method:: Page.end_index()\n\n    Returns the 1-based index of the last object on the page, relative to all\n    of the objects in the paginator's list. For example, when paginating a list\n    of 5 objects with 2 objects per page, the second page's\n    :meth:`~Page.end_index` would return ``4``.\n\nAttributes\n----------\n\n.. attribute:: Page.object_list\n\n    The list of objects on this page.\n\n.. attribute:: Page.number\n\n    The 1-based page number for this page.\n\n.. attribute:: Page.paginator\n\n    The associated :class:`Paginator` object.\n\nExceptions\n==========\n\n.. exception:: InvalidPage\n\n    A base class for exceptions raised when a paginator is passed an invalid\n    page number.\n\nThe :meth:`Paginator.page` method raises an exception if the requested page is\ninvalid (i.e. not an integer) or contains no objects. Generally, it's enough\nto catch the ``InvalidPage`` exception, but if you'd like more granularity,\nyou can catch either of the following exceptions:\n\n.. exception:: PageNotAnInteger\n\n    Raised when :meth:`~Paginator.page` is given a value that isn't an integer.\n\n.. exception:: EmptyPage\n\n    Raised when :meth:`~Paginator.page` is given a valid value but no objects\n    exist on that page.\n\nBoth of the exceptions are subclasses of :exc:`InvalidPage`, so you can handle\nthem both with ``except InvalidPage``.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":32,"nodeType":"TextFile","repoName":null,"name":"validators.txt","path":"docs/ref","text":"==========\nValidators\n==========\n\n.. module:: django.core.validators\n    :synopsis: Validation utilities and base classes\n\nWriting validators\n==================\n\nA validator is a callable that takes a value and raises a\n:exc:`~django.core.exceptions.ValidationError` if it doesn't meet some\ncriteria. Validators can be useful for re-using validation logic between\ndifferent types of fields.\n\nFor example, here's a validator that only allows even numbers::\n\n    from django.core.exceptions import ValidationError\n    from django.utils.translation import gettext_lazy as _\n\n    def validate_even(value):\n        if value % 2 != 0:\n            raise ValidationError(\n                _('%(value)s is not an even number'),\n                params={'value': value},\n            )\n\nYou can add this to a model field via the field's :attr:`~django.db.models.Field.validators`\nargument::\n\n    from django.db import models\n\n    class MyModel(models.Model):\n        even_field = models.IntegerField(validators=[validate_even])\n\nBecause values are converted to Python before validators are run, you can even\nuse the same validator with forms::\n\n    from django import forms\n\n    class MyForm(forms.Form):\n        even_field = forms.IntegerField(validators=[validate_even])\n\nYou can also use a class with a ``__call__()`` method for more complex or\nconfigurable validators. :class:`RegexValidator`, for example, uses this\ntechnique. If a class-based validator is used in the\n:attr:`~django.db.models.Field.validators` model field option, you should make\nsure it is :ref:`serializable by the migration framework\n<migration-serializing>` by adding :ref:`deconstruct()\n<custom-deconstruct-method>` and ``__eq__()`` methods.\n\nHow validators are run\n======================\n\nSee the :doc:`form validation </ref/forms/validation>` for more information on\nhow validators are run in forms, and :ref:`Validating objects\n<validating-objects>` for how they're run in models. Note that validators will\nnot be run automatically when you save a model, but if you are using a\n:class:`~django.forms.ModelForm`, it will run your validators on any fields\nthat are included in your form. See the\n:doc:`ModelForm documentation </topics/forms/modelforms>` for information on\nhow model validation interacts with forms.\n\nBuilt-in validators\n===================\n\nThe :mod:`django.core.validators` module contains a collection of callable\nvalidators for use with model and form fields. They're used internally but\nare available for use with your own fields, too. They can be used in addition\nto, or in lieu of custom ``field.clean()`` methods.\n\n``RegexValidator``\n------------------\n\n.. class:: RegexValidator(regex=None, message=None, code=None, inverse_match=None, flags=0)\n\n    :param regex: If not ``None``, overrides :attr:`regex`. Can be a regular\n        expression string or a pre-compiled regular expression.\n    :param message: If not ``None``, overrides :attr:`.message`.\n    :param code: If not ``None``, overrides :attr:`code`.\n    :param inverse_match: If not ``None``, overrides :attr:`inverse_match`.\n    :param flags: If not ``None``, overrides :attr:`flags`. In that case,\n        :attr:`regex` must be a regular expression string, or\n        :exc:`TypeError` is raised.\n\n    .. attribute:: regex\n\n        The regular expression pattern to search for within the provided\n        ``value``, or a pre-compiled regular expression. By default, raises a\n        :exc:`~django.core.exceptions.ValidationError` with :attr:`message`\n        and :attr:`code` if a match is not found. That standard behavior can\n        be reversed by setting :attr:`inverse_match` to ``True``, in which case\n        the :exc:`~django.core.exceptions.ValidationError` is raised when a\n        match **is** found. By default, matches any string (including an empty\n        string).\n\n    .. attribute:: message\n\n        The error message used by\n        :exc:`~django.core.exceptions.ValidationError` if validation fails.\n        Defaults to ``\"Enter a valid value\"``.\n\n    .. attribute:: code\n\n        The error code used by :exc:`~django.core.exceptions.ValidationError`\n        if validation fails. Defaults to ``\"invalid\"``.\n\n    .. attribute:: inverse_match\n\n        The match mode for :attr:`regex`. Defaults to ``False``.\n\n    .. attribute:: flags\n\n        The flags used when compiling the regular expression string\n        :attr:`regex`. If :attr:`regex` is a pre-compiled regular expression,\n        and :attr:`flags` is overridden, :exc:`TypeError` is raised. Defaults\n        to ``0``.\n\n``EmailValidator``\n------------------\n\n.. class:: EmailValidator(message=None, code=None, whitelist=None)\n\n    :param message: If not ``None``, overrides :attr:`.message`.\n    :param code: If not ``None``, overrides :attr:`code`.\n    :param whitelist: If not ``None``, overrides :attr:`whitelist`.\n\n    .. attribute:: message\n\n        The error message used by\n        :exc:`~django.core.exceptions.ValidationError` if validation fails.\n        Defaults to ``\"Enter a valid email address\"``.\n\n    .. attribute:: code\n\n        The error code used by :exc:`~django.core.exceptions.ValidationError`\n        if validation fails. Defaults to ``\"invalid\"``.\n\n    .. attribute:: whitelist\n\n        Whitelist of email domains to allow. By default, a regular expression\n        (the ``domain_regex`` attribute) is used to validate whatever appears\n        after the @ sign. However, if that string appears in the whitelist, this\n        validation is bypassed. If not provided, the default whitelist is\n        ``['localhost']``. Other domains that don't contain a dot won't pass\n        validation, so you'd need to whitelist them as necessary.\n\n``URLValidator``\n----------------\n\n.. class:: URLValidator(schemes=None, regex=None, message=None, code=None)\n\n    A :class:`RegexValidator` that ensures a value looks like a URL, and raises\n    an error code of ``'invalid'`` if it doesn't.\n\n    Loopback addresses and reserved IP spaces are considered valid. Literal\n    IPv6 addresses (:rfc:`3986#section-3.2.2`) and Unicode domains are both\n    supported.\n\n    In addition to the optional arguments of its parent :class:`RegexValidator`\n    class, ``URLValidator`` accepts an extra optional attribute:\n\n    .. attribute:: schemes\n\n        URL/URI scheme list to validate against. If not provided, the default\n        list is ``['http', 'https', 'ftp', 'ftps']``. As a reference, the IANA\n        website provides a full list of `valid URI schemes`_.\n\n        .. _valid URI schemes: https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml\n\n``validate_email``\n------------------\n\n.. data:: validate_email\n\n    An :class:`EmailValidator` instance without any customizations.\n\n``validate_slug``\n-----------------\n\n.. data:: validate_slug\n\n    A :class:`RegexValidator` instance that ensures a value consists of only\n    letters, numbers, underscores or hyphens.\n\n``validate_unicode_slug``\n-------------------------\n\n.. data:: validate_unicode_slug\n\n    A :class:`RegexValidator` instance that ensures a value consists of only\n    Unicode letters, numbers, underscores, or hyphens.\n\n``validate_ipv4_address``\n-------------------------\n\n.. data:: validate_ipv4_address\n\n    A :class:`RegexValidator` instance that ensures a value looks like an IPv4\n    address.\n\n``validate_ipv6_address``\n-------------------------\n\n.. data:: validate_ipv6_address\n\n    Uses ``django.utils.ipv6`` to check the validity of an IPv6 address.\n\n``validate_ipv46_address``\n--------------------------\n\n.. data:: validate_ipv46_address\n\n    Uses both ``validate_ipv4_address`` and ``validate_ipv6_address`` to\n    ensure a value is either a valid IPv4 or IPv6 address.\n\n``validate_comma_separated_integer_list``\n-----------------------------------------\n\n.. data:: validate_comma_separated_integer_list\n\n    A :class:`RegexValidator` instance that ensures a value is a\n    comma-separated list of integers.\n\n``int_list_validator``\n----------------------\n\n.. function:: int_list_validator(sep=',', message=None, code='invalid', allow_negative=False)\n\n    Returns a :class:`RegexValidator` instance that ensures a string consists\n    of integers separated by ``sep``. It allows negative integers when\n    ``allow_negative`` is ``True``.\n\n``MaxValueValidator``\n---------------------\n\n.. class:: MaxValueValidator(limit_value, message=None)\n\n    Raises a :exc:`~django.core.exceptions.ValidationError` with a code of\n    ``'max_value'`` if ``value`` is greater than ``limit_value``, which may be\n    a callable.\n\n``MinValueValidator``\n---------------------\n\n.. class:: MinValueValidator(limit_value, message=None)\n\n    Raises a :exc:`~django.core.exceptions.ValidationError` with a code of\n    ``'min_value'`` if ``value`` is less than ``limit_value``, which may be a\n    callable.\n\n``MaxLengthValidator``\n----------------------\n\n.. class:: MaxLengthValidator(limit_value, message=None)\n\n    Raises a :exc:`~django.core.exceptions.ValidationError` with a code of\n    ``'max_length'`` if the length of ``value`` is greater than\n    ``limit_value``, which may be a callable.\n\n``MinLengthValidator``\n----------------------\n\n.. class:: MinLengthValidator(limit_value, message=None)\n\n    Raises a :exc:`~django.core.exceptions.ValidationError` with a code of\n    ``'min_length'`` if the length of ``value`` is less than ``limit_value``,\n    which may be a callable.\n\n``DecimalValidator``\n--------------------\n\n.. class:: DecimalValidator(max_digits, decimal_places)\n\n    Raises :exc:`~django.core.exceptions.ValidationError` with the following\n    codes:\n\n    - ``'max_digits'`` if the number of digits is larger than ``max_digits``.\n    - ``'max_decimal_places'`` if the number of decimals is larger than\n      ``decimal_places``.\n    - ``'max_whole_digits'`` if the number of whole digits is larger than\n      the difference between ``max_digits`` and ``decimal_places``.\n\n``FileExtensionValidator``\n--------------------------\n\n.. class:: FileExtensionValidator(allowed_extensions, message, code)\n\n    Raises a :exc:`~django.core.exceptions.ValidationError` with a code of\n    ``'invalid_extension'`` if the extension of ``value.name`` (``value`` is\n    a :class:`~django.core.files.File`) isn't found in ``allowed_extensions``.\n    The extension is compared case-insensitively with ``allowed_extensions``.\n\n    .. warning::\n\n        Don't rely on validation of the file extension to determine a file's\n        type. Files can be renamed to have any extension no matter what data\n        they contain.\n\n``validate_image_file_extension``\n---------------------------------\n\n.. data:: validate_image_file_extension\n\n    Uses Pillow to ensure that ``value.name`` (``value`` is a\n    :class:`~django.core.files.File`) has `a valid image extension\n    <https://pillow.readthedocs.io/en/latest/handbook/image-file-formats.html>`_.\n\n``ProhibitNullCharactersValidator``\n-----------------------------------\n\n.. class:: ProhibitNullCharactersValidator(message=None, code=None)\n\n    Raises a :exc:`~django.core.exceptions.ValidationError` if ``str(value)``\n    contains one or more nulls characters (``'\\x00'``).\n\n    :param message: If not ``None``, overrides :attr:`.message`.\n    :param code: If not ``None``, overrides :attr:`code`.\n\n    .. attribute:: message\n\n        The error message used by\n        :exc:`~django.core.exceptions.ValidationError` if validation fails.\n        Defaults to ``\"Null characters are not allowed.\"``.\n\n    .. attribute:: code\n\n        The error code used by :exc:`~django.core.exceptions.ValidationError`\n        if validation fails. Defaults to ``\"null_characters_not_allowed\"``.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":33,"nodeType":"TextFile","repoName":null,"name":"checks.txt","path":"docs/ref","text":"======================\nSystem check framework\n======================\n\n.. currentmodule:: django.core.checks\n\nThe system check framework is a set of static checks for validating Django\nprojects. It detects common problems and provides hints for how to fix them.\nThe framework is extensible so you can easily add your own checks.\n\nFor details on how to add your own checks and integrate them with Django's\nsystem checks, see the :doc:`System check topic guide </topics/checks>`.\n\nAPI reference\n=============\n\n``CheckMessage``\n----------------\n\n.. class:: CheckMessage(level, msg, hint=None, obj=None, id=None)\n\nThe warnings and errors raised by system checks must be instances of\n``CheckMessage``. An instance encapsulates a single reportable error or\nwarning. It also provides context and hints applicable to the message, and a\nunique identifier that is used for filtering purposes.\n\nConstructor arguments are:\n\n``level``\n    The severity of the message. Use one of the predefined values: ``DEBUG``,\n    ``INFO``, ``WARNING``, ``ERROR``, ``CRITICAL``. If the level is greater or\n    equal to ``ERROR``, then Django will prevent management commands from\n    executing. Messages with level lower than ``ERROR`` (i.e. warnings) are\n    reported to the console, but can be silenced.\n\n``msg``\n    A short (less than 80 characters) string describing the problem. The string\n    should *not* contain newlines.\n\n``hint``\n    A single-line string providing a hint for fixing the problem. If no hint\n    can be provided, or the hint is self-evident from the error message, the\n    hint can be omitted, or a value of ``None`` can be used.\n\n``obj``\n    Optional. An object providing context for the message (for example, the\n    model where the problem was discovered). The object should be a model,\n    field, or manager or any other object that defines a ``__str__()`` method.\n    The method is used while reporting all messages and its result precedes the\n    message.\n\n``id``\n    Optional string. A unique identifier for the issue. Identifiers should\n    follow the pattern ``applabel.X001``, where ``X`` is one of the letters\n    ``CEWID``, indicating the message severity (``C`` for criticals, ``E`` for\n    errors and so). The number can be allocated by the application, but should\n    be unique within that application.\n\nThere are subclasses to make creating messages with common levels easier. When\nusing them you can omit the ``level`` argument because it is implied by the\nclass name.\n\n.. class:: Debug(msg, hint=None, obj=None, id=None)\n.. class:: Info(msg, hint=None, obj=None, id=None)\n.. class:: Warning(msg, hint=None obj=None, id=None)\n.. class:: Error(msg, hint=None, obj=None, id=None)\n.. class:: Critical(msg, hint=None, obj=None, id=None)\n\n.. _system-check-builtin-tags:\n\nBuiltin tags\n============\n\nDjango's system checks are organized using the following tags:\n\n* ``admin``: Checks of any admin site declarations.\n* ``async_support``: Checks asynchronous-related configuration.\n* ``caches``: Checks cache related configuration.\n* ``compatibility``: Flags potential problems with version upgrades.\n* ``database``: Checks database-related configuration issues. Database checks\n  are not run by default because they do more than static code analysis as\n  regular checks do. They are only run by the :djadmin:`migrate` command or if\n  you specify configured database aliases using the ``--database`` option when\n  calling the :djadmin:`check` command.\n* ``models``: Checks of model, field, and manager definitions.\n* ``security``: Checks security related configuration.\n* ``signals``: Checks on signal declarations and handler registrations.\n* ``staticfiles``: Checks :mod:`django.contrib.staticfiles` configuration.\n* ``templates``: Checks template related configuration.\n* ``translation``: Checks translation related configuration.\n* ``urls``: Checks URL configuration.\n\nSome checks may be registered with multiple tags.\n\n.. versionchanged:: 3.1\n\n    The ``async_support`` tag was added.\n\n.. versionchanged:: 3.1\n\n    The ``database`` checks are now run only for database aliases specified\n    using the :option:`check --database` option.\n\nCore system checks\n==================\n\nAsynchronous support\n--------------------\n\n.. versionadded:: 3.1\n\nThe following checks verify your setup for :doc:`/topics/async`:\n\n* **async.E001**: You should not set the :envvar:`DJANGO_ALLOW_ASYNC_UNSAFE`\n  environment variable in deployment. This disables :ref:`async safety\n  protection <async-safety>`.\n\nBackwards compatibility\n-----------------------\n\nCompatibility checks warn of potential problems that might occur after\nupgrading Django.\n\n* **2_0.W001**: Your URL pattern ``<pattern>`` has a ``route`` that contains\n  ``(?P<``, begins with a ``^``, or ends with a ``$``. This was likely an\n  oversight when migrating from ``url()`` to :func:`~django.urls.path`.\n\nCaches\n------\n\nThe following checks verify that your :setting:`CACHES` setting is correctly\nconfigured:\n\n* **caches.E001**: You must define a ``'default'`` cache in your\n  :setting:`CACHES` setting.\n\nDatabase\n--------\n\nMySQL and MariaDB\n~~~~~~~~~~~~~~~~~\n\nIf you're using MySQL or MariaDB, the following checks will be performed:\n\n* **mysql.E001**: MySQL/MariaDB does not allow unique ``CharField``\\s to have a\n  ``max_length`` > 255. *This check was changed to* ``mysql.W003`` *in Django\n  3.1 as the real maximum size depends on many factors.*\n* **mysql.W002**: MySQL/MariaDB Strict Mode is not set for database connection\n  '<alias>'. See also :ref:`mysql-sql-mode`.\n* **mysql.W003**: MySQL/MariaDB may not allow unique ``CharField``\\s to have a\n  ``max_length`` > 255.\n\nModel fields\n------------\n\n* **fields.E001**: Field names must not end with an underscore.\n* **fields.E002**: Field names must not contain ``\"__\"``.\n* **fields.E003**: ``pk`` is a reserved word that cannot be used as a field\n  name.\n* **fields.E004**: ``choices`` must be an iterable (e.g., a list or tuple).\n* **fields.E005**: ``choices`` must be an iterable returning ``(actual value,\n  human readable name)`` tuples.\n* **fields.E006**: ``db_index`` must be ``None``, ``True`` or ``False``.\n* **fields.E007**: Primary keys must not have ``null=True``.\n* **fields.E008**: All ``validators`` must be callable.\n* **fields.E009**: ``max_length`` is too small to fit the longest value in\n  ``choices`` (``<count>`` characters).\n* **fields.E010**: ``<field>`` default should be a callable instead of an\n  instance so that it's not shared between all field instances.\n* **fields.E100**: ``AutoField``\\s must set primary_key=True.\n* **fields.E110**: ``BooleanField``\\s do not accept null values. *This check\n  appeared before support for null values was added in Django 2.1.*\n* **fields.E120**: ``CharField``\\s must define a ``max_length`` attribute.\n* **fields.E121**: ``max_length`` must be a positive integer.\n* **fields.W122**: ``max_length`` is ignored when used with\n  ``<integer field type>``.\n* **fields.E130**: ``DecimalField``\\s must define a ``decimal_places`` attribute.\n* **fields.E131**: ``decimal_places`` must be a non-negative integer.\n* **fields.E132**: ``DecimalField``\\s must define a ``max_digits`` attribute.\n* **fields.E133**: ``max_digits`` must be a non-negative integer.\n* **fields.E134**: ``max_digits`` must be greater or equal to ``decimal_places``.\n* **fields.E140**: ``FilePathField``\\s must have either ``allow_files`` or\n  ``allow_folders`` set to True.\n* **fields.E150**: ``GenericIPAddressField``\\s cannot accept blank values if\n  null values are not allowed, as blank values are stored as nulls.\n* **fields.E160**: The options ``auto_now``, ``auto_now_add``, and ``default``\n  are mutually exclusive. Only one of these options may be present.\n* **fields.W161**: Fixed default value provided.\n* **fields.W162**: ``<database>`` does not support a database index on\n  ``<field data type>`` columns.\n* **fields.E170**: ``BinaryField``’s ``default`` cannot be a string. Use bytes\n  content instead.\n* **fields.E180**: ``<database>`` does not support ``JSONField``\\s.\n* **fields.E900**: ``IPAddressField`` has been removed except for support in\n  historical migrations.\n* **fields.W900**: ``IPAddressField`` has been deprecated. Support for it\n  (except in historical migrations) will be removed in Django 1.9. *This check\n  appeared in Django 1.7 and 1.8*.\n* **fields.W901**: ``CommaSeparatedIntegerField`` has been deprecated. Support\n  for it (except in historical migrations) will be removed in Django 2.0. *This\n  check appeared in Django 1.10 and 1.11*.\n* **fields.E901**: ``CommaSeparatedIntegerField`` is removed except for support\n  in historical migrations.\n* **fields.W902**: ``FloatRangeField`` is deprecated and will be removed in\n  Django 3.1. *This check appeared in Django 2.2 and 3.0*.\n* **fields.W903**: ``NullBooleanField`` is deprecated. Support for it (except\n  in historical migrations) will be removed in Django 4.0.\n* **fields.W904**: ``django.contrib.postgres.fields.JSONField`` is deprecated.\n  Support for it (except in historical migrations) will be removed in Django\n  4.0.\n\nFile fields\n~~~~~~~~~~~\n\n* **fields.E200**: ``unique`` is not a valid argument for a ``FileField``.\n  *This check is removed in Django 1.11*.\n* **fields.E201**: ``primary_key`` is not a valid argument for a ``FileField``.\n* **fields.E202**: ``FileField``’s ``upload_to`` argument must be a relative\n  path, not an absolute path.\n* **fields.E210**: Cannot use ``ImageField`` because Pillow is not installed.\n\nRelated fields\n~~~~~~~~~~~~~~\n\n* **fields.E300**: Field defines a relation with model ``<model>``, which is\n  either not installed, or is abstract.\n* **fields.E301**: Field defines a relation with the model ``<model>`` which\n  has been swapped out.\n* **fields.E302**: Accessor for field ``<field name>`` clashes with field\n  ``<field name>``.\n* **fields.E303**: Reverse query name for field ``<field name>`` clashes with\n  field ``<field name>``.\n* **fields.E304**: Field name ``<field name>`` clashes with accessor for\n  ``<field name>``.\n* **fields.E305**: Field name ``<field name>`` clashes with reverse query name\n  for ``<field name>``.\n* **fields.E306**: Related name must be a valid Python identifier or end with\n  a ``'+'``.\n* **fields.E307**: The field ``<app label>.<model>.<field name>`` was declared\n  with a lazy reference to ``<app label>.<model>``, but app ``<app label>``\n  isn't installed or doesn't provide model ``<model>``.\n* **fields.E308**: Reverse query name ``<related query name>`` must not end\n  with an underscore.\n* **fields.E309**: Reverse query name ``<related query name>`` must not contain\n  ``'__'``.\n* **fields.E310**: No subset of the fields ``<field1>``, ``<field2>``, ... on\n  model ``<model>`` is unique.\n* **fields.E311**: ``<model>.<field name>`` must be unique because it is\n  referenced by a ``ForeignKey``.\n* **fields.E312**: The ``to_field`` ``<field name>`` doesn't exist on the\n  related model ``<app label>.<model>``.\n* **fields.E320**: Field specifies ``on_delete=SET_NULL``, but cannot be null.\n* **fields.E321**: The field specifies ``on_delete=SET_DEFAULT``, but has no\n  default value.\n* **fields.E330**: ``ManyToManyField``\\s cannot be unique.\n* **fields.E331**: Field specifies a many-to-many relation through model\n  ``<model>``, which has not been installed.\n* **fields.E332**: Many-to-many fields with intermediate tables must not be\n  symmetrical. *This check appeared before Django 3.0.*\n* **fields.E333**: The model is used as an intermediate model by ``<model>``,\n  but it has more than two foreign keys to ``<model>``, which is ambiguous.\n  You must specify which two foreign keys Django should use via the\n  ``through_fields`` keyword argument.\n* **fields.E334**: The model is used as an intermediate model by ``<model>``,\n  but it has more than one foreign key from ``<model>``, which is ambiguous.\n  You must specify which foreign key Django should use via the\n  ``through_fields`` keyword argument.\n* **fields.E335**: The model is used as an intermediate model by ``<model>``,\n  but it has more than one foreign key to ``<model>``, which is ambiguous.\n  You must specify which foreign key Django should use via the\n  ``through_fields`` keyword argument.\n* **fields.E336**: The model is used as an intermediary model by ``<model>``,\n  but it does not have foreign key to ``<model>`` or ``<model>``.\n* **fields.E337**: Field specifies ``through_fields`` but does not provide the\n  names of the two link fields that should be used for the relation through\n  ``<model>``.\n* **fields.E338**: The intermediary model ``<through model>`` has no field\n  ``<field name>``.\n* **fields.E339**: ``<model>.<field name>`` is not a foreign key to ``<model>``.\n* **fields.E340**: The field's intermediary table ``<table name>`` clashes with\n  the table name of ``<model>``/``<model>.<field name>``.\n* **fields.W340**: ``null`` has no effect on ``ManyToManyField``.\n* **fields.W341**: ``ManyToManyField`` does not support ``validators``.\n* **fields.W342**: Setting ``unique=True`` on a ``ForeignKey`` has the same\n  effect as using a ``OneToOneField``.\n* **fields.W343**: ``limit_choices_to`` has no effect on ``ManyToManyField``\n  with a ``through`` model.\n* **fields.W344**: The field's intermediary table ``<table name>`` clashes with\n  the table name of ``<model>``/``<model>.<field name>``.\n\nModels\n------\n\n* **models.E001**: ``<swappable>`` is not of the form ``app_label.app_name``.\n* **models.E002**: ``<SETTING>`` references ``<model>``, which has not been\n  installed, or is abstract.\n* **models.E003**: The model has two identical many-to-many relations through\n  the intermediate model ``<app_label>.<model>``.\n* **models.E004**: ``id`` can only be used as a field name if the field also\n  sets ``primary_key=True``.\n* **models.E005**: The field ``<field name>`` from parent model ``<model>``\n  clashes with the field ``<field name>`` from parent model ``<model>``.\n* **models.E006**: The field clashes with the field ``<field name>`` from model\n  ``<model>``.\n* **models.E007**: Field ``<field name>`` has column name ``<column name>``\n  that is used by another field.\n* **models.E008**: ``index_together`` must be a list or tuple.\n* **models.E009**: All ``index_together`` elements must be lists or tuples.\n* **models.E010**: ``unique_together`` must be a list or tuple.\n* **models.E011**: All ``unique_together`` elements must be lists or tuples.\n* **models.E012**: ``indexes/index_together/unique_together`` refers to the\n  nonexistent field ``<field name>``.\n* **models.E013**: ``indexes/index_together/unique_together`` refers to a\n  ``ManyToManyField`` ``<field name>``, but ``ManyToManyField``\\s are not\n  supported for that option.\n* **models.E014**: ``ordering`` must be a tuple or list (even if you want to\n  order by only one field).\n* **models.E015**: ``ordering`` refers to the nonexistent field, related field,\n  or lookup ``<field name>``.\n* **models.E016**: ``indexes/index_together/unique_together`` refers to field\n  ``<field_name>`` which is not local to model ``<model>``.\n* **models.E017**: Proxy model ``<model>`` contains model fields.\n* **models.E018**: Autogenerated column name too long for field ``<field>``.\n  Maximum length is ``<maximum length>`` for database ``<alias>``.\n* **models.E019**: Autogenerated column name too long for M2M field\n  ``<M2M field>``. Maximum length is ``<maximum length>`` for database\n  ``<alias>``.\n* **models.E020**: The ``<model>.check()`` class method is currently overridden.\n* **models.E021**: ``ordering`` and ``order_with_respect_to`` cannot be used\n  together.\n* **models.E022**: ``<function>`` contains a lazy reference to\n  ``<app label>.<model>``, but app ``<app label>`` isn't installed or\n  doesn't provide model ``<model>``.\n* **models.E023**: The model name ``<model>`` cannot start or end with an\n  underscore as it collides with the query lookup syntax.\n* **models.E024**: The model name ``<model>`` cannot contain double underscores\n  as it collides with the query lookup syntax.\n* **models.E025**: The property ``<property name>`` clashes with a related\n  field accessor.\n* **models.E026**: The model cannot have more than one field with\n  ``primary_key=True``.\n* **models.W027**: ``<database>`` does not support check constraints.\n* **models.E028**: ``db_table`` ``<db_table>`` is used by multiple models:\n  ``<model list>``.\n* **models.E029**: index name ``<index>`` is not unique for model ``<model>``.\n* **models.E030**: index name ``<index>`` is not unique amongst models:\n  ``<model list>``.\n* **models.E031**: constraint name ``<constraint>`` is not unique for model\n  ``<model>``.\n* **models.E032**: constraint name ``<constraint>`` is not unique amongst\n  models: ``<model list>``.\n* **models.E033**: The index name ``<index>`` cannot start with an underscore\n  or a number.\n* **models.E034**: The index name ``<index>`` cannot be longer than\n  ``<max_length>`` characters.\n* **models.W035**: ``db_table`` ``<db_table>`` is used by multiple models:\n  ``<model list>``.\n* **models.W036**: ``<database>`` does not support unique constraints with\n  conditions.\n* **models.W037**: ``<database>`` does not support indexes with conditions.\n* **models.W038**: ``<database>`` does not support deferrable unique\n  constraints.\n\nSecurity\n--------\n\nThe security checks do not make your site secure. They do not audit code, do\nintrusion detection, or do anything particularly complex. Rather, they help\nperform an automated, low-hanging-fruit checklist, that can help you to improve\nyour site's security.\n\nSome of these checks may not be appropriate for your particular deployment\nconfiguration. For instance, if you do your HTTP to HTTPS redirection in a load\nbalancer, it'd be irritating to be constantly warned about not having enabled\n:setting:`SECURE_SSL_REDIRECT`. Use :setting:`SILENCED_SYSTEM_CHECKS` to\nsilence unneeded checks.\n\nThe following checks are run if you use the :option:`check --deploy` option:\n\n* **security.W001**: You do not have\n  :class:`django.middleware.security.SecurityMiddleware` in your\n  :setting:`MIDDLEWARE` so the :setting:`SECURE_HSTS_SECONDS`,\n  :setting:`SECURE_CONTENT_TYPE_NOSNIFF`, :setting:`SECURE_BROWSER_XSS_FILTER`,\n  :setting:`SECURE_REFERRER_POLICY`, and :setting:`SECURE_SSL_REDIRECT`\n  settings will have no effect.\n* **security.W002**: You do not have\n  :class:`django.middleware.clickjacking.XFrameOptionsMiddleware` in your\n  :setting:`MIDDLEWARE`, so your pages will not be served with an\n  ``'x-frame-options'`` header. Unless there is a good reason for your\n  site to be served in a frame, you should consider enabling this\n  header to help prevent clickjacking attacks.\n* **security.W003**: You don't appear to be using Django's built-in cross-site\n  request forgery protection via the middleware\n  (:class:`django.middleware.csrf.CsrfViewMiddleware` is not in your\n  :setting:`MIDDLEWARE`). Enabling the middleware is the safest\n  approach to ensure you don't leave any holes.\n* **security.W004**: You have not set a value for the\n  :setting:`SECURE_HSTS_SECONDS` setting. If your entire site is served only\n  over SSL, you may want to consider setting a value and enabling :ref:`HTTP\n  Strict Transport Security <http-strict-transport-security>`. Be sure to read\n  the documentation first; enabling HSTS carelessly can cause serious,\n  irreversible problems.\n* **security.W005**: You have not set the\n  :setting:`SECURE_HSTS_INCLUDE_SUBDOMAINS` setting to ``True``. Without this,\n  your site is potentially vulnerable to attack via an insecure connection to a\n  subdomain. Only set this to ``True`` if you are certain that all subdomains of\n  your domain should be served exclusively via SSL.\n* **security.W006**: Your :setting:`SECURE_CONTENT_TYPE_NOSNIFF` setting is not\n  set to ``True``, so your pages will not be served with an\n  ``'X-Content-Type-Options: nosniff'`` header. You should consider enabling\n  this header to prevent the browser from identifying content types incorrectly.\n* **security.W007**: Your :setting:`SECURE_BROWSER_XSS_FILTER` setting is not\n  set to ``True``, so your pages will not be served with an\n  ``'X-XSS-Protection: 1; mode=block'`` header. You should consider enabling\n  this header to activate the browser's XSS filtering and help prevent XSS\n  attacks. *This check is removed in Django 3.0 as the ``X-XSS-Protection``\n  header is no longer honored by modern browsers.*\n* **security.W008**: Your :setting:`SECURE_SSL_REDIRECT` setting is not set to\n  ``True``. Unless your site should be available over both SSL and non-SSL\n  connections, you may want to either set this setting to ``True`` or configure\n  a load balancer or reverse-proxy server  to redirect all connections to HTTPS.\n* **security.W009**: Your :setting:`SECRET_KEY` has less than 50 characters or\n  less than 5 unique characters. Please generate a long and random\n  ``SECRET_KEY``, otherwise many of Django's security-critical features will be\n  vulnerable to attack.\n* **security.W010**: You have :mod:`django.contrib.sessions` in your\n  :setting:`INSTALLED_APPS` but you have not set\n  :setting:`SESSION_COOKIE_SECURE` to ``True``. Using a secure-only session\n  cookie makes it more difficult for network traffic sniffers to hijack user\n  sessions.\n* **security.W011**: You have\n  :class:`django.contrib.sessions.middleware.SessionMiddleware` in your\n  :setting:`MIDDLEWARE`, but you have not set :setting:`SESSION_COOKIE_SECURE`\n  to ``True``. Using a secure-only session cookie makes it more difficult for\n  network traffic sniffers to hijack user sessions.\n* **security.W012**: :setting:`SESSION_COOKIE_SECURE` is not set to ``True``.\n  Using a secure-only session cookie makes it more difficult for network traffic\n  sniffers to hijack user sessions.\n* **security.W013**: You have :mod:`django.contrib.sessions` in your\n  :setting:`INSTALLED_APPS`, but you have not set\n  :setting:`SESSION_COOKIE_HTTPONLY` to ``True``. Using an ``HttpOnly`` session\n  cookie makes it more difficult for cross-site scripting attacks to hijack user\n  sessions.\n* **security.W014**: You have\n  :class:`django.contrib.sessions.middleware.SessionMiddleware` in your\n  :setting:`MIDDLEWARE`, but you have not set :setting:`SESSION_COOKIE_HTTPONLY`\n  to ``True``. Using an ``HttpOnly`` session cookie makes it more difficult for\n  cross-site scripting attacks to hijack user sessions.\n* **security.W015**: :setting:`SESSION_COOKIE_HTTPONLY` is not set to ``True``.\n  Using an ``HttpOnly`` session cookie makes it more difficult for cross-site\n  scripting attacks to hijack user sessions.\n* **security.W016**: :setting:`CSRF_COOKIE_SECURE` is not set to ``True``.\n  Using a secure-only CSRF cookie makes it more difficult for network traffic\n  sniffers to steal the CSRF token.\n* **security.W017**: :setting:`CSRF_COOKIE_HTTPONLY` is not set to ``True``.\n  Using an ``HttpOnly`` CSRF cookie makes it more difficult for cross-site\n  scripting attacks to steal the CSRF token. *This check is removed in Django\n  1.11 as the* :setting:`CSRF_COOKIE_HTTPONLY` *setting offers no practical\n  benefit.*\n* **security.W018**: You should not have :setting:`DEBUG` set to ``True`` in\n  deployment.\n* **security.W019**: You have\n  :class:`django.middleware.clickjacking.XFrameOptionsMiddleware` in your\n  :setting:`MIDDLEWARE`, but :setting:`X_FRAME_OPTIONS` is not set to\n  ``'DENY'``. Unless there is a good reason for your site to serve other parts\n  of itself in a frame, you should change it to ``'DENY'``.\n* **security.W020**: :setting:`ALLOWED_HOSTS` must not be empty in deployment.\n* **security.W021**: You have not set the\n  :setting:`SECURE_HSTS_PRELOAD` setting to ``True``. Without this, your site\n  cannot be submitted to the browser preload list.\n* **security.W022**: You have not set the :setting:`SECURE_REFERRER_POLICY`\n  setting. Without this, your site will not send a Referrer-Policy header. You\n  should consider enabling this header to protect user privacy.\n* **security.E023**: You have set the :setting:`SECURE_REFERRER_POLICY` setting\n  to an invalid value.\n\nSignals\n-------\n\n* **signals.E001**: ``<handler>`` was connected to the ``<signal>`` signal with\n  a lazy reference to the sender ``<app label>.<model>``, but app ``<app label>``\n  isn't installed or doesn't provide model ``<model>``.\n\nTemplates\n---------\n\nThe following checks verify that your :setting:`TEMPLATES` setting is correctly\nconfigured:\n\n* **templates.E001**: You have ``'APP_DIRS': True`` in your\n  :setting:`TEMPLATES` but also specify ``'loaders'`` in ``OPTIONS``. Either\n  remove ``APP_DIRS`` or remove the ``'loaders'`` option.\n* **templates.E002**: ``string_if_invalid`` in :setting:`TEMPLATES`\n  :setting:`OPTIONS <TEMPLATES-OPTIONS>` must be a string but got: ``{value}``\n  (``{type}``).\n\nTranslation\n-----------\n\nThe following checks are performed on your translation configuration:\n\n* **translation.E001**: You have provided an invalid value for the\n  :setting:`LANGUAGE_CODE` setting: ``<value>``.\n* **translation.E002**: You have provided an invalid language code in the\n  :setting:`LANGUAGES` setting: ``<value>``.\n* **translation.E003**: You have provided an invalid language code in the\n  :setting:`LANGUAGES_BIDI` setting: ``<value>``.\n* **translation.E004**: You have provided a value for the\n  :setting:`LANGUAGE_CODE` setting that is not in the :setting:`LANGUAGES`\n  setting.\n\nURLs\n----\n\nThe following checks are performed on your URL configuration:\n\n* **urls.W001**: Your URL pattern ``<pattern>`` uses\n  :func:`~django.urls.include` with a ``route`` ending with a ``$``. Remove the\n  dollar from the ``route`` to avoid problems including URLs.\n* **urls.W002**: Your URL pattern ``<pattern>`` has a ``route`` beginning with\n  a ``/``. Remove this slash as it is unnecessary. If this pattern is targeted\n  in an :func:`~django.urls.include`, ensure the :func:`~django.urls.include`\n  pattern has a trailing ``/``.\n* **urls.W003**: Your URL pattern ``<pattern>`` has a ``name``\n  including a ``:``. Remove the colon, to avoid ambiguous namespace\n  references.\n* **urls.E004**: Your URL pattern ``<pattern>`` is invalid. Ensure that\n  ``urlpatterns`` is a list of :func:`~django.urls.path` and/or\n  :func:`~django.urls.re_path` instances.\n* **urls.W005**: URL namespace ``<namespace>`` isn't unique. You may not be\n  able to reverse all URLs in this namespace.\n* **urls.E006**: The :setting:`MEDIA_URL`/ :setting:`STATIC_URL` setting must\n  end with a slash.\n* **urls.E007**: The custom ``handlerXXX`` view ``'path.to.view'`` does not\n  take the correct number of arguments (…).\n* **urls.E008**: The custom ``handlerXXX`` view ``'path.to.view'`` could not be\n  imported.\n\n``contrib`` app checks\n======================\n\n``admin``\n---------\n\nAdmin checks are all performed as part of the ``admin`` tag.\n\nThe following checks are performed on any\n:class:`~django.contrib.admin.ModelAdmin` (or subclass) that is registered\nwith the admin site:\n\n* **admin.E001**: The value of ``raw_id_fields`` must be a list or tuple.\n* **admin.E002**: The value of ``raw_id_fields[n]`` refers to ``<field name>``,\n  which is not an attribute of ``<model>``.\n* **admin.E003**: The value of ``raw_id_fields[n]`` must be a foreign key or\n  a many-to-many field.\n* **admin.E004**: The value of ``fields`` must be a list or tuple.\n* **admin.E005**: Both ``fieldsets`` and ``fields`` are specified.\n* **admin.E006**: The value of ``fields`` contains duplicate field(s).\n* **admin.E007**: The value of ``fieldsets`` must be a list or tuple.\n* **admin.E008**: The value of ``fieldsets[n]`` must be a list or tuple.\n* **admin.E009**: The value of ``fieldsets[n]`` must be of length 2.\n* **admin.E010**: The value of ``fieldsets[n][1]`` must be a dictionary.\n* **admin.E011**: The value of ``fieldsets[n][1]`` must contain the key\n  ``fields``.\n* **admin.E012**: There are duplicate field(s) in ``fieldsets[n][1]``.\n* **admin.E013**: ``fields[n]/fieldsets[n][m]`` cannot include the\n  ``ManyToManyField`` ``<field name>``, because that field manually specifies a\n  relationship model.\n* **admin.E014**: The value of ``exclude`` must be a list or tuple.\n* **admin.E015**: The value of ``exclude`` contains duplicate field(s).\n* **admin.E016**: The value of ``form`` must inherit from ``BaseModelForm``.\n* **admin.E017**: The value of ``filter_vertical`` must be a list or tuple.\n* **admin.E018**: The value of ``filter_horizontal`` must be a list or tuple.\n* **admin.E019**: The value of ``filter_vertical[n]/filter_vertical[n]`` refers\n  to ``<field name>``, which is not an attribute of ``<model>``.\n* **admin.E020**: The value of ``filter_vertical[n]/filter_vertical[n]`` must\n  be a many-to-many field.\n* **admin.E021**: The value of ``radio_fields`` must be a dictionary.\n* **admin.E022**: The value of ``radio_fields`` refers to ``<field name>``,\n  which is not an attribute of ``<model>``.\n* **admin.E023**: The value of ``radio_fields`` refers to ``<field name>``,\n  which is not a ``ForeignKey``, and does not have a ``choices`` definition.\n* **admin.E024**: The value of ``radio_fields[<field name>]`` must be either\n  ``admin.HORIZONTAL`` or ``admin.VERTICAL``.\n* **admin.E025**: The value of ``view_on_site`` must be either a callable or a\n  boolean value.\n* **admin.E026**: The value of ``prepopulated_fields`` must be a dictionary.\n* **admin.E027**: The value of ``prepopulated_fields`` refers to\n  ``<field name>``, which is not an attribute of ``<model>``.\n* **admin.E028**: The value of ``prepopulated_fields`` refers to\n  ``<field name>``, which must not be a ``DateTimeField``, a ``ForeignKey``,\n  a ``OneToOneField``, or a ``ManyToManyField`` field.\n* **admin.E029**: The value of ``prepopulated_fields[<field name>]`` must be a\n  list or tuple.\n* **admin.E030**: The value of ``prepopulated_fields`` refers to\n  ``<field name>``, which is not an attribute of ``<model>``.\n* **admin.E031**: The value of ``ordering`` must be a list or tuple.\n* **admin.E032**: The value of ``ordering`` has the random ordering marker\n  ``?``, but contains other fields as well.\n* **admin.E033**: The value of ``ordering`` refers to ``<field name>``, which\n  is not an attribute of ``<model>``.\n* **admin.E034**: The value of ``readonly_fields`` must be a list or tuple.\n* **admin.E035**: The value of ``readonly_fields[n]`` is not a callable, an\n  attribute of ``<ModelAdmin class>``, or an attribute of ``<model>``.\n* **admin.E036**: The value of ``autocomplete_fields`` must be a list or tuple.\n* **admin.E037**: The value of ``autocomplete_fields[n]`` refers to\n  ``<field name>``, which is not an attribute of ``<model>``.\n* **admin.E038**: The value of ``autocomplete_fields[n]`` must be a foreign\n  key or a many-to-many field.\n* **admin.E039**: An admin for model ``<model>`` has to be registered to be\n  referenced by ``<modeladmin>.autocomplete_fields``.\n* **admin.E040**: ``<modeladmin>`` must define ``search_fields``, because\n  it's referenced by ``<other_modeladmin>.autocomplete_fields``.\n\n``ModelAdmin``\n~~~~~~~~~~~~~~\n\nThe following checks are performed on any\n:class:`~django.contrib.admin.ModelAdmin` that is registered\nwith the admin site:\n\n* **admin.E101**: The value of ``save_as`` must be a boolean.\n* **admin.E102**: The value of ``save_on_top`` must be a boolean.\n* **admin.E103**: The value of ``inlines`` must be a list or tuple.\n* **admin.E104**: ``<InlineModelAdmin class>`` must inherit from\n  ``InlineModelAdmin``.\n* **admin.E105**: ``<InlineModelAdmin class>`` must have a ``model`` attribute.\n* **admin.E106**: The value of ``<InlineModelAdmin class>.model`` must be a\n  ``Model``.\n* **admin.E107**: The value of ``list_display`` must be a list or tuple.\n* **admin.E108**: The value of ``list_display[n]`` refers to ``<label>``,\n  which is not a callable, an attribute of ``<ModelAdmin class>``, or an\n  attribute or method on ``<model>``.\n* **admin.E109**: The value of ``list_display[n]`` must not be a\n  ``ManyToManyField`` field.\n* **admin.E110**: The value of ``list_display_links`` must be a list, a tuple,\n  or ``None``.\n* **admin.E111**: The value of ``list_display_links[n]`` refers to ``<label>``,\n  which is not defined in ``list_display``.\n* **admin.E112**: The value of ``list_filter`` must be a list or tuple.\n* **admin.E113**: The value of ``list_filter[n]`` must inherit from\n  ``ListFilter``.\n* **admin.E114**: The value of ``list_filter[n]`` must not inherit from\n  ``FieldListFilter``.\n* **admin.E115**: The value of ``list_filter[n][1]`` must inherit from\n  ``FieldListFilter``.\n* **admin.E116**: The value of ``list_filter[n]`` refers to ``<label>``,\n  which does not refer to a Field.\n* **admin.E117**: The value of ``list_select_related`` must be a boolean,\n  tuple or list.\n* **admin.E118**: The value of ``list_per_page`` must be an integer.\n* **admin.E119**: The value of ``list_max_show_all`` must be an integer.\n* **admin.E120**: The value of ``list_editable`` must be a list or tuple.\n* **admin.E121**: The value of ``list_editable[n]`` refers to ``<label>``,\n  which is not an attribute of ``<model>``.\n* **admin.E122**: The value of ``list_editable[n]`` refers to ``<label>``,\n  which is not contained in ``list_display``.\n* **admin.E123**: The value of ``list_editable[n]`` cannot be in both\n  ``list_editable`` and ``list_display_links``.\n* **admin.E124**: The value of ``list_editable[n]`` refers to the first field\n  in ``list_display`` (``<label>``), which cannot be used unless\n  ``list_display_links`` is set.\n* **admin.E125**: The value of ``list_editable[n]`` refers to ``<field name>``,\n  which is not editable through the admin.\n* **admin.E126**: The value of ``search_fields`` must be a list or tuple.\n* **admin.E127**: The value of ``date_hierarchy`` refers to ``<field name>``,\n  which does not refer to a Field.\n* **admin.E128**: The value of ``date_hierarchy`` must be a ``DateField`` or\n  ``DateTimeField``.\n* **admin.E129**: ``<modeladmin>`` must define a ``has_<foo>_permission()``\n  method for the ``<action>`` action.\n* **admin.E130**: ``__name__`` attributes of actions defined in\n  ``<modeladmin>`` must be unique. Name ``<name>`` is not unique.\n\n``InlineModelAdmin``\n~~~~~~~~~~~~~~~~~~~~\n\nThe following checks are performed on any\n:class:`~django.contrib.admin.InlineModelAdmin` that is registered as an\ninline on a :class:`~django.contrib.admin.ModelAdmin`.\n\n* **admin.E201**: Cannot exclude the field ``<field name>``, because it is the\n  foreign key to the parent model ``<app_label>.<model>``.\n* **admin.E202**: ``<model>`` has no ``ForeignKey`` to ``<parent model>``./\n  ``<model>`` has more than one ``ForeignKey`` to ``<parent model>``. You must\n  specify a ``fk_name`` attribute.\n* **admin.E203**: The value of ``extra`` must be an integer.\n* **admin.E204**: The value of ``max_num`` must be an integer.\n* **admin.E205**: The value of ``min_num`` must be an integer.\n* **admin.E206**: The value of ``formset`` must inherit from\n  ``BaseModelFormSet``.\n\n``GenericInlineModelAdmin``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe following checks are performed on any\n:class:`~django.contrib.contenttypes.admin.GenericInlineModelAdmin` that is\nregistered as an inline on a :class:`~django.contrib.admin.ModelAdmin`.\n\n* **admin.E301**: ``'ct_field'`` references ``<label>``, which is not a field\n  on ``<model>``.\n* **admin.E302**: ``'ct_fk_field'`` references ``<label>``, which is not a\n  field on ``<model>``.\n* **admin.E303**: ``<model>`` has no ``GenericForeignKey``.\n* **admin.E304**: ``<model>`` has no ``GenericForeignKey`` using content type\n  field ``<field name>`` and object ID field ``<field name>``.\n\n``AdminSite``\n~~~~~~~~~~~~~\n\nThe following checks are performed on the default\n:class:`~django.contrib.admin.AdminSite`:\n\n* **admin.E401**: :mod:`django.contrib.contenttypes` must be in\n  :setting:`INSTALLED_APPS` in order to use the admin application.\n* **admin.E402**: :mod:`django.contrib.auth.context_processors.auth`\n  must be enabled in :class:`~django.template.backends.django.DjangoTemplates`\n  (:setting:`TEMPLATES`) if using the default auth backend in order to use the\n  admin application.\n* **admin.E403**: A :class:`django.template.backends.django.DjangoTemplates`\n  instance must be configured in :setting:`TEMPLATES` in order to use the\n  admin application.\n* **admin.E404**: ``django.contrib.messages.context_processors.messages``\n  must be enabled in :class:`~django.template.backends.django.DjangoTemplates`\n  (:setting:`TEMPLATES`) in order to use the admin application.\n* **admin.E405**: :mod:`django.contrib.auth` must be in\n  :setting:`INSTALLED_APPS` in order to use the admin application.\n* **admin.E406**: :mod:`django.contrib.messages` must be in\n  :setting:`INSTALLED_APPS` in order to use the admin application.\n* **admin.E408**:\n  :class:`django.contrib.auth.middleware.AuthenticationMiddleware` must be in\n  :setting:`MIDDLEWARE` in order to use the admin application.\n* **admin.E409**: :class:`django.contrib.messages.middleware.MessageMiddleware`\n  must be in :setting:`MIDDLEWARE` in order to use the admin application.\n* **admin.E410**: :class:`django.contrib.sessions.middleware.SessionMiddleware`\n  must be in :setting:`MIDDLEWARE` in order to use the admin application.\n* **admin.W411**: ``django.template.context_processors.request`` must be\n  enabled in :class:`~django.template.backends.django.DjangoTemplates`\n  (:setting:`TEMPLATES`) in order to use the admin navigation sidebar.\n\n``auth``\n--------\n\n* **auth.E001**: ``REQUIRED_FIELDS`` must be a list or tuple.\n* **auth.E002**: The field named as the ``USERNAME_FIELD`` for a custom user\n  model must not be included in ``REQUIRED_FIELDS``.\n* **auth.E003**: ``<field>`` must be unique because it is named as the\n  ``USERNAME_FIELD``.\n* **auth.W004**: ``<field>`` is named as the ``USERNAME_FIELD``, but it is not\n  unique.\n* **auth.E005**: The permission codenamed ``<codename>`` clashes with a builtin\n  permission for model ``<model>``.\n* **auth.E006**: The permission codenamed ``<codename>`` is duplicated for model\n  ``<model>``.\n* **auth.E007**: The :attr:`verbose_name\n  <django.db.models.Options.verbose_name>` of model ``<model>`` must be at most\n  244 characters for its builtin permission names\n  to be at most 255 characters.\n* **auth.E008**: The permission named ``<name>`` of model ``<model>`` is longer\n  than 255 characters.\n* **auth.C009**: ``<User model>.is_anonymous`` must be an attribute or property\n  rather than a method. Ignoring this is a security issue as anonymous users\n  will be treated as authenticated!\n* **auth.C010**: ``<User model>.is_authenticated`` must be an attribute or\n  property rather than a method. Ignoring this is a security issue as anonymous\n  users will be treated as authenticated!\n* **auth.E011**: The name of model ``<model>`` must be at most 93 characters\n  for its builtin permission names to be at most 100 characters.\n* **auth.E012**: The permission codenamed ``<codename>`` of model ``<model>``\n  is longer than 100 characters.\n\n``contenttypes``\n----------------\n\nThe following checks are performed when a model contains a\n:class:`~django.contrib.contenttypes.fields.GenericForeignKey` or\n:class:`~django.contrib.contenttypes.fields.GenericRelation`:\n\n* **contenttypes.E001**: The ``GenericForeignKey`` object ID references the\n  nonexistent field ``<field>``.\n* **contenttypes.E002**: The ``GenericForeignKey`` content type references the\n  nonexistent field ``<field>``.\n* **contenttypes.E003**: ``<field>`` is not a ``ForeignKey``.\n* **contenttypes.E004**: ``<field>`` is not a ``ForeignKey`` to\n  ``contenttypes.ContentType``.\n* **contenttypes.E005**: Model names must be at most 100 characters.\n\n``postgres``\n------------\n\nThe following checks are performed on :mod:`django.contrib.postgres` model\nfields:\n\n* **postgres.E001**: Base field for array has errors: ...\n* **postgres.E002**: Base field for array cannot be a related field.\n* **postgres.E003**: ``<field>`` default should be a callable instead of an\n  instance so that it's not shared between all field instances. *This check was\n  changed to* ``fields.E010`` *in Django 3.1*.\n\n``sites``\n---------\n\nThe following checks are performed on any model using a\n:class:`~django.contrib.sites.managers.CurrentSiteManager`:\n\n* **sites.E001**: ``CurrentSiteManager`` could not find a field named\n  ``<field name>``.\n* **sites.E002**: ``CurrentSiteManager`` cannot use ``<field>`` as it is not a\n  foreign key or a many-to-many field.\n\n``staticfiles``\n---------------\n\nThe following checks verify that :mod:`django.contrib.staticfiles` is correctly\nconfigured:\n\n* **staticfiles.E001**: The :setting:`STATICFILES_DIRS` setting is not a tuple\n  or list.\n* **staticfiles.E002**: The :setting:`STATICFILES_DIRS` setting should not\n  contain the :setting:`STATIC_ROOT` setting.\n* **staticfiles.E003**: The prefix ``<prefix>`` in the\n  :setting:`STATICFILES_DIRS` setting must not end with a slash.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":34,"nodeType":"TextFile","repoName":null,"name":"django-admin.1","path":"docs/man","text":".\\\" Man page generated from reStructuredText.\n.\n.TH \"DJANGO-ADMIN\" \"1\" \"May 12, 2020\" \"3.1\" \"Django\"\n.SH NAME\ndjango-admin \\- Utility script for the Django Web framework\n.\n.nr rst2man-indent-level 0\n.\n.de1 rstReportMargin\n\\\\$1 \\\\n[an-margin]\nlevel \\\\n[rst2man-indent-level]\nlevel margin: \\\\n[rst2man-indent\\\\n[rst2man-indent-level]]\n-\n\\\\n[rst2man-indent0]\n\\\\n[rst2man-indent1]\n\\\\n[rst2man-indent2]\n..\n.de1 INDENT\n.\\\" .rstReportMargin pre:\n. RS \\\\$1\n. nr rst2man-indent\\\\n[rst2man-indent-level] \\\\n[an-margin]\n. nr rst2man-indent-level +1\n.\\\" .rstReportMargin post:\n..\n.de UNINDENT\n. RE\n.\\\" indent \\\\n[an-margin]\n.\\\" old: \\\\n[rst2man-indent\\\\n[rst2man-indent-level]]\n.nr rst2man-indent-level -1\n.\\\" new: \\\\n[rst2man-indent\\\\n[rst2man-indent-level]]\n.in \\\\n[rst2man-indent\\\\n[rst2man-indent-level]]u\n..\n.sp\n\\fBdjango\\-admin\\fP is Django\\(aqs command\\-line utility for administrative tasks.\nThis document outlines all it can do.\n.sp\nIn addition, \\fBmanage.py\\fP is automatically created in each Django project. It\ndoes the same thing as \\fBdjango\\-admin\\fP but also sets the\n\\fBDJANGO_SETTINGS_MODULE\\fP environment variable so that it points to your\nproject\\(aqs \\fBsettings.py\\fP file.\n.sp\nThe \\fBdjango\\-admin\\fP script should be on your system path if you installed\nDjango via \\fBpip\\fP\\&. If it\\(aqs not in your path, ensure you have your virtual\nenvironment activated.\n.sp\nGenerally, when working on a single Django project, it\\(aqs easier to use\n\\fBmanage.py\\fP than \\fBdjango\\-admin\\fP\\&. If you need to switch between multiple\nDjango settings files, use \\fBdjango\\-admin\\fP with\n\\fBDJANGO_SETTINGS_MODULE\\fP or the \\fI\\%\\-\\-settings\\fP command line\noption.\n.sp\nThe command\\-line examples throughout this document use \\fBdjango\\-admin\\fP to\nbe consistent, but any example can use \\fBmanage.py\\fP or \\fBpython \\-m django\\fP\njust as well.\n.SH USAGE\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\n$ django\\-admin <command> [options]\n$ manage.py <command> [options]\n$ python \\-m django <command> [options]\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\n\\fBcommand\\fP should be one of the commands listed in this document.\n\\fBoptions\\fP, which is optional, should be zero or more of the options available\nfor the given command.\n.SS Getting runtime help\n.INDENT 0.0\n.TP\n.B django\\-admin help\n.UNINDENT\n.sp\nRun \\fBdjango\\-admin help\\fP to display usage information and a list of the\ncommands provided by each application.\n.sp\nRun \\fBdjango\\-admin help \\-\\-commands\\fP to display a list of all available\ncommands.\n.sp\nRun \\fBdjango\\-admin help <command>\\fP to display a description of the given\ncommand and a list of its available options.\n.SS App names\n.sp\nMany commands take a list of \"app names.\" An \"app name\" is the basename of\nthe package containing your models. For example, if your \\fBINSTALLED_APPS\\fP\ncontains the string \\fB\\(aqmysite.blog\\(aq\\fP, the app name is \\fBblog\\fP\\&.\n.SS Determining the version\n.INDENT 0.0\n.TP\n.B django\\-admin version\n.UNINDENT\n.sp\nRun \\fBdjango\\-admin version\\fP to display the current Django version.\n.sp\nThe output follows the schema described in \\fI\\%PEP 440\\fP:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\n1.4.dev17026\n1.4a1\n1.4\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.SS Displaying debug output\n.sp\nUse \\fI\\%\\-\\-verbosity\\fP to specify the amount of notification and debug\ninformation that \\fBdjango\\-admin\\fP prints to the console.\n.SH AVAILABLE COMMANDS\n.SS \\fBcheck\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin check [app_label [app_label ...]]\n.UNINDENT\n.sp\nUses the system check framework to inspect the entire\nDjango project for common problems.\n.sp\nBy default, all apps will be checked. You can check a subset of apps by\nproviding a list of app labels as arguments:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin check auth admin myapp\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nIf you do not specify any app, all apps will be checked.\n.INDENT 0.0\n.TP\n.B \\-\\-tag TAGS, \\-t TAGS\n.UNINDENT\n.sp\nThe system check framework performs many different types of checks that are\ncategorized with tags\\&. You can use these\ntags to restrict the checks performed to just those in a particular category.\nFor example, to perform only models and compatibility checks, run:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin check \\-\\-tag models \\-\\-tag compatibility\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.INDENT 0.0\n.TP\n.B \\-\\-database DATABASE\n.UNINDENT\n.sp\n\n.sp\nSpecifies the database to run checks requiring database access:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin check \\-\\-database default \\-\\-database other\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nBy default, these checks will not be run.\n.INDENT 0.0\n.TP\n.B \\-\\-list\\-tags\n.UNINDENT\n.sp\nLists all available tags.\n.INDENT 0.0\n.TP\n.B \\-\\-deploy\n.UNINDENT\n.sp\nActivates some additional checks that are only relevant in a deployment setting.\n.sp\nYou can use this option in your local development environment, but since your\nlocal development settings module may not have many of your production settings,\nyou will probably want to point the \\fBcheck\\fP command at a different settings\nmodule, either by setting the \\fBDJANGO_SETTINGS_MODULE\\fP environment variable,\nor by passing the \\fB\\-\\-settings\\fP option:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin check \\-\\-deploy \\-\\-settings=production_settings\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nOr you could run it directly on a production or staging deployment to verify\nthat the correct settings are in use (omitting \\fB\\-\\-settings\\fP). You could even\nmake it part of your integration test suite.\n.INDENT 0.0\n.TP\n.B \\-\\-fail\\-level {CRITICAL,ERROR,WARNING,INFO,DEBUG}\n.UNINDENT\n.sp\nSpecifies the message level that will cause the command to exit with a non\\-zero\nstatus. Default is \\fBERROR\\fP\\&.\n.SS \\fBcompilemessages\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin compilemessages\n.UNINDENT\n.sp\nCompiles \\fB\\&.po\\fP files created by \\fI\\%makemessages\\fP to \\fB\\&.mo\\fP files for\nuse with the built\\-in gettext support. See /topics/i18n/index\\&.\n.INDENT 0.0\n.TP\n.B \\-\\-locale LOCALE, \\-l LOCALE\n.UNINDENT\n.sp\nSpecifies the locale(s) to process. If not provided, all locales are processed.\n.INDENT 0.0\n.TP\n.B \\-\\-exclude EXCLUDE, \\-x EXCLUDE\n.UNINDENT\n.sp\nSpecifies the locale(s) to exclude from processing. If not provided, no locales\nare excluded.\n.INDENT 0.0\n.TP\n.B \\-\\-use\\-fuzzy, \\-f\n.UNINDENT\n.sp\nIncludes fuzzy translations into compiled files.\n.sp\nExample usage:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin compilemessages \\-\\-locale=pt_BR\ndjango\\-admin compilemessages \\-\\-locale=pt_BR \\-\\-locale=fr \\-f\ndjango\\-admin compilemessages \\-l pt_BR\ndjango\\-admin compilemessages \\-l pt_BR \\-l fr \\-\\-use\\-fuzzy\ndjango\\-admin compilemessages \\-\\-exclude=pt_BR\ndjango\\-admin compilemessages \\-\\-exclude=pt_BR \\-\\-exclude=fr\ndjango\\-admin compilemessages \\-x pt_BR\ndjango\\-admin compilemessages \\-x pt_BR \\-x fr\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.INDENT 0.0\n.TP\n.B \\-\\-ignore PATTERN, \\-i PATTERN\n.UNINDENT\n.sp\n\n.sp\nIgnores directories matching the given \\fI\\%glob\\fP\\-style pattern. Use\nmultiple times to ignore more.\n.sp\nExample usage:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin compilemessages \\-\\-ignore=cache \\-\\-ignore=outdated/*/locale\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.SS \\fBcreatecachetable\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin createcachetable\n.UNINDENT\n.sp\nCreates the cache tables for use with the database cache backend using the\ninformation from your settings file. See /topics/cache for more\ninformation.\n.INDENT 0.0\n.TP\n.B \\-\\-database DATABASE\n.UNINDENT\n.sp\nSpecifies the database in which the cache table(s) will be created. Defaults to\n\\fBdefault\\fP\\&.\n.INDENT 0.0\n.TP\n.B \\-\\-dry\\-run\n.UNINDENT\n.sp\nPrints the SQL that would be run without actually running it, so you can\ncustomize it or use the migrations framework.\n.SS \\fBdbshell\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin dbshell\n.UNINDENT\n.sp\nRuns the command\\-line client for the database engine specified in your\n\\fBENGINE\\fP setting, with the connection parameters\nspecified in your \\fBUSER\\fP, \\fBPASSWORD\\fP, etc., settings.\n.INDENT 0.0\n.IP \\(bu 2\nFor PostgreSQL, this runs the \\fBpsql\\fP command\\-line client.\n.IP \\(bu 2\nFor MySQL, this runs the \\fBmysql\\fP command\\-line client.\n.IP \\(bu 2\nFor SQLite, this runs the \\fBsqlite3\\fP command\\-line client.\n.IP \\(bu 2\nFor Oracle, this runs the \\fBsqlplus\\fP command\\-line client.\n.UNINDENT\n.sp\nThis command assumes the programs are on your \\fBPATH\\fP so that a call to\nthe program name (\\fBpsql\\fP, \\fBmysql\\fP, \\fBsqlite3\\fP, \\fBsqlplus\\fP) will find the\nprogram in the right place. There\\(aqs no way to specify the location of the\nprogram manually.\n.INDENT 0.0\n.TP\n.B \\-\\-database DATABASE\n.UNINDENT\n.sp\nSpecifies the database onto which to open a shell. Defaults to \\fBdefault\\fP\\&.\n.INDENT 0.0\n.TP\n.B \\-\\- ARGUMENTS\n.UNINDENT\n.sp\n\n.sp\nAny arguments following a \\fB\\-\\-\\fP divider will be passed on to the underlying\ncommand\\-line client. For example, with PostgreSQL you can use the \\fBpsql\\fP\ncommand\\(aqs \\fB\\-c\\fP flag to execute a raw SQL query directly:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\n$ django\\-admin dbshell \\-\\- \\-c \\(aqselect current_user\\(aq\n current_user\n\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\n postgres\n(1 row)\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nOn MySQL/MariaDB, you can do this with the \\fBmysql\\fP command\\(aqs \\fB\\-e\\fP flag:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\n$ django\\-admin dbshell \\-\\- \\-e \"select user()\"\n+\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-+\n| user()               |\n+\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-+\n| djangonaut@localhost |\n+\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-\\-+\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\n\\fBNOTE:\\fP\n.INDENT 0.0\n.INDENT 3.5\nBe aware that not all options set in the \\fBOPTIONS\\fP part of your\ndatabase configuration in \\fBDATABASES\\fP are passed to the\ncommand\\-line client, e.g. \\fB\\(aqisolation_level\\(aq\\fP\\&.\n.UNINDENT\n.UNINDENT\n.SS \\fBdiffsettings\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin diffsettings\n.UNINDENT\n.sp\nDisplays differences between the current settings file and Django\\(aqs default\nsettings (or another settings file specified by \\fI\\%\\-\\-default\\fP).\n.sp\nSettings that don\\(aqt appear in the defaults are followed by \\fB\"###\"\\fP\\&. For\nexample, the default settings don\\(aqt define \\fBROOT_URLCONF\\fP, so\n\\fBROOT_URLCONF\\fP is followed by \\fB\"###\"\\fP in the output of\n\\fBdiffsettings\\fP\\&.\n.INDENT 0.0\n.TP\n.B \\-\\-all\n.UNINDENT\n.sp\nDisplays all settings, even if they have Django\\(aqs default value. Such settings\nare prefixed by \\fB\"###\"\\fP\\&.\n.INDENT 0.0\n.TP\n.B \\-\\-default MODULE\n.UNINDENT\n.sp\nThe settings module to compare the current settings against. Leave empty to\ncompare against Django\\(aqs default settings.\n.INDENT 0.0\n.TP\n.B \\-\\-output {hash,unified}\n.UNINDENT\n.sp\nSpecifies the output format. Available values are \\fBhash\\fP and \\fBunified\\fP\\&.\n\\fBhash\\fP is the default mode that displays the output that\\(aqs described above.\n\\fBunified\\fP displays the output similar to \\fBdiff \\-u\\fP\\&. Default settings are\nprefixed with a minus sign, followed by the changed setting prefixed with a\nplus sign.\n.SS \\fBdumpdata\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin dumpdata [app_label[.ModelName] [app_label[.ModelName] ...]]\n.UNINDENT\n.sp\nOutputs to standard output all data in the database associated with the named\napplication(s).\n.sp\nIf no application name is provided, all installed applications will be dumped.\n.sp\nThe output of \\fBdumpdata\\fP can be used as input for \\fI\\%loaddata\\fP\\&.\n.sp\nNote that \\fBdumpdata\\fP uses the default manager on the model for selecting the\nrecords to dump. If you\\(aqre using a custom manager as\nthe default manager and it filters some of the available records, not all of the\nobjects will be dumped.\n.INDENT 0.0\n.TP\n.B \\-\\-all, \\-a\n.UNINDENT\n.sp\nUses Django\\(aqs base manager, dumping records which might otherwise be filtered\nor modified by a custom manager.\n.INDENT 0.0\n.TP\n.B \\-\\-format FORMAT\n.UNINDENT\n.sp\nSpecifies the serialization format of the output. Defaults to JSON. Supported\nformats are listed in serialization\\-formats\\&.\n.INDENT 0.0\n.TP\n.B \\-\\-indent INDENT\n.UNINDENT\n.sp\nSpecifies the number of indentation spaces to use in the output. Defaults to\n\\fBNone\\fP which displays all data on single line.\n.INDENT 0.0\n.TP\n.B \\-\\-exclude EXCLUDE, \\-e EXCLUDE\n.UNINDENT\n.sp\nPrevents specific applications or models (specified in the form of\n\\fBapp_label.ModelName\\fP) from being dumped. If you specify a model name, the\noutput will be restricted to that model, rather than the entire application.\nYou can also mix application names and model names.\n.sp\nIf you want to exclude multiple applications, pass \\fB\\-\\-exclude\\fP more than\nonce:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin dumpdata \\-\\-exclude=auth \\-\\-exclude=contenttypes\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.INDENT 0.0\n.TP\n.B \\-\\-database DATABASE\n.UNINDENT\n.sp\nSpecifies the database from which data will be dumped. Defaults to \\fBdefault\\fP\\&.\n.INDENT 0.0\n.TP\n.B \\-\\-natural\\-foreign\n.UNINDENT\n.sp\nUses the \\fBnatural_key()\\fP model method to serialize any foreign key and\nmany\\-to\\-many relationship to objects of the type that defines the method. If\nyou\\(aqre dumping \\fBcontrib.auth\\fP \\fBPermission\\fP objects or\n\\fBcontrib.contenttypes\\fP \\fBContentType\\fP objects, you should probably use this\nflag. See the natural keys\ndocumentation for more details on this and the next option.\n.INDENT 0.0\n.TP\n.B \\-\\-natural\\-primary\n.UNINDENT\n.sp\nOmits the primary key in the serialized data of this object since it can be\ncalculated during deserialization.\n.INDENT 0.0\n.TP\n.B \\-\\-pks PRIMARY_KEYS\n.UNINDENT\n.sp\nOutputs only the objects specified by a comma separated list of primary keys.\nThis is only available when dumping one model. By default, all the records of\nthe model are output.\n.INDENT 0.0\n.TP\n.B \\-\\-output OUTPUT, \\-o OUTPUT\n.UNINDENT\n.sp\nSpecifies a file to write the serialized data to. By default, the data goes to\nstandard output.\n.sp\nWhen this option is set and \\fB\\-\\-verbosity\\fP is greater than 0 (the default), a\nprogress bar is shown in the terminal.\n.SS \\fBflush\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin flush\n.UNINDENT\n.sp\nRemoves all data from the database and re\\-executes any post\\-synchronization\nhandlers. The table of which migrations have been applied is not cleared.\n.sp\nIf you would rather start from an empty database and re\\-run all migrations, you\nshould drop and recreate the database and then run \\fI\\%migrate\\fP instead.\n.INDENT 0.0\n.TP\n.B \\-\\-noinput, \\-\\-no\\-input\n.UNINDENT\n.sp\nSuppresses all user prompts.\n.INDENT 0.0\n.TP\n.B \\-\\-database DATABASE\n.UNINDENT\n.sp\nSpecifies the database to flush. Defaults to \\fBdefault\\fP\\&.\n.SS \\fBinspectdb\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin inspectdb [table [table ...]]\n.UNINDENT\n.sp\nIntrospects the database tables in the database pointed\\-to by the\n\\fBNAME\\fP setting and outputs a Django model module (a \\fBmodels.py\\fP\nfile) to standard output.\n.sp\nYou may choose what tables or views to inspect by passing their names as\narguments. If no arguments are provided, models are created for views only if\nthe \\fI\\%\\-\\-include\\-views\\fP option is used. Models for partition tables are\ncreated on PostgreSQL if the \\fI\\%\\-\\-include\\-partitions\\fP option is used.\n.sp\nUse this if you have a legacy database with which you\\(aqd like to use Django.\nThe script will inspect the database and create a model for each table within\nit.\n.sp\nAs you might expect, the created models will have an attribute for every field\nin the table. Note that \\fBinspectdb\\fP has a few special cases in its field\\-name\noutput:\n.INDENT 0.0\n.IP \\(bu 2\nIf \\fBinspectdb\\fP cannot map a column\\(aqs type to a model field type, it\\(aqll\nuse \\fBTextField\\fP and will insert the Python comment\n\\fB\\(aqThis field type is a guess.\\(aq\\fP next to the field in the generated\nmodel. The recognized fields may depend on apps listed in\n\\fBINSTALLED_APPS\\fP\\&. For example, \\fBdjango.contrib.postgres\\fP adds\nrecognition for several PostgreSQL\\-specific field types.\n.IP \\(bu 2\nIf the database column name is a Python reserved word (such as\n\\fB\\(aqpass\\(aq\\fP, \\fB\\(aqclass\\(aq\\fP or \\fB\\(aqfor\\(aq\\fP), \\fBinspectdb\\fP will append\n\\fB\\(aq_field\\(aq\\fP to the attribute name. For example, if a table has a column\n\\fB\\(aqfor\\(aq\\fP, the generated model will have a field \\fB\\(aqfor_field\\(aq\\fP, with\nthe \\fBdb_column\\fP attribute set to \\fB\\(aqfor\\(aq\\fP\\&. \\fBinspectdb\\fP will insert\nthe Python comment\n\\fB\\(aqField renamed because it was a Python reserved word.\\(aq\\fP next to the\nfield.\n.UNINDENT\n.sp\nThis feature is meant as a shortcut, not as definitive model generation. After\nyou run it, you\\(aqll want to look over the generated models yourself to make\ncustomizations. In particular, you\\(aqll need to rearrange models\\(aq order, so that\nmodels that refer to other models are ordered properly.\n.sp\nDjango doesn\\(aqt create database defaults when a\n\\fBdefault\\fP is specified on a model field.\nSimilarly, database defaults aren\\(aqt translated to model field defaults or\ndetected in any fashion by \\fBinspectdb\\fP\\&.\n.sp\nBy default, \\fBinspectdb\\fP creates unmanaged models. That is, \\fBmanaged = False\\fP\nin the model\\(aqs \\fBMeta\\fP class tells Django not to manage each table\\(aqs creation,\nmodification, and deletion. If you do want to allow Django to manage the\ntable\\(aqs lifecycle, you\\(aqll need to change the\n\\fBmanaged\\fP option to \\fBTrue\\fP (or remove\nit because \\fBTrue\\fP is its default value).\n.SS Database\\-specific notes\n.SS Oracle\n.INDENT 0.0\n.IP \\(bu 2\nModels are created for materialized views if \\fI\\%\\-\\-include\\-views\\fP is\nused.\n.UNINDENT\n.SS PostgreSQL\n.INDENT 0.0\n.IP \\(bu 2\nModels are created for foreign tables.\n.IP \\(bu 2\nModels are created for materialized views if\n\\fI\\%\\-\\-include\\-views\\fP is used.\n.IP \\(bu 2\nModels are created for partition tables if\n\\fI\\%\\-\\-include\\-partitions\\fP is used.\n.UNINDENT\n.INDENT 0.0\n.TP\n.B \\-\\-database DATABASE\n.UNINDENT\n.sp\nSpecifies the database to introspect. Defaults to \\fBdefault\\fP\\&.\n.INDENT 0.0\n.TP\n.B \\-\\-include\\-partitions\n.UNINDENT\n.sp\nIf this option is provided, models are also created for partitions.\n.sp\nOnly support for PostgreSQL is implemented.\n.INDENT 0.0\n.TP\n.B \\-\\-include\\-views\n.UNINDENT\n.sp\nIf this option is provided, models are also created for database views.\n.SS \\fBloaddata\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin loaddata fixture [fixture ...]\n.UNINDENT\n.sp\nSearches for and loads the contents of the named fixture into the database.\n.INDENT 0.0\n.TP\n.B \\-\\-database DATABASE\n.UNINDENT\n.sp\nSpecifies the database into which the data will be loaded. Defaults to\n\\fBdefault\\fP\\&.\n.INDENT 0.0\n.TP\n.B \\-\\-ignorenonexistent, \\-i\n.UNINDENT\n.sp\nIgnores fields and models that may have been removed since the fixture was\noriginally generated.\n.INDENT 0.0\n.TP\n.B \\-\\-app APP_LABEL\n.UNINDENT\n.sp\nSpecifies a single app to look for fixtures in rather than looking in all apps.\n.INDENT 0.0\n.TP\n.B \\-\\-format FORMAT\n.UNINDENT\n.sp\nSpecifies the serialization format (e.g.,\n\\fBjson\\fP or \\fBxml\\fP) for fixtures \\fI\\%read from stdin\\fP\\&.\n.INDENT 0.0\n.TP\n.B \\-\\-exclude EXCLUDE, \\-e EXCLUDE\n.UNINDENT\n.sp\nExcludes loading the fixtures from the given applications and/or models (in the\nform of \\fBapp_label\\fP or \\fBapp_label.ModelName\\fP). Use the option multiple\ntimes to exclude more than one app or model.\n.SS What\\(aqs a \"fixture\"?\n.sp\nA \\fIfixture\\fP is a collection of files that contain the serialized contents of\nthe database. Each fixture has a unique name, and the files that comprise the\nfixture can be distributed over multiple directories, in multiple applications.\n.sp\nDjango will search in three locations for fixtures:\n.INDENT 0.0\n.IP 1. 3\nIn the \\fBfixtures\\fP directory of every installed application\n.IP 2. 3\nIn any directory named in the \\fBFIXTURE_DIRS\\fP setting\n.IP 3. 3\nIn the literal path named by the fixture\n.UNINDENT\n.sp\nDjango will load any and all fixtures it finds in these locations that match\nthe provided fixture names.\n.sp\nIf the named fixture has a file extension, only fixtures of that type\nwill be loaded. For example:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin loaddata mydata.json\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nwould only load JSON fixtures called \\fBmydata\\fP\\&. The fixture extension\nmust correspond to the registered name of a\nserializer (e.g., \\fBjson\\fP or \\fBxml\\fP).\n.sp\nIf you omit the extensions, Django will search all available fixture types\nfor a matching fixture. For example:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin loaddata mydata\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nwould look for any fixture of any fixture type called \\fBmydata\\fP\\&. If a fixture\ndirectory contained \\fBmydata.json\\fP, that fixture would be loaded\nas a JSON fixture.\n.sp\nThe fixtures that are named can include directory components. These\ndirectories will be included in the search path. For example:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin loaddata foo/bar/mydata.json\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nwould search \\fB<app_label>/fixtures/foo/bar/mydata.json\\fP for each installed\napplication,  \\fB<dirname>/foo/bar/mydata.json\\fP for each directory in\n\\fBFIXTURE_DIRS\\fP, and the literal path \\fBfoo/bar/mydata.json\\fP\\&.\n.sp\nWhen fixture files are processed, the data is saved to the database as is.\nModel defined \\fBsave()\\fP methods are not called, and\nany \\fBpre_save\\fP or\n\\fBpost_save\\fP signals will be called with\n\\fBraw=True\\fP since the instance only contains attributes that are local to the\nmodel. You may, for example, want to disable handlers that access\nrelated fields that aren\\(aqt present during fixture loading and would otherwise\nraise an exception:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\nfrom django.db.models.signals import post_save\nfrom .models import MyModel\n\ndef my_handler(**kwargs):\n    # disable the handler during fixture loading\n    if kwargs[\\(aqraw\\(aq]:\n        return\n    ...\n\npost_save.connect(my_handler, sender=MyModel)\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nYou could also write a decorator to encapsulate this logic:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\nfrom functools import wraps\n\ndef disable_for_loaddata(signal_handler):\n    \"\"\"\n    Decorator that turns off signal handlers when loading fixture data.\n    \"\"\"\n    @wraps(signal_handler)\n    def wrapper(*args, **kwargs):\n        if kwargs[\\(aqraw\\(aq]:\n            return\n        signal_handler(*args, **kwargs)\n    return wrapper\n\n@disable_for_loaddata\ndef my_handler(**kwargs):\n    ...\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nJust be aware that this logic will disable the signals whenever fixtures are\ndeserialized, not just during \\fBloaddata\\fP\\&.\n.sp\nNote that the order in which fixture files are processed is undefined. However,\nall fixture data is installed as a single transaction, so data in\none fixture can reference data in another fixture. If the database backend\nsupports row\\-level constraints, these constraints will be checked at the\nend of the transaction.\n.sp\nThe \\fI\\%dumpdata\\fP command can be used to generate input for \\fBloaddata\\fP\\&.\n.SS Compressed fixtures\n.sp\nFixtures may be compressed in \\fBzip\\fP, \\fBgz\\fP, or \\fBbz2\\fP format. For example:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin loaddata mydata.json\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nwould look for any of \\fBmydata.json\\fP, \\fBmydata.json.zip\\fP,\n\\fBmydata.json.gz\\fP, or \\fBmydata.json.bz2\\fP\\&. The first file contained within a\nzip\\-compressed archive is used.\n.sp\nNote that if two fixtures with the same name but different\nfixture type are discovered (for example, if \\fBmydata.json\\fP and\n\\fBmydata.xml.gz\\fP were found in the same fixture directory), fixture\ninstallation will be aborted, and any data installed in the call to\n\\fBloaddata\\fP will be removed from the database.\n.INDENT 0.0\n.INDENT 3.5\n.IP \"MySQL with MyISAM and fixtures\"\n.sp\nThe MyISAM storage engine of MySQL doesn\\(aqt support transactions or\nconstraints, so if you use MyISAM, you won\\(aqt get validation of fixture\ndata, or a rollback if multiple transaction files are found.\n.UNINDENT\n.UNINDENT\n.SS Database\\-specific fixtures\n.sp\nIf you\\(aqre in a multi\\-database setup, you might have fixture data that\nyou want to load onto one database, but not onto another. In this\nsituation, you can add a database identifier into the names of your fixtures.\n.sp\nFor example, if your \\fBDATABASES\\fP setting has a \\(aqmaster\\(aq database\ndefined, name the fixture \\fBmydata.master.json\\fP or\n\\fBmydata.master.json.gz\\fP and the fixture will only be loaded when you\nspecify you want to load data into the \\fBmaster\\fP database.\n.SS Loading fixtures from \\fBstdin\\fP\n.sp\nYou can use a dash as the fixture name to load input from \\fBsys.stdin\\fP\\&. For\nexample:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin loaddata \\-\\-format=json \\-\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nWhen reading from \\fBstdin\\fP, the \\fI\\%\\-\\-format\\fP option\nis required to specify the serialization format\nof the input (e.g., \\fBjson\\fP or \\fBxml\\fP).\n.sp\nLoading from \\fBstdin\\fP is useful with standard input and output redirections.\nFor example:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin dumpdata \\-\\-format=json \\-\\-database=test app_label.ModelName | django\\-admin loaddata \\-\\-format=json \\-\\-database=prod \\-\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.SS \\fBmakemessages\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin makemessages\n.UNINDENT\n.sp\nRuns over the entire source tree of the current directory and pulls out all\nstrings marked for translation. It creates (or updates) a message file in the\nconf/locale (in the Django tree) or locale (for project and application)\ndirectory. After making changes to the messages files you need to compile them\nwith \\fI\\%compilemessages\\fP for use with the builtin gettext support. See\nthe i18n documentation for details.\n.sp\nThis command doesn\\(aqt require configured settings. However, when settings aren\\(aqt\nconfigured, the command can\\(aqt ignore the \\fBMEDIA_ROOT\\fP and\n\\fBSTATIC_ROOT\\fP directories or include \\fBLOCALE_PATHS\\fP\\&.\n.INDENT 0.0\n.TP\n.B \\-\\-all, \\-a\n.UNINDENT\n.sp\nUpdates the message files for all available languages.\n.INDENT 0.0\n.TP\n.B \\-\\-extension EXTENSIONS, \\-e EXTENSIONS\n.UNINDENT\n.sp\nSpecifies a list of file extensions to examine (default: \\fBhtml\\fP, \\fBtxt\\fP,\n\\fBpy\\fP or \\fBjs\\fP if \\fI\\%\\-\\-domain\\fP is \\fBjs\\fP).\n.sp\nExample usage:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin makemessages \\-\\-locale=de \\-\\-extension xhtml\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nSeparate multiple extensions with commas or use \\fB\\-e\\fP or \\fB\\-\\-extension\\fP\nmultiple times:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin makemessages \\-\\-locale=de \\-\\-extension=html,txt \\-\\-extension xml\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.INDENT 0.0\n.TP\n.B \\-\\-locale LOCALE, \\-l LOCALE\n.UNINDENT\n.sp\nSpecifies the locale(s) to process.\n.INDENT 0.0\n.TP\n.B \\-\\-exclude EXCLUDE, \\-x EXCLUDE\n.UNINDENT\n.sp\nSpecifies the locale(s) to exclude from processing. If not provided, no locales\nare excluded.\n.sp\nExample usage:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin makemessages \\-\\-locale=pt_BR\ndjango\\-admin makemessages \\-\\-locale=pt_BR \\-\\-locale=fr\ndjango\\-admin makemessages \\-l pt_BR\ndjango\\-admin makemessages \\-l pt_BR \\-l fr\ndjango\\-admin makemessages \\-\\-exclude=pt_BR\ndjango\\-admin makemessages \\-\\-exclude=pt_BR \\-\\-exclude=fr\ndjango\\-admin makemessages \\-x pt_BR\ndjango\\-admin makemessages \\-x pt_BR \\-x fr\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.INDENT 0.0\n.TP\n.B \\-\\-domain DOMAIN, \\-d DOMAIN\n.UNINDENT\n.sp\nSpecifies the domain of the messages files. Supported options are:\n.INDENT 0.0\n.IP \\(bu 2\n\\fBdjango\\fP for all \\fB*.py\\fP, \\fB*.html\\fP and \\fB*.txt\\fP files (default)\n.IP \\(bu 2\n\\fBdjangojs\\fP for \\fB*.js\\fP files\n.UNINDENT\n.INDENT 0.0\n.TP\n.B \\-\\-symlinks, \\-s\n.UNINDENT\n.sp\nFollows symlinks to directories when looking for new translation strings.\n.sp\nExample usage:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin makemessages \\-\\-locale=de \\-\\-symlinks\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.INDENT 0.0\n.TP\n.B \\-\\-ignore PATTERN, \\-i PATTERN\n.UNINDENT\n.sp\nIgnores files or directories matching the given \\fI\\%glob\\fP\\-style pattern. Use\nmultiple times to ignore more.\n.sp\nThese patterns are used by default: \\fB\\(aqCVS\\(aq\\fP, \\fB\\(aq.*\\(aq\\fP, \\fB\\(aq*~\\(aq\\fP, \\fB\\(aq*.pyc\\(aq\\fP\\&.\n.sp\nExample usage:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin makemessages \\-\\-locale=en_US \\-\\-ignore=apps/* \\-\\-ignore=secret/*.html\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.INDENT 0.0\n.TP\n.B \\-\\-no\\-default\\-ignore\n.UNINDENT\n.sp\nDisables the default values of \\fB\\-\\-ignore\\fP\\&.\n.INDENT 0.0\n.TP\n.B \\-\\-no\\-wrap\n.UNINDENT\n.sp\nDisables breaking long message lines into several lines in language files.\n.INDENT 0.0\n.TP\n.B \\-\\-no\\-location\n.UNINDENT\n.sp\nSuppresses writing \\(aq\\fB#: filename:line\\fP’ comment lines in language files.\nUsing this option makes it harder for technically skilled translators to\nunderstand each message\\(aqs context.\n.INDENT 0.0\n.TP\n.B \\-\\-add\\-location [{full,file,never}]\n.UNINDENT\n.sp\nControls \\fB#: filename:line\\fP comment lines in language files. If the option\nis:\n.INDENT 0.0\n.IP \\(bu 2\n\\fBfull\\fP (the default if not given): the lines include both file name and\nline number.\n.IP \\(bu 2\n\\fBfile\\fP: the line number is omitted.\n.IP \\(bu 2\n\\fBnever\\fP: the lines are suppressed (same as \\fI\\%\\-\\-no\\-location\\fP).\n.UNINDENT\n.sp\nRequires \\fBgettext\\fP 0.19 or newer.\n.INDENT 0.0\n.TP\n.B \\-\\-keep\\-pot\n.UNINDENT\n.sp\nPrevents deleting the temporary \\fB\\&.pot\\fP files generated before creating the\n\\fB\\&.po\\fP file. This is useful for debugging errors which may prevent the final\nlanguage files from being created.\n.sp\n\\fBSEE ALSO:\\fP\n.INDENT 0.0\n.INDENT 3.5\nSee customizing\\-makemessages for instructions on how to customize\nthe keywords that \\fI\\%makemessages\\fP passes to \\fBxgettext\\fP\\&.\n.UNINDENT\n.UNINDENT\n.SS \\fBmakemigrations\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin makemigrations [app_label [app_label ...]]\n.UNINDENT\n.sp\nCreates new migrations based on the changes detected to your models.\nMigrations, their relationship with apps and more are covered in depth in\nthe migrations documentation\\&.\n.sp\nProviding one or more app names as arguments will limit the migrations created\nto the app(s) specified and any dependencies needed (the table at the other end\nof a \\fBForeignKey\\fP, for example).\n.sp\nTo add migrations to an app that doesn\\(aqt have a \\fBmigrations\\fP directory, run\n\\fBmakemigrations\\fP with the app\\(aqs \\fBapp_label\\fP\\&.\n.INDENT 0.0\n.TP\n.B \\-\\-noinput, \\-\\-no\\-input\n.UNINDENT\n.sp\nSuppresses all user prompts. If a suppressed prompt cannot be resolved\nautomatically, the command will exit with error code 3.\n.INDENT 0.0\n.TP\n.B \\-\\-empty\n.UNINDENT\n.sp\nOutputs an empty migration for the specified apps, for manual editing. This is\nfor advanced users and should not be used unless you are familiar with the\nmigration format, migration operations, and the dependencies between your\nmigrations.\n.INDENT 0.0\n.TP\n.B \\-\\-dry\\-run\n.UNINDENT\n.sp\nShows what migrations would be made without actually writing any migrations\nfiles to disk. Using this option along with \\fB\\-\\-verbosity 3\\fP will also show\nthe complete migrations files that would be written.\n.INDENT 0.0\n.TP\n.B \\-\\-merge\n.UNINDENT\n.sp\nEnables fixing of migration conflicts.\n.INDENT 0.0\n.TP\n.B \\-\\-name NAME, \\-n NAME\n.UNINDENT\n.sp\nAllows naming the generated migration(s) instead of using a generated name. The\nname must be a valid Python \\fI\\%identifier\\fP\\&.\n.INDENT 0.0\n.TP\n.B \\-\\-no\\-header\n.UNINDENT\n.sp\nGenerate migration files without Django version and timestamp header.\n.INDENT 0.0\n.TP\n.B \\-\\-check\n.UNINDENT\n.sp\nMakes \\fBmakemigrations\\fP exit with a non\\-zero status when model changes without\nmigrations are detected.\n.SS \\fBmigrate\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin migrate [app_label] [migration_name]\n.UNINDENT\n.sp\nSynchronizes the database state with the current set of models and migrations.\nMigrations, their relationship with apps and more are covered in depth in\nthe migrations documentation\\&.\n.sp\nThe behavior of this command changes depending on the arguments provided:\n.INDENT 0.0\n.IP \\(bu 2\nNo arguments: All apps have all of their migrations run.\n.IP \\(bu 2\n\\fB<app_label>\\fP: The specified app has its migrations run, up to the most\nrecent migration. This may involve running other apps\\(aq migrations too, due\nto dependencies.\n.IP \\(bu 2\n\\fB<app_label> <migrationname>\\fP: Brings the database schema to a state where\nthe named migration is applied, but no later migrations in the same app are\napplied. This may involve unapplying migrations if you have previously\nmigrated past the named migration. You can use a prefix of the migration\nname, e.g. \\fB0001\\fP, as long as it\\(aqs unique for the given app name. Use the\nname \\fBzero\\fP to migrate all the way back i.e. to revert all applied\nmigrations for an app.\n.UNINDENT\n.sp\n\\fBWARNING:\\fP\n.INDENT 0.0\n.INDENT 3.5\nWhen unapplying migrations, all dependent migrations will also be\nunapplied, regardless of \\fB<app_label>\\fP\\&. You can use \\fB\\-\\-plan\\fP to check\nwhich migrations will be unapplied.\n.UNINDENT\n.UNINDENT\n.INDENT 0.0\n.TP\n.B \\-\\-database DATABASE\n.UNINDENT\n.sp\nSpecifies the database to migrate. Defaults to \\fBdefault\\fP\\&.\n.INDENT 0.0\n.TP\n.B \\-\\-fake\n.UNINDENT\n.sp\nMarks the migrations up to the target one (following the rules above) as\napplied, but without actually running the SQL to change your database schema.\n.sp\nThis is intended for advanced users to manipulate the\ncurrent migration state directly if they\\(aqre manually applying changes;\nbe warned that using \\fB\\-\\-fake\\fP runs the risk of putting the migration state\ntable into a state where manual recovery will be needed to make migrations\nrun correctly.\n.INDENT 0.0\n.TP\n.B \\-\\-fake\\-initial\n.UNINDENT\n.sp\nAllows Django to skip an app\\(aqs initial migration if all database tables with\nthe names of all models created by all\n\\fBCreateModel\\fP operations in that\nmigration already exist. This option is intended for use when first running\nmigrations against a database that preexisted the use of migrations. This\noption does not, however, check for matching database schema beyond matching\ntable names and so is only safe to use if you are confident that your existing\nschema matches what is recorded in your initial migration.\n.INDENT 0.0\n.TP\n.B \\-\\-plan\n.UNINDENT\n.sp\nShows the migration operations that will be performed for the given \\fBmigrate\\fP\ncommand.\n.INDENT 0.0\n.TP\n.B \\-\\-run\\-syncdb\n.UNINDENT\n.sp\nAllows creating tables for apps without migrations. While this isn\\(aqt\nrecommended, the migrations framework is sometimes too slow on large projects\nwith hundreds of models.\n.INDENT 0.0\n.TP\n.B \\-\\-noinput, \\-\\-no\\-input\n.UNINDENT\n.sp\nSuppresses all user prompts. An example prompt is asking about removing stale\ncontent types.\n.INDENT 0.0\n.TP\n.B \\-\\-check\n.UNINDENT\n.sp\n\n.sp\nMakes \\fBmigrate\\fP exit with a non\\-zero status when unapplied migrations are\ndetected.\n.SS \\fBrunserver\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin runserver [addrport]\n.UNINDENT\n.sp\nStarts a lightweight development Web server on the local machine. By default,\nthe server runs on port 8000 on the IP address \\fB127.0.0.1\\fP\\&. You can pass in an\nIP address and port number explicitly.\n.sp\nIf you run this script as a user with normal privileges (recommended), you\nmight not have access to start a port on a low port number. Low port numbers\nare reserved for the superuser (root).\n.sp\nThis server uses the WSGI application object specified by the\n\\fBWSGI_APPLICATION\\fP setting.\n.sp\nDO NOT USE THIS SERVER IN A PRODUCTION SETTING. It has not gone through\nsecurity audits or performance tests. (And that\\(aqs how it\\(aqs gonna stay. We\\(aqre in\nthe business of making Web frameworks, not Web servers, so improving this\nserver to be able to handle a production environment is outside the scope of\nDjango.)\n.sp\nThe development server automatically reloads Python code for each request, as\nneeded. You don\\(aqt need to restart the server for code changes to take effect.\nHowever, some actions like adding files don\\(aqt trigger a restart, so you\\(aqll\nhave to restart the server in these cases.\n.sp\nIf you\\(aqre using Linux or MacOS and install both \\fI\\%pywatchman\\fP and the\n\\fI\\%Watchman\\fP service, kernel signals will be used to autoreload the server\n(rather than polling file modification timestamps each second). This offers\nbetter performance on large projects, reduced response time after code changes,\nmore robust change detection, and a reduction in power usage. Django supports\n\\fBpywatchman\\fP 1.2.0 and higher.\n.INDENT 0.0\n.INDENT 3.5\n.IP \"Large directories with many files may cause performance issues\"\n.sp\nWhen using Watchman with a project that includes large non\\-Python\ndirectories like \\fBnode_modules\\fP, it\\(aqs advisable to ignore this directory\nfor optimal performance. See the \\fI\\%watchman documentation\\fP for information\non how to do this.\n.UNINDENT\n.UNINDENT\n.INDENT 0.0\n.INDENT 3.5\n.IP \"Watchman timeout\"\n.sp\nThe default timeout of \\fBWatchman\\fP client is 5 seconds. You can change it\nby setting the \\fBDJANGO_WATCHMAN_TIMEOUT\\fP environment variable.\n.UNINDENT\n.UNINDENT\n.sp\nWhen you start the server, and each time you change Python code while the\nserver is running, the system check framework will check your entire Django\nproject for some common errors (see the \\fI\\%check\\fP command). If any\nerrors are found, they will be printed to standard output.\n.sp\nYou can run as many concurrent servers as you want, as long as they\\(aqre on\nseparate ports by executing \\fBdjango\\-admin runserver\\fP more than once.\n.sp\nNote that the default IP address, \\fB127.0.0.1\\fP, is not accessible from other\nmachines on your network. To make your development server viewable to other\nmachines on the network, use its own IP address (e.g. \\fB192.168.2.1\\fP) or\n\\fB0.0.0.0\\fP or \\fB::\\fP (with IPv6 enabled).\n.sp\nYou can provide an IPv6 address surrounded by brackets\n(e.g. \\fB[200a::1]:8000\\fP). This will automatically enable IPv6 support.\n.sp\nA hostname containing ASCII\\-only characters can also be used.\n.sp\nIf the staticfiles contrib app is enabled\n(default in new projects) the \\fI\\%runserver\\fP command will be overridden\nwith its own runserver command.\n.sp\nLogging of each request and response of the server is sent to the\ndjango\\-server\\-logger logger.\n.INDENT 0.0\n.TP\n.B \\-\\-noreload\n.UNINDENT\n.sp\nDisables the auto\\-reloader. This means any Python code changes you make while\nthe server is running will \\fInot\\fP take effect if the particular Python modules\nhave already been loaded into memory.\n.INDENT 0.0\n.TP\n.B \\-\\-nothreading\n.UNINDENT\n.sp\nDisables use of threading in the development server. The server is\nmultithreaded by default.\n.INDENT 0.0\n.TP\n.B \\-\\-ipv6, \\-6\n.UNINDENT\n.sp\nUses IPv6 for the development server. This changes the default IP address from\n\\fB127.0.0.1\\fP to \\fB::1\\fP\\&.\n.SS Examples of using different ports and addresses\n.sp\nPort 8000 on IP address \\fB127.0.0.1\\fP:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin runserver\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nPort 8000 on IP address \\fB1.2.3.4\\fP:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin runserver 1.2.3.4:8000\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nPort 7000 on IP address \\fB127.0.0.1\\fP:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin runserver 7000\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nPort 7000 on IP address \\fB1.2.3.4\\fP:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin runserver 1.2.3.4:7000\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nPort 8000 on IPv6 address \\fB::1\\fP:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin runserver \\-6\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nPort 7000 on IPv6 address \\fB::1\\fP:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin runserver \\-6 7000\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nPort 7000 on IPv6 address \\fB2001:0db8:1234:5678::9\\fP:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin runserver [2001:0db8:1234:5678::9]:7000\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nPort 8000 on IPv4 address of host \\fBlocalhost\\fP:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin runserver localhost:8000\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nPort 8000 on IPv6 address of host \\fBlocalhost\\fP:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin runserver \\-6 localhost:8000\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.SS Serving static files with the development server\n.sp\nBy default, the development server doesn\\(aqt serve any static files for your site\n(such as CSS files, images, things under \\fBMEDIA_URL\\fP and so forth). If\nyou want to configure Django to serve static media, read\n/howto/static\\-files/index\\&.\n.SS \\fBsendtestemail\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin sendtestemail [email [email ...]]\n.UNINDENT\n.sp\nSends a test email (to confirm email sending through Django is working) to the\nrecipient(s) specified. For example:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin sendtestemail foo@example.com bar@example.com\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nThere are a couple of options, and you may use any combination of them\ntogether:\n.INDENT 0.0\n.TP\n.B \\-\\-managers\n.UNINDENT\n.sp\nMails the email addresses specified in \\fBMANAGERS\\fP using\n\\fBmail_managers()\\fP\\&.\n.INDENT 0.0\n.TP\n.B \\-\\-admins\n.UNINDENT\n.sp\nMails the email addresses specified in \\fBADMINS\\fP using\n\\fBmail_admins()\\fP\\&.\n.SS \\fBshell\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin shell\n.UNINDENT\n.sp\nStarts the Python interactive interpreter.\n.INDENT 0.0\n.TP\n.B \\-\\-interface {ipython,bpython,python}, \\-i {ipython,bpython,python}\n.UNINDENT\n.sp\nSpecifies the shell to use. By default, Django will use \\fI\\%IPython\\fP or \\fI\\%bpython\\fP if\neither is installed. If both are installed, specify which one you want like so:\n.sp\nIPython:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin shell \\-i ipython\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nbpython:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin shell \\-i bpython\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nIf you have a \"rich\" shell installed but want to force use of the \"plain\"\nPython interpreter, use \\fBpython\\fP as the interface name, like so:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin shell \\-i python\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.INDENT 0.0\n.TP\n.B \\-\\-nostartup\n.UNINDENT\n.sp\nDisables reading the startup script for the \"plain\" Python interpreter. By\ndefault, the script pointed to by the \\fI\\%PYTHONSTARTUP\\fP environment\nvariable or the \\fB~/.pythonrc.py\\fP script is read.\n.INDENT 0.0\n.TP\n.B \\-\\-command COMMAND, \\-c COMMAND\n.UNINDENT\n.sp\nLets you pass a command as a string to execute it as Django, like so:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin shell \\-\\-command=\"import django; print(django.__version__)\"\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nYou can also pass code in on standard input to execute it. For example:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\n$ django\\-admin shell <<EOF\n> import django\n> print(django.__version__)\n> EOF\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nOn Windows, the REPL is output due to implementation limits of\n\\fI\\%select.select()\\fP on that platform.\n.SS \\fBshowmigrations\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin showmigrations [app_label [app_label ...]]\n.UNINDENT\n.sp\nShows all migrations in a project. You can choose from one of two formats:\n.INDENT 0.0\n.TP\n.B \\-\\-list, \\-l\n.UNINDENT\n.sp\nLists all of the apps Django knows about, the migrations available for each\napp, and whether or not each migration is applied (marked by an \\fB[X]\\fP next to\nthe migration name). For a \\fB\\-\\-verbosity\\fP of 2 and above, the applied\ndatetimes are also shown.\n.sp\nApps without migrations are also listed, but have \\fB(no migrations)\\fP printed\nunder them.\n.sp\nThis is the default output format.\n.sp\nOutput of the applied datetimes at verbosity 2 and above was added.\n\n.INDENT 0.0\n.TP\n.B \\-\\-plan, \\-p\n.UNINDENT\n.sp\nShows the migration plan Django will follow to apply migrations. Like\n\\fB\\-\\-list\\fP, applied migrations are marked by an \\fB[X]\\fP\\&. For a \\fB\\-\\-verbosity\\fP\nof 2 and above, all dependencies of a migration will also be shown.\n.sp\n\\fBapp_label\\fPs arguments limit the output, however, dependencies of provided\napps may also be included.\n.INDENT 0.0\n.TP\n.B \\-\\-database DATABASE\n.UNINDENT\n.sp\nSpecifies the database to examine. Defaults to \\fBdefault\\fP\\&.\n.SS \\fBsqlflush\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin sqlflush\n.UNINDENT\n.sp\nPrints the SQL statements that would be executed for the \\fI\\%flush\\fP\ncommand.\n.INDENT 0.0\n.TP\n.B \\-\\-database DATABASE\n.UNINDENT\n.sp\nSpecifies the database for which to print the SQL. Defaults to \\fBdefault\\fP\\&.\n.SS \\fBsqlmigrate\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin sqlmigrate app_label migration_name\n.UNINDENT\n.sp\nPrints the SQL for the named migration. This requires an active database\nconnection, which it will use to resolve constraint names; this means you must\ngenerate the SQL against a copy of the database you wish to later apply it on.\n.sp\nNote that \\fBsqlmigrate\\fP doesn\\(aqt colorize its output.\n.INDENT 0.0\n.TP\n.B \\-\\-backwards\n.UNINDENT\n.sp\nGenerates the SQL for unapplying the migration. By default, the SQL created is\nfor running the migration in the forwards direction.\n.INDENT 0.0\n.TP\n.B \\-\\-database DATABASE\n.UNINDENT\n.sp\nSpecifies the database for which to generate the SQL. Defaults to \\fBdefault\\fP\\&.\n.SS \\fBsqlsequencereset\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin sqlsequencereset app_label [app_label ...]\n.UNINDENT\n.sp\nPrints the SQL statements for resetting sequences for the given app name(s).\n.sp\nSequences are indexes used by some database engines to track the next available\nnumber for automatically incremented fields.\n.sp\nUse this command to generate SQL which will fix cases where a sequence is out\nof sync with its automatically incremented field data.\n.INDENT 0.0\n.TP\n.B \\-\\-database DATABASE\n.UNINDENT\n.sp\nSpecifies the database for which to print the SQL. Defaults to \\fBdefault\\fP\\&.\n.SS \\fBsquashmigrations\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin squashmigrations app_label [start_migration_name] migration_name\n.UNINDENT\n.sp\nSquashes the migrations for \\fBapp_label\\fP up to and including \\fBmigration_name\\fP\ndown into fewer migrations, if possible. The resulting squashed migrations\ncan live alongside the unsquashed ones safely. For more information,\nplease read migration\\-squashing\\&.\n.sp\nWhen \\fBstart_migration_name\\fP is given, Django will only include migrations\nstarting from and including this migration. This helps to mitigate the\nsquashing limitation of \\fBRunPython\\fP and\n\\fBdjango.db.migrations.operations.RunSQL\\fP migration operations.\n.INDENT 0.0\n.TP\n.B \\-\\-no\\-optimize\n.UNINDENT\n.sp\nDisables the optimizer when generating a squashed migration. By default, Django\nwill try to optimize the operations in your migrations to reduce the size of\nthe resulting file. Use this option if this process is failing or creating\nincorrect migrations, though please also file a Django bug report about the\nbehavior, as optimization is meant to be safe.\n.INDENT 0.0\n.TP\n.B \\-\\-noinput, \\-\\-no\\-input\n.UNINDENT\n.sp\nSuppresses all user prompts.\n.INDENT 0.0\n.TP\n.B \\-\\-squashed\\-name SQUASHED_NAME\n.UNINDENT\n.sp\nSets the name of the squashed migration. When omitted, the name is based on the\nfirst and last migration, with \\fB_squashed_\\fP in between.\n.INDENT 0.0\n.TP\n.B \\-\\-no\\-header\n.UNINDENT\n.sp\nGenerate squashed migration file without Django version and timestamp header.\n.SS \\fBstartapp\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin startapp name [directory]\n.UNINDENT\n.sp\nCreates a Django app directory structure for the given app name in the current\ndirectory or the given destination.\n.sp\nBy default, \\fI\\%the new directory\\fP contains a\n\\fBmodels.py\\fP file and other app template files. If only the app name is given,\nthe app directory will be created in the current working directory.\n.sp\nIf the optional destination is provided, Django will use that existing\ndirectory rather than creating a new one. You can use \\(aq.\\(aq to denote the current\nworking directory.\n.sp\nFor example:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin startapp myapp /Users/jezdez/Code/myapp\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.INDENT 0.0\n.TP\n.B \\-\\-template TEMPLATE\n.UNINDENT\n.sp\nProvides the path to a directory with a custom app template file, or a path to\nan uncompressed archive (\\fB\\&.tar\\fP) or a compressed archive (\\fB\\&.tar.gz\\fP,\n\\fB\\&.tar.bz2\\fP, \\fB\\&.tar.xz\\fP, \\fB\\&.tar.lzma\\fP, \\fB\\&.tgz\\fP, \\fB\\&.tbz2\\fP, \\fB\\&.txz\\fP,\n\\fB\\&.tlz\\fP, \\fB\\&.zip\\fP) containing the app template files.\n.sp\nFor example, this would look for an app template in the given directory when\ncreating the \\fBmyapp\\fP app:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin startapp \\-\\-template=/Users/jezdez/Code/my_app_template myapp\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nDjango will also accept URLs (\\fBhttp\\fP, \\fBhttps\\fP, \\fBftp\\fP) to compressed\narchives with the app template files, downloading and extracting them on the\nfly.\n.sp\nFor example, taking advantage of GitHub\\(aqs feature to expose repositories as\nzip files, you can use a URL like:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin startapp \\-\\-template=https://github.com/githubuser/django\\-app\\-template/archive/master.zip myapp\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nSupport for XZ archives (\\fB\\&.tar.xz\\fP, \\fB\\&.txz\\fP) and LZMA archives\n(\\fB\\&.tar.lzma\\fP, \\fB\\&.tlz\\fP) was added.\n\n.INDENT 0.0\n.TP\n.B \\-\\-extension EXTENSIONS, \\-e EXTENSIONS\n.UNINDENT\n.sp\nSpecifies which file extensions in the app template should be rendered with the\ntemplate engine. Defaults to \\fBpy\\fP\\&.\n.INDENT 0.0\n.TP\n.B \\-\\-name FILES, \\-n FILES\n.UNINDENT\n.sp\nSpecifies which files in the app template (in addition to those matching\n\\fB\\-\\-extension\\fP) should be rendered with the template engine. Defaults to an\nempty list.\n.sp\nThe \\fBtemplate context\\fP used for all matching\nfiles is:\n.INDENT 0.0\n.IP \\(bu 2\nAny option passed to the \\fBstartapp\\fP command (among the command\\(aqs supported\noptions)\n.IP \\(bu 2\n\\fBapp_name\\fP \\-\\- the app name as passed to the command\n.IP \\(bu 2\n\\fBapp_directory\\fP \\-\\- the full path of the newly created app\n.IP \\(bu 2\n\\fBcamel_case_app_name\\fP \\-\\- the app name in camel case format\n.IP \\(bu 2\n\\fBdocs_version\\fP \\-\\- the version of the documentation: \\fB\\(aqdev\\(aq\\fP or \\fB\\(aq1.x\\(aq\\fP\n.IP \\(bu 2\n\\fBdjango_version\\fP \\-\\- the version of Django, e.g. \\fB\\(aq2.0.3\\(aq\\fP\n.UNINDENT\n.sp\n\\fBWARNING:\\fP\n.INDENT 0.0\n.INDENT 3.5\nWhen the app template files are rendered with the Django template\nengine (by default all \\fB*.py\\fP files), Django will also replace all\nstray template variables contained. For example, if one of the Python files\ncontains a docstring explaining a particular feature related\nto template rendering, it might result in an incorrect example.\n.sp\nTo work around this problem, you can use the \\fBtemplatetag\\fP\ntemplate tag to \"escape\" the various parts of the template syntax.\n.sp\nIn addition, to allow Python template files that contain Django template\nlanguage syntax while also preventing packaging systems from trying to\nbyte\\-compile invalid \\fB*.py\\fP files, template files ending with \\fB\\&.py\\-tpl\\fP\nwill be renamed to \\fB\\&.py\\fP\\&.\n.UNINDENT\n.UNINDENT\n.SS \\fBstartproject\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin startproject name [directory]\n.UNINDENT\n.sp\nCreates a Django project directory structure for the given project name in\nthe current directory or the given destination.\n.sp\nBy default, \\fI\\%the new directory\\fP contains\n\\fBmanage.py\\fP and a project package (containing a \\fBsettings.py\\fP and other\nfiles).\n.sp\nIf only the project name is given, both the project directory and project\npackage will be named \\fB<projectname>\\fP and the project directory\nwill be created in the current working directory.\n.sp\nIf the optional destination is provided, Django will use that existing\ndirectory as the project directory, and create \\fBmanage.py\\fP and the project\npackage within it. Use \\(aq.\\(aq to denote the current working directory.\n.sp\nFor example:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin startproject myproject /Users/jezdez/Code/myproject_repo\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.INDENT 0.0\n.TP\n.B \\-\\-template TEMPLATE\n.UNINDENT\n.sp\nSpecifies a directory, file path, or URL of a custom project template. See the\n\\fI\\%startapp \\-\\-template\\fP documentation for examples and usage.\n.INDENT 0.0\n.TP\n.B \\-\\-extension EXTENSIONS, \\-e EXTENSIONS\n.UNINDENT\n.sp\nSpecifies which file extensions in the project template should be rendered with\nthe template engine. Defaults to \\fBpy\\fP\\&.\n.INDENT 0.0\n.TP\n.B \\-\\-name FILES, \\-n FILES\n.UNINDENT\n.sp\nSpecifies which files in the project template (in addition to those matching\n\\fB\\-\\-extension\\fP) should be rendered with the template engine. Defaults to an\nempty list.\n.sp\nThe \\fBtemplate context\\fP used is:\n.INDENT 0.0\n.IP \\(bu 2\nAny option passed to the \\fBstartproject\\fP command (among the command\\(aqs\nsupported options)\n.IP \\(bu 2\n\\fBproject_name\\fP \\-\\- the project name as passed to the command\n.IP \\(bu 2\n\\fBproject_directory\\fP \\-\\- the full path of the newly created project\n.IP \\(bu 2\n\\fBsecret_key\\fP \\-\\- a random key for the \\fBSECRET_KEY\\fP setting\n.IP \\(bu 2\n\\fBdocs_version\\fP \\-\\- the version of the documentation: \\fB\\(aqdev\\(aq\\fP or \\fB\\(aq1.x\\(aq\\fP\n.IP \\(bu 2\n\\fBdjango_version\\fP \\-\\- the version of Django, e.g. \\fB\\(aq2.0.3\\(aq\\fP\n.UNINDENT\n.sp\nPlease also see the \\fI\\%rendering warning\\fP as mentioned\nfor \\fI\\%startapp\\fP\\&.\n.SS \\fBtest\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin test [test_label [test_label ...]]\n.UNINDENT\n.sp\nRuns tests for all installed apps. See /topics/testing/index for more\ninformation.\n.INDENT 0.0\n.TP\n.B \\-\\-failfast\n.UNINDENT\n.sp\nStops running tests and reports the failure immediately after a test fails.\n.INDENT 0.0\n.TP\n.B \\-\\-testrunner TESTRUNNER\n.UNINDENT\n.sp\nControls the test runner class that is used to execute tests. This value\noverrides the value provided by the \\fBTEST_RUNNER\\fP setting.\n.INDENT 0.0\n.TP\n.B \\-\\-noinput, \\-\\-no\\-input\n.UNINDENT\n.sp\nSuppresses all user prompts. A typical prompt is a warning about deleting an\nexisting test database.\n.SS Test runner options\n.sp\nThe \\fBtest\\fP command receives options on behalf of the specified\n\\fI\\%\\-\\-testrunner\\fP\\&. These are the options of the default test runner:\n\\fBDiscoverRunner\\fP\\&.\n.INDENT 0.0\n.TP\n.B \\-\\-keepdb\n.UNINDENT\n.sp\nPreserves the test database between test runs. This has the advantage of\nskipping both the create and destroy actions which can greatly decrease the\ntime to run tests, especially those in a large test suite. If the test database\ndoes not exist, it will be created on the first run and then preserved for each\nsubsequent run. Unless the \\fBMIGRATE\\fP test setting is\n\\fBFalse\\fP, any unapplied migrations will also be applied to the test database\nbefore running the test suite.\n.INDENT 0.0\n.TP\n.B \\-\\-reverse, \\-r\n.UNINDENT\n.sp\nSorts test cases in the opposite execution order. This may help in debugging\nthe side effects of tests that aren\\(aqt properly isolated. Grouping by test\nclass is preserved when using this option.\n.INDENT 0.0\n.TP\n.B \\-\\-debug\\-mode\n.UNINDENT\n.sp\nSets the \\fBDEBUG\\fP setting to \\fBTrue\\fP prior to running tests. This may\nhelp troubleshoot test failures.\n.INDENT 0.0\n.TP\n.B \\-\\-debug\\-sql, \\-d\n.UNINDENT\n.sp\nEnables SQL logging for failing tests. If\n\\fB\\-\\-verbosity\\fP is \\fB2\\fP, then queries in passing tests are also output.\n.INDENT 0.0\n.TP\n.B \\-\\-parallel [N]\n.UNINDENT\n.sp\nRuns tests in separate parallel processes. Since modern processors have\nmultiple cores, this allows running tests significantly faster.\n.sp\nBy default \\fB\\-\\-parallel\\fP runs one process per core according to\n\\fI\\%multiprocessing.cpu_count()\\fP\\&. You can adjust the number of processes\neither by providing it as the option\\(aqs value, e.g. \\fB\\-\\-parallel=4\\fP, or by\nsetting the \\fBDJANGO_TEST_PROCESSES\\fP environment variable.\n.sp\nDjango distributes test cases — \\fI\\%unittest.TestCase\\fP subclasses — to\nsubprocesses. If there are fewer test cases than configured processes, Django\nwill reduce the number of processes accordingly.\n.sp\nEach process gets its own database. You must ensure that different test cases\ndon\\(aqt access the same resources. For instance, test cases that touch the\nfilesystem should create a temporary directory for their own use.\n.sp\n\\fBNOTE:\\fP\n.INDENT 0.0\n.INDENT 3.5\nIf you have test classes that cannot be run in parallel, you can use\n\\fBSerializeMixin\\fP to run them sequentially. See Enforce running test\nclasses sequentially\\&.\n.UNINDENT\n.UNINDENT\n.sp\nThis option requires the third\\-party \\fBtblib\\fP package to display tracebacks\ncorrectly:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\n$ python \\-m pip install tblib\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nThis feature isn\\(aqt available on Windows. It doesn\\(aqt work with the Oracle\ndatabase backend either.\n.sp\nIf you want to use \\fI\\%pdb\\fP while debugging tests, you must disable parallel\nexecution (\\fB\\-\\-parallel=1\\fP). You\\(aqll see something like \\fBbdb.BdbQuit\\fP if you\ndon\\(aqt.\n.sp\n\\fBWARNING:\\fP\n.INDENT 0.0\n.INDENT 3.5\nWhen test parallelization is enabled and a test fails, Django may be\nunable to display the exception traceback. This can make debugging\ndifficult. If you encounter this problem, run the affected test without\nparallelization to see the traceback of the failure.\n.sp\nThis is a known limitation. It arises from the need to serialize objects\nin order to exchange them between processes. See\n\\fI\\%What can be pickled and unpickled?\\fP for details.\n.UNINDENT\n.UNINDENT\n.INDENT 0.0\n.TP\n.B \\-\\-tag TAGS\n.UNINDENT\n.sp\nRuns only tests marked with the specified tags\\&.\nMay be specified multiple times and combined with \\fI\\%test \\-\\-exclude\\-tag\\fP\\&.\n.INDENT 0.0\n.TP\n.B \\-\\-exclude\\-tag EXCLUDE_TAGS\n.UNINDENT\n.sp\nExcludes tests marked with the specified tags\\&.\nMay be specified multiple times and combined with \\fI\\%test \\-\\-tag\\fP\\&.\n.INDENT 0.0\n.TP\n.B \\-k TEST_NAME_PATTERNS\n.UNINDENT\n.sp\n\n.sp\nRuns test methods and classes matching test name patterns, in the same way as\n\\fI\\%unittest\\(aqs \\-k option\\fP\\&. Can be specified multiple times.\n.INDENT 0.0\n.INDENT 3.5\n.IP \"Python 3.7 and later\"\n.sp\nThis feature is only available for Python 3.7 and later.\n.UNINDENT\n.UNINDENT\n.INDENT 0.0\n.TP\n.B \\-\\-pdb\n.UNINDENT\n.sp\n\n.sp\nSpawns a \\fBpdb\\fP debugger at each test error or failure. If you have it\ninstalled, \\fBipdb\\fP is used instead.\n.INDENT 0.0\n.TP\n.B \\-\\-buffer, \\-b\n.UNINDENT\n.sp\n\n.sp\nDiscards output (\\fBstdout\\fP and \\fBstderr\\fP) for passing tests, in the same way\nas \\fI\\%unittest\\(aqs \\-\\-buffer option\\fP\\&.\n.SS \\fBtestserver\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin testserver [fixture [fixture ...]]\n.UNINDENT\n.sp\nRuns a Django development server (as in \\fI\\%runserver\\fP) using data from\nthe given fixture(s).\n.sp\nFor example, this command:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin testserver mydata.json\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\n\\&...would perform the following steps:\n.INDENT 0.0\n.IP 1. 3\nCreate a test database, as described in the\\-test\\-database\\&.\n.IP 2. 3\nPopulate the test database with fixture data from the given fixtures.\n(For more on fixtures, see the documentation for \\fI\\%loaddata\\fP above.)\n.IP 3. 3\nRuns the Django development server (as in \\fI\\%runserver\\fP), pointed at\nthis newly created test database instead of your production database.\n.UNINDENT\n.sp\nThis is useful in a number of ways:\n.INDENT 0.0\n.IP \\(bu 2\nWhen you\\(aqre writing unit tests of how your views\nact with certain fixture data, you can use \\fBtestserver\\fP to interact with\nthe views in a Web browser, manually.\n.IP \\(bu 2\nLet\\(aqs say you\\(aqre developing your Django application and have a \"pristine\"\ncopy of a database that you\\(aqd like to interact with. You can dump your\ndatabase to a fixture (using the \\fI\\%dumpdata\\fP command, explained\nabove), then use \\fBtestserver\\fP to run your Web application with that data.\nWith this arrangement, you have the flexibility of messing up your data\nin any way, knowing that whatever data changes you\\(aqre making are only\nbeing made to a test database.\n.UNINDENT\n.sp\nNote that this server does \\fInot\\fP automatically detect changes to your Python\nsource code (as \\fI\\%runserver\\fP does). It does, however, detect changes to\ntemplates.\n.INDENT 0.0\n.TP\n.B \\-\\-addrport ADDRPORT\n.UNINDENT\n.sp\nSpecifies a different port, or IP address and port, from the default of\n\\fB127.0.0.1:8000\\fP\\&. This value follows exactly the same format and serves\nexactly the same function as the argument to the \\fI\\%runserver\\fP command.\n.sp\nExamples:\n.sp\nTo run the test server on port 7000 with \\fBfixture1\\fP and \\fBfixture2\\fP:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin testserver \\-\\-addrport 7000 fixture1 fixture2\ndjango\\-admin testserver fixture1 fixture2 \\-\\-addrport 7000\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\n(The above statements are equivalent. We include both of them to demonstrate\nthat it doesn\\(aqt matter whether the options come before or after the fixture\narguments.)\n.sp\nTo run on 1.2.3.4:7000 with a \\fBtest\\fP fixture:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin testserver \\-\\-addrport 1.2.3.4:7000 test\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.INDENT 0.0\n.TP\n.B \\-\\-noinput, \\-\\-no\\-input\n.UNINDENT\n.sp\nSuppresses all user prompts. A typical prompt is a warning about deleting an\nexisting test database.\n.SH COMMANDS PROVIDED BY APPLICATIONS\n.sp\nSome commands are only available when the \\fBdjango.contrib\\fP application that\nimplements them has been\n\\fBenabled\\fP\\&. This section describes them grouped by\ntheir application.\n.SS \\fBdjango.contrib.auth\\fP\n.SS \\fBchangepassword\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin changepassword [<username>]\n.UNINDENT\n.sp\nThis command is only available if Django\\(aqs authentication system (\\fBdjango.contrib.auth\\fP) is installed.\n.sp\nAllows changing a user\\(aqs password. It prompts you to enter a new password twice\nfor the given user. If the entries are identical, this immediately becomes the\nnew password. If you do not supply a user, the command will attempt to change\nthe password whose username matches the current user.\n.INDENT 0.0\n.TP\n.B \\-\\-database DATABASE\n.UNINDENT\n.sp\nSpecifies the database to query for the user. Defaults to \\fBdefault\\fP\\&.\n.sp\nExample usage:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin changepassword ringo\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.SS \\fBcreatesuperuser\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin createsuperuser\n.UNINDENT\n.sp\nThis command is only available if Django\\(aqs authentication system (\\fBdjango.contrib.auth\\fP) is installed.\n.sp\nCreates a superuser account (a user who has all permissions). This is\nuseful if you need to create an initial superuser account or if you need to\nprogrammatically generate superuser accounts for your site(s).\n.sp\nWhen run interactively, this command will prompt for a password for\nthe new superuser account. When run non\\-interactively, you can provide\na password by setting the \\fBDJANGO_SUPERUSER_PASSWORD\\fP environment variable.\nOtherwise, no password will be set, and the superuser account will not be able\nto log in until a password has been manually set for it.\n.sp\nIn non\\-interactive mode, the\n\\fBUSERNAME_FIELD\\fP and required\nfields (listed in\n\\fBREQUIRED_FIELDS\\fP) fall back to\n\\fBDJANGO_SUPERUSER_<uppercase_field_name>\\fP environment variables, unless they\nare overridden by a command line argument. For example, to provide an \\fBemail\\fP\nfield, you can use \\fBDJANGO_SUPERUSER_EMAIL\\fP environment variable.\n.sp\nSupport for using \\fBDJANGO_SUPERUSER_PASSWORD\\fP and\n\\fBDJANGO_SUPERUSER_<uppercase_field_name>\\fP environment variables was added.\n\n.INDENT 0.0\n.TP\n.B \\-\\-noinput, \\-\\-no\\-input\n.UNINDENT\n.sp\nSuppresses all user prompts. If a suppressed prompt cannot be resolved\nautomatically, the command will exit with error code 1.\n.INDENT 0.0\n.TP\n.B \\-\\-username USERNAME\n.UNINDENT\n.INDENT 0.0\n.TP\n.B \\-\\-email EMAIL\n.UNINDENT\n.sp\nThe username and email address for the new account can be supplied by\nusing the \\fB\\-\\-username\\fP and \\fB\\-\\-email\\fP arguments on the command\nline. If either of those is not supplied, \\fBcreatesuperuser\\fP will prompt for\nit when running interactively.\n.INDENT 0.0\n.TP\n.B \\-\\-database DATABASE\n.UNINDENT\n.sp\nSpecifies the database into which the superuser object will be saved.\n.sp\nYou can subclass the management command and override \\fBget_input_data()\\fP if you\nwant to customize data input and validation. Consult the source code for\ndetails on the existing implementation and the method\\(aqs parameters. For example,\nit could be useful if you have a \\fBForeignKey\\fP in\n\\fBREQUIRED_FIELDS\\fP and want to\nallow creating an instance instead of entering the primary key of an existing\ninstance.\n.SS \\fBdjango.contrib.contenttypes\\fP\n.SS \\fBremove_stale_contenttypes\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin remove_stale_contenttypes\n.UNINDENT\n.sp\nThis command is only available if Django\\(aqs contenttypes app (\\fBdjango.contrib.contenttypes\\fP) is installed.\n.sp\nDeletes stale content types (from deleted models) in your database. Any objects\nthat depend on the deleted content types will also be deleted. A list of\ndeleted objects will be displayed before you confirm it\\(aqs okay to proceed with\nthe deletion.\n.INDENT 0.0\n.TP\n.B \\-\\-database DATABASE\n.UNINDENT\n.sp\nSpecifies the database to use. Defaults to \\fBdefault\\fP\\&.\n.INDENT 0.0\n.TP\n.B \\-\\-include\\-stale\\-apps\n.UNINDENT\n.sp\n\n.sp\nDeletes stale content types including ones from previously installed apps that\nhave been removed from \\fBINSTALLED_APPS\\fP\\&. Defaults to \\fBFalse\\fP\\&.\n.SS \\fBdjango.contrib.gis\\fP\n.SS \\fBogrinspect\\fP\n.sp\nThis command is only available if GeoDjango\n(\\fBdjango.contrib.gis\\fP) is installed.\n.sp\nPlease refer to its \\fBdescription\\fP in the GeoDjango\ndocumentation.\n.SS \\fBdjango.contrib.sessions\\fP\n.SS \\fBclearsessions\\fP\n.INDENT 0.0\n.TP\n.B django\\-admin clearsessions\n.UNINDENT\n.sp\nCan be run as a cron job or directly to clean out expired sessions.\n.SS \\fBdjango.contrib.sitemaps\\fP\n.SS \\fBping_google\\fP\n.sp\nThis command is only available if the Sitemaps framework (\\fBdjango.contrib.sitemaps\\fP) is installed.\n.sp\nPlease refer to its \\fBdescription\\fP in the Sitemaps\ndocumentation.\n.SS \\fBdjango.contrib.staticfiles\\fP\n.SS \\fBcollectstatic\\fP\n.sp\nThis command is only available if the static files application (\\fBdjango.contrib.staticfiles\\fP) is installed.\n.sp\nPlease refer to its \\fBdescription\\fP in the\nstaticfiles documentation.\n.SS \\fBfindstatic\\fP\n.sp\nThis command is only available if the static files application (\\fBdjango.contrib.staticfiles\\fP) is installed.\n.sp\nPlease refer to its \\fBdescription\\fP in the staticfiles documentation.\n.SH DEFAULT OPTIONS\n.sp\nAlthough some commands may allow their own custom options, every command\nallows for the following options:\n.INDENT 0.0\n.TP\n.B \\-\\-pythonpath PYTHONPATH\n.UNINDENT\n.sp\nAdds the given filesystem path to the Python \\fI\\%import search path\\fP\\&. If this\nisn\\(aqt provided, \\fBdjango\\-admin\\fP will use the \\fBPYTHONPATH\\fP environment\nvariable.\n.sp\nThis option is unnecessary in \\fBmanage.py\\fP, because it takes care of setting\nthe Python path for you.\n.sp\nExample usage:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin migrate \\-\\-pythonpath=\\(aq/home/djangoprojects/myproject\\(aq\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.INDENT 0.0\n.TP\n.B \\-\\-settings SETTINGS\n.UNINDENT\n.sp\nSpecifies the settings module to use. The settings module should be in Python\npackage syntax, e.g. \\fBmysite.settings\\fP\\&. If this isn\\(aqt provided,\n\\fBdjango\\-admin\\fP will use the \\fBDJANGO_SETTINGS_MODULE\\fP environment variable.\n.sp\nThis option is unnecessary in \\fBmanage.py\\fP, because it uses\n\\fBsettings.py\\fP from the current project by default.\n.sp\nExample usage:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin migrate \\-\\-settings=mysite.settings\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.INDENT 0.0\n.TP\n.B \\-\\-traceback\n.UNINDENT\n.sp\nDisplays a full stack trace when a \\fBCommandError\\fP\nis raised. By default, \\fBdjango\\-admin\\fP will show an error message when a\n\\fBCommandError\\fP occurs and a full stack trace for any other exception.\n.sp\nExample usage:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin migrate \\-\\-traceback\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.INDENT 0.0\n.TP\n.B \\-\\-verbosity {0,1,2,3}, \\-v {0,1,2,3}\n.UNINDENT\n.sp\nSpecifies the amount of notification and debug information that a command\nshould print to the console.\n.INDENT 0.0\n.IP \\(bu 2\n\\fB0\\fP means no output.\n.IP \\(bu 2\n\\fB1\\fP means normal output (default).\n.IP \\(bu 2\n\\fB2\\fP means verbose output.\n.IP \\(bu 2\n\\fB3\\fP means \\fIvery\\fP verbose output.\n.UNINDENT\n.sp\nExample usage:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin migrate \\-\\-verbosity 2\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.INDENT 0.0\n.TP\n.B \\-\\-no\\-color\n.UNINDENT\n.sp\nDisables colorized command output.  Some commands format their output to be\ncolorized. For example, errors will be printed to the console in red and SQL\nstatements will be syntax highlighted.\n.sp\nExample usage:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin runserver \\-\\-no\\-color\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.INDENT 0.0\n.TP\n.B \\-\\-force\\-color\n.UNINDENT\n.sp\nForces colorization of the command output if it would otherwise be disabled\nas discussed in \\fI\\%Syntax coloring\\fP\\&. For example, you may want to pipe\ncolored output to another command.\n.INDENT 0.0\n.TP\n.B \\-\\-skip\\-checks\n.UNINDENT\n.sp\n\n.sp\nSkips running system checks prior to running the command. This option is only\navailable if the\n\\fBrequires_system_checks\\fP command\nattribute is set to \\fBTrue\\fP\\&.\n.sp\nExample usage:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\ndjango\\-admin migrate \\-\\-skip\\-checks\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.SH EXTRA NICETIES\n.SS Syntax coloring\n.sp\nThe \\fBdjango\\-admin\\fP / \\fBmanage.py\\fP commands will use pretty\ncolor\\-coded output if your terminal supports ANSI\\-colored output. It\nwon\\(aqt use the color codes if you\\(aqre piping the command\\(aqs output to\nanother program unless the \\fI\\%\\-\\-force\\-color\\fP option is used.\n.sp\nUnder Windows, the native console doesn\\(aqt support ANSI escape sequences so by\ndefault there is no color output. But you can install the \\fI\\%ANSICON\\fP\nthird\\-party tool, the Django commands will detect its presence and will make\nuse of its services to color output just like on Unix\\-based platforms.\n.sp\nThe colors used for syntax highlighting can be customized. Django\nships with three color palettes:\n.INDENT 0.0\n.IP \\(bu 2\n\\fBdark\\fP, suited to terminals that show white text on a black\nbackground. This is the default palette.\n.IP \\(bu 2\n\\fBlight\\fP, suited to terminals that show black text on a white\nbackground.\n.IP \\(bu 2\n\\fBnocolor\\fP, which disables syntax highlighting.\n.UNINDENT\n.sp\nYou select a palette by setting a \\fBDJANGO_COLORS\\fP environment\nvariable to specify the palette you want to use. For example, to\nspecify the \\fBlight\\fP palette under a Unix or OS/X BASH shell, you\nwould run the following at a command prompt:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\nexport DJANGO_COLORS=\"light\"\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nYou can also customize the colors that are used. Django specifies a\nnumber of roles in which color is used:\n.INDENT 0.0\n.IP \\(bu 2\n\\fBerror\\fP \\- A major error.\n.IP \\(bu 2\n\\fBnotice\\fP \\- A minor error.\n.IP \\(bu 2\n\\fBsuccess\\fP \\- A success.\n.IP \\(bu 2\n\\fBwarning\\fP \\- A warning.\n.IP \\(bu 2\n\\fBsql_field\\fP \\- The name of a model field in SQL.\n.IP \\(bu 2\n\\fBsql_coltype\\fP \\- The type of a model field in SQL.\n.IP \\(bu 2\n\\fBsql_keyword\\fP \\- An SQL keyword.\n.IP \\(bu 2\n\\fBsql_table\\fP \\- The name of a model in SQL.\n.IP \\(bu 2\n\\fBhttp_info\\fP \\- A 1XX HTTP Informational server response.\n.IP \\(bu 2\n\\fBhttp_success\\fP \\- A 2XX HTTP Success server response.\n.IP \\(bu 2\n\\fBhttp_not_modified\\fP \\- A 304 HTTP Not Modified server response.\n.IP \\(bu 2\n\\fBhttp_redirect\\fP \\- A 3XX HTTP Redirect server response other than 304.\n.IP \\(bu 2\n\\fBhttp_not_found\\fP \\- A 404 HTTP Not Found server response.\n.IP \\(bu 2\n\\fBhttp_bad_request\\fP \\- A 4XX HTTP Bad Request server response other than 404.\n.IP \\(bu 2\n\\fBhttp_server_error\\fP \\- A 5XX HTTP Server Error response.\n.IP \\(bu 2\n\\fBmigrate_heading\\fP \\- A heading in a migrations management command.\n.IP \\(bu 2\n\\fBmigrate_label\\fP \\- A migration name.\n.UNINDENT\n.sp\nEach of these roles can be assigned a specific foreground and\nbackground color, from the following list:\n.INDENT 0.0\n.IP \\(bu 2\n\\fBblack\\fP\n.IP \\(bu 2\n\\fBred\\fP\n.IP \\(bu 2\n\\fBgreen\\fP\n.IP \\(bu 2\n\\fByellow\\fP\n.IP \\(bu 2\n\\fBblue\\fP\n.IP \\(bu 2\n\\fBmagenta\\fP\n.IP \\(bu 2\n\\fBcyan\\fP\n.IP \\(bu 2\n\\fBwhite\\fP\n.UNINDENT\n.sp\nEach of these colors can then be modified by using the following\ndisplay options:\n.INDENT 0.0\n.IP \\(bu 2\n\\fBbold\\fP\n.IP \\(bu 2\n\\fBunderscore\\fP\n.IP \\(bu 2\n\\fBblink\\fP\n.IP \\(bu 2\n\\fBreverse\\fP\n.IP \\(bu 2\n\\fBconceal\\fP\n.UNINDENT\n.sp\nA color specification follows one of the following patterns:\n.INDENT 0.0\n.IP \\(bu 2\n\\fBrole=fg\\fP\n.IP \\(bu 2\n\\fBrole=fg/bg\\fP\n.IP \\(bu 2\n\\fBrole=fg,option,option\\fP\n.IP \\(bu 2\n\\fBrole=fg/bg,option,option\\fP\n.UNINDENT\n.sp\nwhere \\fBrole\\fP is the name of a valid color role, \\fBfg\\fP is the\nforeground color, \\fBbg\\fP is the background color and each \\fBoption\\fP\nis one of the color modifying options. Multiple color specifications\nare then separated by a semicolon. For example:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\nexport DJANGO_COLORS=\"error=yellow/blue,blink;notice=magenta\"\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nwould specify that errors be displayed using blinking yellow on blue,\nand notices displayed using magenta. All other color roles would be\nleft uncolored.\n.sp\nColors can also be specified by extending a base palette. If you put\na palette name in a color specification, all the colors implied by that\npalette will be loaded. So:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\nexport DJANGO_COLORS=\"light;error=yellow/blue,blink;notice=magenta\"\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nwould specify the use of all the colors in the light color palette,\n\\fIexcept\\fP for the colors for errors and notices which would be\noverridden as specified.\n.SS Bash completion\n.sp\nIf you use the Bash shell, consider installing the Django bash completion\nscript, which lives in \\fBextras/django_bash_completion\\fP in the Django source\ndistribution. It enables tab\\-completion of \\fBdjango\\-admin\\fP and\n\\fBmanage.py\\fP commands, so you can, for instance...\n.INDENT 0.0\n.IP \\(bu 2\nType \\fBdjango\\-admin\\fP\\&.\n.IP \\(bu 2\nPress [TAB] to see all available options.\n.IP \\(bu 2\nType \\fBsql\\fP, then [TAB], to see all available options whose names start\nwith \\fBsql\\fP\\&.\n.UNINDENT\n.sp\nSee /howto/custom\\-management\\-commands for how to add customized actions.\n.INDENT 0.0\n.TP\n.B django.core.management.call_command(name, *args, **options)\n.UNINDENT\n.sp\nTo call a management command from code use \\fBcall_command\\fP\\&.\n.INDENT 0.0\n.TP\n.B \\fBname\\fP\nthe name of the command to call or a command object. Passing the name is\npreferred unless the object is required for testing.\n.TP\n.B \\fB*args\\fP\na list of arguments accepted by the command. Arguments are passed to the\nargument parser, so you can use the same style as you would on the command\nline. For example, \\fBcall_command(\\(aqflush\\(aq, \\(aq\\-\\-verbosity=0\\(aq)\\fP\\&.\n.TP\n.B \\fB**options\\fP\nnamed options accepted on the command\\-line. Options are passed to the command\nwithout triggering the argument parser, which means you\\(aqll need to pass the\ncorrect type. For example, \\fBcall_command(\\(aqflush\\(aq, verbosity=0)\\fP (zero must\nbe an integer rather than a string).\n.UNINDENT\n.sp\nExamples:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\nfrom django.core import management\nfrom django.core.management.commands import loaddata\n\nmanagement.call_command(\\(aqflush\\(aq, verbosity=0, interactive=False)\nmanagement.call_command(\\(aqloaddata\\(aq, \\(aqtest_data\\(aq, verbosity=0)\nmanagement.call_command(loaddata.Command(), \\(aqtest_data\\(aq, verbosity=0)\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nNote that command options that take no arguments are passed as keywords\nwith \\fBTrue\\fP or \\fBFalse\\fP, as you can see with the \\fBinteractive\\fP option above.\n.sp\nNamed arguments can be passed by using either one of the following syntaxes:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\n# Similar to the command line\nmanagement.call_command(\\(aqdumpdata\\(aq, \\(aq\\-\\-natural\\-foreign\\(aq)\n\n# Named argument similar to the command line minus the initial dashes and\n# with internal dashes replaced by underscores\nmanagement.call_command(\\(aqdumpdata\\(aq, natural_foreign=True)\n\n# \\(gause_natural_foreign_keys\\(ga is the option destination variable\nmanagement.call_command(\\(aqdumpdata\\(aq, use_natural_foreign_keys=True)\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nSome command options have different names when using \\fBcall_command()\\fP instead\nof \\fBdjango\\-admin\\fP or \\fBmanage.py\\fP\\&. For example, \\fBdjango\\-admin\ncreatesuperuser \\-\\-no\\-input\\fP translates to \\fBcall_command(\\(aqcreatesuperuser\\(aq,\ninteractive=False)\\fP\\&. To find what keyword argument name to use for\n\\fBcall_command()\\fP, check the command\\(aqs source code for the \\fBdest\\fP argument\npassed to \\fBparser.add_argument()\\fP\\&.\n.sp\nCommand options which take multiple options are passed a list:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\nmanagement.call_command(\\(aqdumpdata\\(aq, exclude=[\\(aqcontenttypes\\(aq, \\(aqauth\\(aq])\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.sp\nThe return value of the \\fBcall_command()\\fP function is the same as the return\nvalue of the \\fBhandle()\\fP method of the command.\n.SH OUTPUT REDIRECTION\n.sp\nNote that you can redirect standard output and error streams as all commands\nsupport the \\fBstdout\\fP and \\fBstderr\\fP options. For example, you could write:\n.INDENT 0.0\n.INDENT 3.5\n.sp\n.nf\n.ft C\nwith open(\\(aq/path/to/command_output\\(aq, \\(aqw\\(aq) as f:\n    management.call_command(\\(aqdumpdata\\(aq, stdout=f)\n.ft P\n.fi\n.UNINDENT\n.UNINDENT\n.SH AUTHOR\nDjango Software Foundation\n.SH COPYRIGHT\nDjango Software Foundation and contributors\n.\\\" Generated by docutils manpage writer.\n.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":35,"nodeType":"TextFile","repoName":null,"name":"signals.txt","path":"docs/ref","text":"=======\nSignals\n=======\n\nA list of all the signals that Django sends. All built-in signals are sent\nusing the :meth:`~django.dispatch.Signal.send` method.\n\n.. seealso::\n\n    See the documentation on the :doc:`signal dispatcher </topics/signals>` for\n    information regarding how to register for and receive signals.\n\n    The :doc:`authentication framework </topics/auth/index>` sends :ref:`signals when\n    a user is logged in / out <topics-auth-signals>`.\n\nModel signals\n=============\n\n.. module:: django.db.models.signals\n   :synopsis: Signals sent by the model system.\n\nThe :mod:`django.db.models.signals` module defines a set of signals sent by the\nmodel system.\n\n.. warning::\n\n    Many of these signals are sent by various model methods like\n    ``__init__()`` or :meth:`~django.db.models.Model.save` that you can\n    override in your own code.\n\n    If you override these methods on your model, you must call the parent class'\n    methods for these signals to be sent.\n\n    Note also that Django stores signal handlers as weak references by default,\n    so if your handler is a local function, it may be garbage collected.  To\n    prevent this, pass ``weak=False`` when you call the signal's :meth:`~django.dispatch.Signal.connect`.\n\n.. note::\n\n    Model signals ``sender`` model can be lazily referenced when connecting a\n    receiver by specifying its full application label. For example, an\n    ``Question`` model defined in the ``polls`` application could be referenced\n    as ``'polls.Question'``. This sort of reference can be quite handy when\n    dealing with circular import dependencies and swappable models.\n\n``pre_init``\n------------\n\n.. attribute:: django.db.models.signals.pre_init\n   :module:\n\n.. ^^^^^^^ this :module: hack keeps Sphinx from prepending the module.\n\nWhenever you instantiate a Django model, this signal is sent at the beginning\nof the model's ``__init__()`` method.\n\nArguments sent with this signal:\n\n``sender``\n    The model class that just had an instance created.\n\n``args``\n    A list of positional arguments passed to ``__init__()``.\n\n``kwargs``\n    A dictionary of keyword arguments passed to ``__init__()``.\n\nFor example, the :doc:`tutorial </intro/tutorial02>` has this line::\n\n    q = Question(question_text=\"What's new?\", pub_date=timezone.now())\n\nThe arguments sent to a :data:`pre_init` handler would be:\n\n==========  ===============================================================\nArgument    Value\n==========  ===============================================================\n``sender``  ``Question`` (the class itself)\n\n``args``    ``[]`` (an empty list because there were no positional\n            arguments passed to ``__init__()``)\n\n``kwargs``  ``{'question_text': \"What's new?\",``\n            ``'pub_date': datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)}``\n==========  ===============================================================\n\n``post_init``\n-------------\n\n.. data:: django.db.models.signals.post_init\n   :module:\n\nLike pre_init, but this one is sent when the ``__init__()`` method finishes.\n\nArguments sent with this signal:\n\n``sender``\n    As above: the model class that just had an instance created.\n\n``instance``\n    The actual instance of the model that's just been created.\n\n    .. note::\n\n        ``instance._state`` isn't set before sending the ``post_init`` signal,\n        so ``_state`` attributes always have their default values. For example,\n        ``_state.db`` is ``None`` and cannot be used to check an ``instance``\n        database.\n\n.. warning::\n\n    For performance reasons, you shouldn't perform queries in receivers of\n    ``pre_init`` or ``post_init`` signals because they would be executed for\n    each instance returned during queryset iteration.\n\n``pre_save``\n------------\n\n.. data:: django.db.models.signals.pre_save\n   :module:\n\nThis is sent at the beginning of a model's :meth:`~django.db.models.Model.save`\nmethod.\n\nArguments sent with this signal:\n\n``sender``\n    The model class.\n\n``instance``\n    The actual instance being saved.\n\n``raw``\n    A boolean; ``True`` if the model is saved exactly as presented\n    (i.e. when loading a fixture). One should not query/modify other\n    records in the database as the database might not be in a\n    consistent state yet.\n\n``using``\n    The database alias being used.\n\n``update_fields``\n    The set of fields to update as passed to :meth:`.Model.save`, or ``None``\n    if ``update_fields`` wasn't passed to ``save()``.\n\n``post_save``\n-------------\n\n.. data:: django.db.models.signals.post_save\n   :module:\n\nLike :data:`pre_save`, but sent at the end of the\n:meth:`~django.db.models.Model.save` method.\n\nArguments sent with this signal:\n\n``sender``\n    The model class.\n\n``instance``\n    The actual instance being saved.\n\n``created``\n    A boolean; ``True`` if a new record was created.\n\n``raw``\n    A boolean; ``True`` if the model is saved exactly as presented\n    (i.e. when loading a fixture). One should not query/modify other\n    records in the database as the database might not be in a\n    consistent state yet.\n\n``using``\n    The database alias being used.\n\n``update_fields``\n    The set of fields to update as passed to :meth:`.Model.save`, or ``None``\n    if ``update_fields`` wasn't passed to ``save()``.\n\n``pre_delete``\n--------------\n\n.. data:: django.db.models.signals.pre_delete\n   :module:\n\nSent at the beginning of a model's :meth:`~django.db.models.Model.delete`\nmethod and a queryset's :meth:`~django.db.models.query.QuerySet.delete` method.\n\nArguments sent with this signal:\n\n``sender``\n    The model class.\n\n``instance``\n    The actual instance being deleted.\n\n``using``\n    The database alias being used.\n\n``post_delete``\n---------------\n\n.. data:: django.db.models.signals.post_delete\n   :module:\n\nLike :data:`pre_delete`, but sent at the end of a model's\n:meth:`~django.db.models.Model.delete` method and a queryset's\n:meth:`~django.db.models.query.QuerySet.delete` method.\n\nArguments sent with this signal:\n\n``sender``\n    The model class.\n\n``instance``\n    The actual instance being deleted.\n\n    Note that the object will no longer be in the database, so be very\n    careful what you do with this instance.\n\n``using``\n    The database alias being used.\n\n``m2m_changed``\n---------------\n\n.. data:: django.db.models.signals.m2m_changed\n   :module:\n\nSent when a :class:`~django.db.models.ManyToManyField` is changed on a model\ninstance. Strictly speaking, this is not a model signal since it is sent by the\n:class:`~django.db.models.ManyToManyField`, but since it complements the\n:data:`pre_save`/:data:`post_save` and :data:`pre_delete`/:data:`post_delete`\nwhen it comes to tracking changes to models, it is included here.\n\nArguments sent with this signal:\n\n``sender``\n    The intermediate model class describing the\n    :class:`~django.db.models.ManyToManyField`. This class is automatically\n    created when a many-to-many field is defined; you can access it using the\n    ``through`` attribute on the many-to-many field.\n\n``instance``\n    The instance whose many-to-many relation is updated. This can be an\n    instance of the ``sender``, or of the class the\n    :class:`~django.db.models.ManyToManyField` is related to.\n\n``action``\n    A string indicating the type of update that is done on the relation.\n    This can be one of the following:\n\n    ``\"pre_add\"``\n        Sent *before* one or more objects are added to the relation.\n    ``\"post_add\"``\n        Sent *after* one or more objects are added to the relation.\n    ``\"pre_remove\"``\n        Sent *before* one or more objects are removed from the relation.\n    ``\"post_remove\"``\n        Sent *after* one or more objects are removed from the relation.\n    ``\"pre_clear\"``\n        Sent *before* the relation is cleared.\n    ``\"post_clear\"``\n        Sent *after* the relation is cleared.\n\n``reverse``\n    Indicates which side of the relation is updated (i.e., if it is the\n    forward or reverse relation that is being modified).\n\n``model``\n    The class of the objects that are added to, removed from or cleared\n    from the relation.\n\n``pk_set``\n    For the ``pre_add`` and ``post_add`` actions, this is a set of primary key\n    values that will be, or have been, added to the relation. This may be a\n    subset of the values submitted to be added, since inserts must filter\n    existing values in order to avoid a database ``IntegrityError``.\n\n    For the ``pre_remove`` and ``post_remove`` actions, this is a set of\n    primary key values that was submitted to be removed from the relation. This\n    is not dependent on whether the values actually will be, or have been,\n    removed. In particular, non-existent values may be submitted, and will\n    appear in ``pk_set``, even though they have no effect on the database.\n\n    For the ``pre_clear`` and ``post_clear`` actions, this is ``None``.\n\n``using``\n    The database alias being used.\n\nFor example, if a ``Pizza`` can have multiple ``Topping`` objects, modeled\nlike this::\n\n    class Topping(models.Model):\n        # ...\n        pass\n\n    class Pizza(models.Model):\n        # ...\n        toppings = models.ManyToManyField(Topping)\n\nIf we connected a handler like this::\n\n    from django.db.models.signals import m2m_changed\n\n    def toppings_changed(sender, **kwargs):\n        # Do something\n        pass\n\n    m2m_changed.connect(toppings_changed, sender=Pizza.toppings.through)\n\nand then did something like this::\n\n    >>> p = Pizza.objects.create(...)\n    >>> t = Topping.objects.create(...)\n    >>> p.toppings.add(t)\n\nthe arguments sent to a :data:`m2m_changed` handler (``toppings_changed`` in\nthe example above) would be:\n\n==============  ============================================================\nArgument        Value\n==============  ============================================================\n``sender``      ``Pizza.toppings.through`` (the intermediate m2m class)\n\n``instance``    ``p`` (the ``Pizza`` instance being modified)\n\n``action``      ``\"pre_add\"`` (followed by a separate signal with ``\"post_add\"``)\n\n``reverse``     ``False`` (``Pizza`` contains the\n                :class:`~django.db.models.ManyToManyField`, so this call\n                modifies the forward relation)\n\n``model``       ``Topping`` (the class of the objects added to the\n                ``Pizza``)\n\n``pk_set``      ``{t.id}`` (since only ``Topping t`` was added to the relation)\n\n``using``       ``\"default\"`` (since the default router sends writes here)\n==============  ============================================================\n\nAnd if we would then do something like this::\n\n    >>> t.pizza_set.remove(p)\n\nthe arguments sent to a :data:`m2m_changed` handler would be:\n\n==============  ============================================================\nArgument        Value\n==============  ============================================================\n``sender``      ``Pizza.toppings.through`` (the intermediate m2m class)\n\n``instance``    ``t`` (the ``Topping`` instance being modified)\n\n``action``      ``\"pre_remove\"`` (followed by a separate signal with ``\"post_remove\"``)\n\n``reverse``     ``True`` (``Pizza`` contains the\n                :class:`~django.db.models.ManyToManyField`, so this call\n                modifies the reverse relation)\n\n``model``       ``Pizza`` (the class of the objects removed from the\n                ``Topping``)\n\n``pk_set``      ``{p.id}`` (since only ``Pizza p`` was removed from the\n                relation)\n\n``using``       ``\"default\"`` (since the default router sends writes here)\n==============  ============================================================\n\n``class_prepared``\n------------------\n\n.. data:: django.db.models.signals.class_prepared\n   :module:\n\nSent whenever a model class has been \"prepared\" -- that is, once model has\nbeen defined and registered with Django's model system. Django uses this\nsignal internally; it's not generally used in third-party applications.\n\nSince this signal is sent during the app registry population process, and\n:meth:`AppConfig.ready() <django.apps.AppConfig.ready>` runs after the app\nregistry is fully populated, receivers cannot be connected in that method.\nOne possibility is to connect them ``AppConfig.__init__()`` instead, taking\ncare not to import models or trigger calls to the app registry.\n\nArguments that are sent with this signal:\n\n``sender``\n    The model class which was just prepared.\n\nManagement signals\n==================\n\nSignals sent by :doc:`django-admin </ref/django-admin>`.\n\n``pre_migrate``\n---------------\n\n.. data:: django.db.models.signals.pre_migrate\n   :module:\n\nSent by the :djadmin:`migrate` command before it starts to install an\napplication. It's not emitted for applications that lack a ``models`` module.\n\nArguments sent with this signal:\n\n``sender``\n    An :class:`~django.apps.AppConfig` instance for the application about to\n    be migrated/synced.\n\n``app_config``\n    Same as ``sender``.\n\n``verbosity``\n    Indicates how much information manage.py is printing on screen. See\n    the :option:`--verbosity` flag for details.\n\n    Functions which listen for :data:`pre_migrate` should adjust what they\n    output to the screen based on the value of this argument.\n\n``interactive``\n    If ``interactive`` is ``True``, it's safe to prompt the user to input\n    things on the command line. If ``interactive`` is ``False``, functions\n    which listen for this signal should not try to prompt for anything.\n\n    For example, the :mod:`django.contrib.auth` app only prompts to create a\n    superuser when ``interactive`` is ``True``.\n\n``using``\n    The alias of database on which a command will operate.\n\n``plan``\n    The migration plan that is going to be used for the migration run. While\n    the plan is not public API, this allows for the rare cases when it is\n    necessary to know the plan. A plan is a list of two-tuples with the first\n    item being the instance of a migration class and the second item showing\n    if the migration was rolled back (``True``) or applied (``False``).\n\n``apps``\n    An instance of :data:`Apps <django.apps>` containing the state of the\n    project before the migration run. It should be used instead of the global\n    :attr:`apps <django.apps.apps>` registry to retrieve the models you\n    want to perform operations on.\n\n``post_migrate``\n----------------\n\n.. data:: django.db.models.signals.post_migrate\n   :module:\n\nSent at the end of the :djadmin:`migrate` (even if no migrations are run) and\n:djadmin:`flush` commands. It's not emitted for applications that lack a\n``models`` module.\n\nHandlers of this signal must not perform database schema alterations as doing\nso may cause the :djadmin:`flush` command to fail if it runs during the\n:djadmin:`migrate` command.\n\nArguments sent with this signal:\n\n``sender``\n    An :class:`~django.apps.AppConfig` instance for the application that was\n    just installed.\n\n``app_config``\n    Same as ``sender``.\n\n``verbosity``\n    Indicates how much information manage.py is printing on screen. See\n    the :option:`--verbosity` flag for details.\n\n    Functions which listen for :data:`post_migrate` should adjust what they\n    output to the screen based on the value of this argument.\n\n``interactive``\n    If ``interactive`` is ``True``, it's safe to prompt the user to input\n    things on the command line. If ``interactive`` is ``False``, functions\n    which listen for this signal should not try to prompt for anything.\n\n    For example, the :mod:`django.contrib.auth` app only prompts to create a\n    superuser when ``interactive`` is ``True``.\n\n``using``\n    The database alias used for synchronization. Defaults to the ``default``\n    database.\n\n``plan``\n    The migration plan that was used for the migration run. While the plan is\n    not public API, this allows for the rare cases when it is necessary to\n    know the plan. A plan is a list of two-tuples with the first item being\n    the instance of a migration class and the second item showing if the\n    migration was rolled back (``True``) or applied (``False``).\n\n``apps``\n    An instance of :data:`Apps <django.apps.apps>` containing the state of the\n    project after the migration run. It should be used instead of the global\n    :attr:`apps <django.apps.apps>` registry to retrieve the models you\n    want to perform operations on.\n\nFor example, you could register a callback in an\n:class:`~django.apps.AppConfig` like this::\n\n    from django.apps import AppConfig\n    from django.db.models.signals import post_migrate\n\n    def my_callback(sender, **kwargs):\n        # Your specific logic here\n        pass\n\n    class MyAppConfig(AppConfig):\n        ...\n\n        def ready(self):\n            post_migrate.connect(my_callback, sender=self)\n\n.. note::\n\n    If you provide an :class:`~django.apps.AppConfig` instance as the sender\n    argument, please ensure that the signal is registered in\n    :meth:`~django.apps.AppConfig.ready`. ``AppConfig``\\s are recreated for\n    tests that run with a modified set of :setting:`INSTALLED_APPS` (such as\n    when settings are overridden) and such signals should be connected for each\n    new ``AppConfig`` instance.\n\nRequest/response signals\n========================\n\n.. module:: django.core.signals\n   :synopsis: Core signals sent by the request/response system.\n\nSignals sent by the core framework when processing a request.\n\n``request_started``\n-------------------\n\n.. data:: django.core.signals.request_started\n   :module:\n\nSent when Django begins processing an HTTP request.\n\nArguments sent with this signal:\n\n``sender``\n    The handler class -- e.g. ``django.core.handlers.wsgi.WsgiHandler`` -- that\n    handled the request.\n``environ``\n    The ``environ`` dictionary provided to the request.\n\n``request_finished``\n--------------------\n\n.. data:: django.core.signals.request_finished\n   :module:\n\nSent when Django finishes delivering an HTTP response to the client.\n\nArguments sent with this signal:\n\n``sender``\n    The handler class, as above.\n\n``got_request_exception``\n-------------------------\n\n.. data:: django.core.signals.got_request_exception\n   :module:\n\nThis signal is sent whenever Django encounters an exception while processing an incoming HTTP request.\n\nArguments sent with this signal:\n\n``sender``\n    Unused (always ``None``).\n\n``request``\n    The :class:`~django.http.HttpRequest` object.\n\nTest signals\n============\n\n.. module:: django.test.signals\n   :synopsis: Signals sent during testing.\n\nSignals only sent when :ref:`running tests <running-tests>`.\n\n``setting_changed``\n-------------------\n\n.. data:: django.test.signals.setting_changed\n   :module:\n\nThis signal is sent when the value of a setting is changed through the\n``django.test.TestCase.settings()`` context manager or the\n:func:`django.test.override_settings` decorator/context manager.\n\nIt's actually sent twice: when the new value is applied (\"setup\") and when the\noriginal value is restored (\"teardown\"). Use the ``enter`` argument to\ndistinguish between the two.\n\nYou can also import this signal from ``django.core.signals`` to avoid importing\nfrom ``django.test`` in non-test situations.\n\nArguments sent with this signal:\n\n``sender``\n    The settings handler.\n\n``setting``\n    The name of the setting.\n\n``value``\n    The value of the setting after the change. For settings that initially\n    don't exist, in the \"teardown\" phase, ``value`` is ``None``.\n\n``enter``\n    A boolean; ``True`` if the setting is applied, ``False`` if restored.\n\n``template_rendered``\n---------------------\n\n.. data:: django.test.signals.template_rendered\n   :module:\n\nSent when the test system renders a template. This signal is not emitted during\nnormal operation of a Django server -- it is only available during testing.\n\nArguments sent with this signal:\n\n``sender``\n    The :class:`~django.template.Template` object which was rendered.\n\n``template``\n    Same as sender\n\n``context``\n    The :class:`~django.template.Context` with which the template was\n    rendered.\n\nDatabase Wrappers\n=================\n\n.. module:: django.db.backends\n   :synopsis: Core signals sent by the database wrapper.\n\nSignals sent by the database wrapper when a database connection is\ninitiated.\n\n``connection_created``\n----------------------\n\n.. data:: django.db.backends.signals.connection_created\n   :module:\n\nSent when the database wrapper makes the initial connection to the\ndatabase.  This is particularly useful if you'd like to send any post\nconnection commands to the SQL backend.\n\nArguments sent with this signal:\n\n``sender``\n    The database wrapper class -- i.e.\n    ``django.db.backends.postgresql.DatabaseWrapper`` or\n    ``django.db.backends.mysql.DatabaseWrapper``, etc.\n\n``connection``\n    The database connection that was opened. This can be used in a\n    multiple-database configuration to differentiate connection signals\n    from different databases.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":36,"nodeType":"TextFile","repoName":null,"name":"applications.txt","path":"docs/ref","text":"============\nApplications\n============\n\n.. module:: django.apps\n\nDjango contains a registry of installed applications that stores configuration\nand provides introspection. It also maintains a list of available :doc:`models\n</topics/db/models>`.\n\nThis registry is called :attr:`~django.apps.apps` and it's available in\n:mod:`django.apps`::\n\n    >>> from django.apps import apps\n    >>> apps.get_app_config('admin').verbose_name\n    'Administration'\n\nProjects and applications\n=========================\n\nThe term **project** describes a Django web application. The project Python\npackage is defined primarily by a settings module, but it usually contains\nother things. For example, when you run  ``django-admin startproject mysite``\nyou'll get a ``mysite`` project directory that contains a ``mysite`` Python\npackage with ``settings.py``, ``urls.py``, ``asgi.py`` and ``wsgi.py``. The\nproject package is often extended to include things like fixtures, CSS, and\ntemplates which aren't tied to a particular application.\n\nA **project's root directory** (the one that contains ``manage.py``) is usually\nthe container for all of a project's applications which aren't installed\nseparately.\n\nThe term **application** describes a Python package that provides some set of\nfeatures. Applications :doc:`may be reused </intro/reusable-apps/>` in various\nprojects.\n\nApplications include some combination of models, views, templates, template\ntags, static files, URLs, middleware, etc. They're generally wired into\nprojects with the :setting:`INSTALLED_APPS` setting and optionally with other\nmechanisms such as URLconfs, the :setting:`MIDDLEWARE` setting, or template\ninheritance.\n\nIt is important to understand that a Django application is a set of code\nthat interacts with various parts of the framework. There's no such thing as\nan ``Application`` object. However, there's a few places where Django needs to\ninteract with installed applications, mainly for configuration and also for\nintrospection. That's why the application registry maintains metadata in an\n:class:`~django.apps.AppConfig` instance for each installed application.\n\nThere's no restriction that a project package can't also be considered an\napplication and have models, etc. (which would require adding it to\n:setting:`INSTALLED_APPS`).\n\n.. _configuring-applications-ref:\n\nConfiguring applications\n========================\n\nTo configure an application, subclass :class:`~django.apps.AppConfig` and put\nthe dotted path to that subclass in :setting:`INSTALLED_APPS`.\n\nWhen :setting:`INSTALLED_APPS` contains the dotted path to an application\nmodule, Django checks for a ``default_app_config`` variable in that module.\n\nIf it's defined, it's the dotted path to the :class:`~django.apps.AppConfig`\nsubclass for that application.\n\nIf there is no ``default_app_config``, Django uses the base\n:class:`~django.apps.AppConfig` class.\n\n``default_app_config`` allows applications that predate Django 1.7 such as\n``django.contrib.admin`` to opt-in to :class:`~django.apps.AppConfig` features\nwithout requiring users to update their :setting:`INSTALLED_APPS`.\n\nNew applications should avoid ``default_app_config``. Instead they should\nrequire the dotted path to the appropriate :class:`~django.apps.AppConfig`\nsubclass to be configured explicitly in :setting:`INSTALLED_APPS`.\n\nFor application authors\n-----------------------\n\nIf you're creating a pluggable app called \"Rock ’n’ roll\", here's how you\nwould provide a proper name for the admin::\n\n    # rock_n_roll/apps.py\n\n    from django.apps import AppConfig\n\n    class RockNRollConfig(AppConfig):\n        name = 'rock_n_roll'\n        verbose_name = \"Rock ’n’ roll\"\n\nYou can make your application load this :class:`~django.apps.AppConfig`\nsubclass by default as follows::\n\n    # rock_n_roll/__init__.py\n\n    default_app_config = 'rock_n_roll.apps.RockNRollConfig'\n\nThat will cause ``RockNRollConfig`` to be used when :setting:`INSTALLED_APPS`\ncontains ``'rock_n_roll'``. This allows you to make use of\n:class:`~django.apps.AppConfig` features without requiring your users to update\ntheir :setting:`INSTALLED_APPS` setting. Besides this use case, it's best to\navoid using ``default_app_config`` and instead specify the app config class in\n:setting:`INSTALLED_APPS` as described next.\n\nYou can also tell your users to put ``'rock_n_roll.apps.RockNRollConfig'`` in\ntheir :setting:`INSTALLED_APPS` setting. You can even provide several different\n:class:`~django.apps.AppConfig` subclasses with different behaviors and allow\nyour users to choose one via their :setting:`INSTALLED_APPS` setting.\n\nThe recommended convention is to put the configuration class in a submodule of\nthe application called ``apps``. However, this isn't enforced by Django.\n\nYou must include the :attr:`~django.apps.AppConfig.name` attribute for Django\nto determine which application this configuration applies to. You can define\nany attributes documented in the :class:`~django.apps.AppConfig` API\nreference.\n\n.. note::\n\n    If your code imports the application registry in an application's\n    ``__init__.py``, the name ``apps`` will clash with the ``apps`` submodule.\n    The best practice is to move that code to a submodule and import it. A\n    workaround is to import the registry under a different name::\n\n        from django.apps import apps as django_apps\n\nFor application users\n---------------------\n\nIf you're using \"Rock ’n’ roll\" in a project called ``anthology``, but you\nwant it to show up as \"Jazz Manouche\" instead, you can provide your own\nconfiguration::\n\n    # anthology/apps.py\n\n    from rock_n_roll.apps import RockNRollConfig\n\n    class JazzManoucheConfig(RockNRollConfig):\n        verbose_name = \"Jazz Manouche\"\n\n    # anthology/settings.py\n\n    INSTALLED_APPS = [\n        'anthology.apps.JazzManoucheConfig',\n        # ...\n    ]\n\nAgain, defining project-specific configuration classes in a submodule called\n``apps`` is a convention, not a requirement.\n\nApplication configuration\n=========================\n\n.. class:: AppConfig\n\n    Application configuration objects store metadata for an application. Some\n    attributes can be configured in :class:`~django.apps.AppConfig`\n    subclasses. Others are set by Django and read-only.\n\nConfigurable attributes\n-----------------------\n\n.. attribute:: AppConfig.name\n\n    Full Python path to the application, e.g. ``'django.contrib.admin'``.\n\n    This attribute defines which application the configuration applies to. It\n    must be set in all :class:`~django.apps.AppConfig` subclasses.\n\n    It must be unique across a Django project.\n\n.. attribute:: AppConfig.label\n\n    Short name for the application, e.g. ``'admin'``\n\n    This attribute allows relabeling an application when two applications\n    have conflicting labels. It defaults to the last component of ``name``.\n    It should be a valid Python identifier.\n\n    It must be unique across a Django project.\n\n.. attribute:: AppConfig.verbose_name\n\n    Human-readable name for the application, e.g. \"Administration\".\n\n    This attribute defaults to ``label.title()``.\n\n.. attribute:: AppConfig.path\n\n    Filesystem path to the application directory, e.g.\n    ``'/usr/lib/pythonX.Y/dist-packages/django/contrib/admin'``.\n\n    In most cases, Django can automatically detect and set this, but you can\n    also provide an explicit override as a class attribute on your\n    :class:`~django.apps.AppConfig` subclass. In a few situations this is\n    required; for instance if the app package is a `namespace package`_ with\n    multiple paths.\n\nRead-only attributes\n--------------------\n\n.. attribute:: AppConfig.module\n\n    Root module for the application, e.g. ``<module 'django.contrib.admin' from\n    'django/contrib/admin/__init__.py'>``.\n\n.. attribute:: AppConfig.models_module\n\n    Module containing the models, e.g. ``<module 'django.contrib.admin.models'\n    from 'django/contrib/admin/models.py'>``.\n\n    It may be ``None`` if the application doesn't contain a ``models`` module.\n    Note that the database related signals such as\n    :data:`~django.db.models.signals.pre_migrate` and\n    :data:`~django.db.models.signals.post_migrate`\n    are only emitted for applications that have a ``models`` module.\n\nMethods\n-------\n\n.. method:: AppConfig.get_models()\n\n    Returns an iterable of :class:`~django.db.models.Model` classes for this\n    application.\n\n    Requires the app registry to be fully populated.\n\n.. method:: AppConfig.get_model(model_name, require_ready=True)\n\n    Returns the :class:`~django.db.models.Model` with the given\n    ``model_name``. ``model_name`` is case-insensitive.\n\n    Raises :exc:`LookupError` if no such model exists in this application.\n\n    Requires the app registry to be fully populated unless the\n    ``require_ready`` argument is set to ``False``. ``require_ready`` behaves\n    exactly as in :meth:`apps.get_model()`.\n\n.. method:: AppConfig.ready()\n\n    Subclasses can override this method to perform initialization tasks such\n    as registering signals. It is called as soon as the registry is fully\n    populated.\n\n    Although you can't import models at the module-level where\n    :class:`~django.apps.AppConfig` classes are defined, you can import them in\n    ``ready()``, using either an ``import`` statement or\n    :meth:`~AppConfig.get_model`.\n\n    If you're registering :mod:`model signals <django.db.models.signals>`, you\n    can refer to the sender by its string label instead of using the model\n    class itself.\n\n    Example::\n\n        from django.apps import AppConfig\n        from django.db.models.signals import pre_save\n\n\n        class RockNRollConfig(AppConfig):\n            # ...\n\n            def ready(self):\n                # importing model classes\n                from .models import MyModel  # or...\n                MyModel = self.get_model('MyModel')\n\n                # registering signals with the model's string label\n                pre_save.connect(receiver, sender='app_label.MyModel')\n\n    .. warning::\n\n        Although you can access model classes as described above, avoid\n        interacting with the database in your :meth:`ready()` implementation.\n        This includes model methods that execute queries\n        (:meth:`~django.db.models.Model.save()`,\n        :meth:`~django.db.models.Model.delete()`, manager methods etc.), and\n        also raw SQL queries via ``django.db.connection``. Your\n        :meth:`ready()` method will run during startup of every management\n        command. For example, even though the test database configuration is\n        separate from the production settings, ``manage.py test`` would still\n        execute some queries against your **production** database!\n\n    .. note::\n\n        In the usual initialization process, the ``ready`` method is only called\n        once by Django. But in some corner cases, particularly in tests which\n        are fiddling with installed applications, ``ready`` might be called more\n        than once. In that case, either write idempotent methods, or put a flag\n        on your ``AppConfig`` classes to prevent re-running code which should\n        be executed exactly one time.\n\n.. _namespace package:\n\nNamespace packages as apps\n--------------------------\n\nPython packages without an ``__init__.py`` file are known as \"namespace\npackages\" and may be spread across multiple directories at different locations\non ``sys.path`` (see :pep:`420`).\n\nDjango applications require a single base filesystem path where Django\n(depending on configuration) will search for templates, static assets,\netc. Thus, namespace packages may only be Django applications if one of the\nfollowing is true:\n\n#. The namespace package actually has only a single location (i.e. is not\n   spread across more than one directory.)\n\n#. The :class:`~django.apps.AppConfig` class used to configure the application\n   has a :attr:`~django.apps.AppConfig.path` class attribute, which is the\n   absolute directory path Django will use as the single base path for the\n   application.\n\nIf neither of these conditions is met, Django will raise\n:exc:`~django.core.exceptions.ImproperlyConfigured`.\n\nApplication registry\n====================\n\n.. data:: apps\n\n    The application registry provides the following public API. Methods that\n    aren't listed below are considered private and may change without notice.\n\n.. attribute:: apps.ready\n\n    Boolean attribute that is set to ``True`` after the registry is fully\n    populated and all :meth:`AppConfig.ready` methods are called.\n\n.. method:: apps.get_app_configs()\n\n    Returns an iterable of :class:`~django.apps.AppConfig` instances.\n\n.. method:: apps.get_app_config(app_label)\n\n    Returns an :class:`~django.apps.AppConfig` for the application with the\n    given ``app_label``. Raises :exc:`LookupError` if no such application\n    exists.\n\n.. method:: apps.is_installed(app_name)\n\n    Checks whether an application with the given name exists in the registry.\n    ``app_name`` is the full name of the app, e.g. ``'django.contrib.admin'``.\n\n.. method:: apps.get_model(app_label, model_name, require_ready=True)\n\n    Returns the :class:`~django.db.models.Model` with the given ``app_label``\n    and ``model_name``. As a shortcut, this method also accepts a single\n    argument in the form ``app_label.model_name``. ``model_name`` is\n    case-insensitive.\n\n    Raises :exc:`LookupError` if no such application or model exists. Raises\n    :exc:`ValueError` when called with a single argument that doesn't contain\n    exactly one dot.\n\n    Requires the app registry to be fully populated unless the\n    ``require_ready`` argument is set to ``False``.\n\n    Setting ``require_ready`` to ``False`` allows looking up models\n    :ref:`while the app registry is being populated <app-loading-process>`,\n    specifically during the second phase where it imports models. Then\n    ``get_model()`` has the same effect as importing the model. The main use\n    case is to configure model classes with settings, such as\n    :setting:`AUTH_USER_MODEL`.\n\n    When ``require_ready`` is ``False``, ``get_model()`` returns a model class\n    that may not be fully functional (reverse accessors may be missing, for\n    example) until the app registry is fully populated. For this reason, it's\n    best to leave ``require_ready`` to the default value of ``True`` whenever\n    possible.\n\n.. _app-loading-process:\n\nInitialization process\n======================\n\nHow applications are loaded\n---------------------------\n\nWhen Django starts, :func:`django.setup()` is responsible for populating the\napplication registry.\n\n.. currentmodule:: django\n\n.. function:: setup(set_prefix=True)\n\n    Configures Django by:\n\n    * Loading the settings.\n    * Setting up logging.\n    * If ``set_prefix`` is True, setting the URL resolver script prefix to\n      :setting:`FORCE_SCRIPT_NAME` if defined, or ``/`` otherwise.\n    * Initializing the application registry.\n\n    This function is called automatically:\n\n    * When running an HTTP server via Django's WSGI support.\n    * When invoking a management command.\n\n    It must be called explicitly in other cases, for instance in plain Python\n    scripts.\n\n.. currentmodule:: django.apps\n\nThe application registry is initialized in three stages. At each stage, Django\nprocesses all applications in the order of :setting:`INSTALLED_APPS`.\n\n#. First Django imports each item in :setting:`INSTALLED_APPS`.\n\n   If it's an application configuration class, Django imports the root package\n   of the application, defined by its :attr:`~AppConfig.name` attribute. If\n   it's a Python package, Django creates a default application configuration.\n\n   *At this stage, your code shouldn't import any models!*\n\n   In other words, your applications' root packages and the modules that\n   define your application configuration classes shouldn't import any models,\n   even indirectly.\n\n   Strictly speaking, Django allows importing models once their application\n   configuration is loaded. However, in order to avoid needless constraints on\n   the order of :setting:`INSTALLED_APPS`, it's strongly recommended not\n   import any models at this stage.\n\n   Once this stage completes, APIs that operate on application configurations\n   such as :meth:`~apps.get_app_config()` become usable.\n\n#. Then Django attempts to import the ``models`` submodule of each application,\n   if there is one.\n\n   You must define or import all models in your application's ``models.py`` or\n   ``models/__init__.py``. Otherwise, the application registry may not be fully\n   populated at this point, which could cause the ORM to malfunction.\n\n   Once this stage completes, APIs that operate on models such as\n   :meth:`~apps.get_model()` become usable.\n\n#. Finally Django runs the :meth:`~AppConfig.ready()` method of each application\n   configuration.\n\n.. _applications-troubleshooting:\n\nTroubleshooting\n---------------\n\nHere are some common problems that you may encounter during initialization:\n\n* :class:`~django.core.exceptions.AppRegistryNotReady`: This happens when\n  importing an application configuration or a models module triggers code that\n  depends on the app registry.\n\n  For example, :func:`~django.utils.translation.gettext()` uses the app\n  registry to look up translation catalogs in applications. To translate at\n  import time, you need :func:`~django.utils.translation.gettext_lazy()`\n  instead. (Using :func:`~django.utils.translation.gettext()` would be a bug,\n  because the translation would happen at import time, rather than at each\n  request depending on the active language.)\n\n  Executing database queries with the ORM at import time in models modules\n  will also trigger this exception. The ORM cannot function properly until all\n  models are available.\n\n  This exception also happens if you forget to call :func:`django.setup()` in\n  a standalone Python script.\n\n* ``ImportError: cannot import name ...`` This happens if the import sequence\n  ends up in a loop.\n\n  To eliminate such problems, you should minimize dependencies between your\n  models modules and do as little work as possible at import time. To avoid\n  executing code at import time, you can move it into a function and cache its\n  results. The code will be executed when you first need its results. This\n  concept is known as \"lazy evaluation\".\n\n* ``django.contrib.admin`` automatically performs autodiscovery of ``admin``\n  modules in installed applications. To prevent it, change your\n  :setting:`INSTALLED_APPS` to contain\n  ``'django.contrib.admin.apps.SimpleAdminConfig'`` instead of\n  ``'django.contrib.admin'``.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":37,"nodeType":"TextFile","repoName":null,"name":"exceptions.txt","path":"docs/ref","text":"=================\nDjango Exceptions\n=================\n\nDjango raises some of its own exceptions as well as standard Python exceptions.\n\nDjango Core Exceptions\n======================\n\n.. module:: django.core.exceptions\n    :synopsis: Django core exceptions\n\nDjango core exception classes are defined in ``django.core.exceptions``.\n\n``AppRegistryNotReady``\n-----------------------\n\n.. exception:: AppRegistryNotReady\n\n    This exception is raised when attempting to use models before the :ref:`app\n    loading process <app-loading-process>`, which initializes the ORM, is\n    complete.\n\n``ObjectDoesNotExist``\n----------------------\n\n.. exception:: ObjectDoesNotExist\n\n    The base class for :exc:`~django.db.models.Model.DoesNotExist` exceptions;\n    a ``try/except`` for ``ObjectDoesNotExist`` will catch\n    :exc:`~django.db.models.Model.DoesNotExist` exceptions for all models.\n\n    See :meth:`~django.db.models.query.QuerySet.get()` for further information\n    on :exc:`ObjectDoesNotExist` and :exc:`~django.db.models.Model.DoesNotExist`.\n\n``EmptyResultSet``\n------------------\n\n.. exception:: EmptyResultSet\n\n    ``EmptyResultSet`` may be raised during query generation if a query won't\n    return any results. Most Django projects won't encounter this exception,\n    but it might be useful for implementing custom lookups and expressions.\n\n``FieldDoesNotExist``\n---------------------\n\n.. exception:: FieldDoesNotExist\n\n    The ``FieldDoesNotExist`` exception is raised by a model's\n    ``_meta.get_field()`` method when the requested field does not exist on the\n    model or on the model's parents.\n\n``MultipleObjectsReturned``\n---------------------------\n\n.. exception:: MultipleObjectsReturned\n\n    The :exc:`MultipleObjectsReturned` exception is raised by a query if only\n    one object is expected, but multiple objects are returned. A base version\n    of this exception is provided in :mod:`django.core.exceptions`; each model\n    class contains a subclassed version that can be used to identify the\n    specific object type that has returned multiple objects.\n\n    See :meth:`~django.db.models.query.QuerySet.get()` for further information.\n\n``SuspiciousOperation``\n-----------------------\n\n.. exception:: SuspiciousOperation\n\n    The :exc:`SuspiciousOperation` exception is raised when a user has\n    performed an operation that should be considered suspicious from a security\n    perspective, such as tampering with a session cookie. Subclasses of\n    ``SuspiciousOperation`` include:\n\n    * ``DisallowedHost``\n    * ``DisallowedModelAdminLookup``\n    * ``DisallowedModelAdminToField``\n    * ``DisallowedRedirect``\n    * ``InvalidSessionKey``\n    * ``RequestDataTooBig``\n    * ``SuspiciousFileOperation``\n    * ``SuspiciousMultipartForm``\n    * ``SuspiciousSession``\n    * ``TooManyFieldsSent``\n\n    If a ``SuspiciousOperation`` exception reaches the WSGI handler level it is\n    logged at the ``Error`` level and results in\n    a :class:`~django.http.HttpResponseBadRequest`. See the :doc:`logging\n    documentation </topics/logging/>` for more information.\n\n``PermissionDenied``\n--------------------\n\n.. exception:: PermissionDenied\n\n    The :exc:`PermissionDenied` exception is raised when a user does not have\n    permission to perform the action requested.\n\n``ViewDoesNotExist``\n--------------------\n\n.. exception:: ViewDoesNotExist\n\n    The :exc:`ViewDoesNotExist` exception is raised by\n    :mod:`django.urls` when a requested view does not exist.\n\n``MiddlewareNotUsed``\n---------------------\n\n.. exception:: MiddlewareNotUsed\n\n    The :exc:`MiddlewareNotUsed` exception is raised when a middleware is not\n    used in the server configuration.\n\n``ImproperlyConfigured``\n------------------------\n\n.. exception:: ImproperlyConfigured\n\n    The :exc:`ImproperlyConfigured` exception is raised when Django is\n    somehow improperly configured -- for example, if a value in ``settings.py``\n    is incorrect or unparseable.\n\n``FieldError``\n--------------\n\n.. exception:: FieldError\n\n    The :exc:`FieldError` exception is raised when there is a problem with a\n    model field. This can happen for several reasons:\n\n    - A field in a model clashes with a field of the same name from an\n      abstract base class\n    - An infinite loop is caused by ordering\n    - A keyword cannot be parsed from the filter parameters\n    - A field cannot be determined from a keyword in the query\n      parameters\n    - A join is not permitted on the specified field\n    - A field name is invalid\n    - A query contains invalid order_by arguments\n\n``ValidationError``\n-------------------\n\n.. exception:: ValidationError\n\n    The :exc:`ValidationError` exception is raised when data fails form or\n    model field validation. For more information about validation, see\n    :doc:`Form and Field Validation </ref/forms/validation>`,\n    :ref:`Model Field Validation <validating-objects>` and the\n    :doc:`Validator Reference </ref/validators>`.\n\n``NON_FIELD_ERRORS``\n~~~~~~~~~~~~~~~~~~~~\n\n.. data:: NON_FIELD_ERRORS\n\n``ValidationError``\\s that don't belong to a particular field in a form\nor model are classified as ``NON_FIELD_ERRORS``. This constant is used\nas a key in dictionaries that otherwise map fields to their respective\nlist of errors.\n\n``RequestAborted``\n------------------\n\n.. exception:: RequestAborted\n\n    The :exc:`RequestAborted` exception is raised when a HTTP body being read\n    in by the handler is cut off midstream and the client connection closes,\n    or when the client does not send data and hits a timeout where the server\n    closes the connection.\n\n    It is internal to the HTTP handler modules and you are unlikely to see\n    it elsewhere. If you are modifying HTTP handling code, you should raise\n    this when you encounter an aborted request to make sure the socket is\n    closed cleanly.\n\n``SynchronousOnlyOperation``\n----------------------------\n\n.. exception:: SynchronousOnlyOperation\n\n    The :exc:`SynchronousOnlyOperation` exception is raised when code that\n    is only allowed in synchronous Python code is called from an asynchronous\n    context (a thread with a running asynchronous event loop). These parts of\n    Django are generally heavily reliant on thread-safety to function and don't\n    work correctly under coroutines sharing the same thread.\n\n    If you are trying to call code that is synchronous-only from an\n    asynchronous thread, then create a synchronous thread and call it in that.\n    You can accomplish this is with :func:`asgiref.sync.sync_to_async`.\n\n.. currentmodule:: django.urls\n\nURL Resolver exceptions\n=======================\n\nURL Resolver exceptions are defined in ``django.urls``.\n\n``Resolver404``\n---------------\n\n.. exception:: Resolver404\n\n    The :exc:`Resolver404` exception is raised by\n    :func:`~django.urls.resolve()` if the path passed to ``resolve()`` doesn't\n    map to a view. It's a subclass of :class:`django.http.Http404`.\n\n``NoReverseMatch``\n------------------\n\n.. exception:: NoReverseMatch\n\n    The :exc:`NoReverseMatch` exception is raised by :mod:`django.urls` when a\n    matching URL in your URLconf cannot be identified based on the parameters\n    supplied.\n\n.. currentmodule:: django.db\n\nDatabase Exceptions\n===================\n\nDatabase exceptions may be imported from ``django.db``.\n\nDjango wraps the standard database exceptions so that your Django code has a\nguaranteed common implementation of these classes.\n\n.. exception:: Error\n.. exception:: InterfaceError\n.. exception:: DatabaseError\n.. exception:: DataError\n.. exception:: OperationalError\n.. exception:: IntegrityError\n.. exception:: InternalError\n.. exception:: ProgrammingError\n.. exception:: NotSupportedError\n\nThe Django wrappers for database exceptions behave exactly the same as\nthe underlying database exceptions. See :pep:`249`, the Python Database API\nSpecification v2.0, for further information.\n\nAs per :pep:`3134`, a ``__cause__`` attribute is set with the original\n(underlying) database exception, allowing access to any additional\ninformation provided.\n\n.. exception:: models.ProtectedError\n\nRaised to prevent deletion of referenced objects when using\n:attr:`django.db.models.PROTECT`. :exc:`models.ProtectedError` is a subclass\nof :exc:`IntegrityError`.\n\n.. exception:: models.RestrictedError\n\nRaised to prevent deletion of referenced objects when using\n:attr:`django.db.models.RESTRICT`. :exc:`models.RestrictedError` is a subclass\nof :exc:`IntegrityError`.\n\n.. currentmodule:: django.http\n\nHttp Exceptions\n===============\n\nHttp exceptions may be imported from ``django.http``.\n\n``UnreadablePostError``\n-----------------------\n\n.. exception:: UnreadablePostError\n\n    :exc:`UnreadablePostError` is raised when a user cancels an upload.\n\nTransaction Exceptions\n======================\n\n.. currentmodule:: django.db.transaction\n\nTransaction exceptions are defined in ``django.db.transaction``.\n\n``TransactionManagementError``\n------------------------------\n\n.. exception:: TransactionManagementError\n\n    :exc:`TransactionManagementError` is raised for any and all problems\n    related to database transactions.\n\n.. currentmodule:: django.test\n\nTesting Framework Exceptions\n============================\n\nExceptions provided by the ``django.test`` package.\n\n``RedirectCycleError``\n----------------------\n\n.. exception:: client.RedirectCycleError\n\n    :exc:`~client.RedirectCycleError` is raised when the test client detects a\n    loop or an overly long chain of redirects.\n\nPython Exceptions\n=================\n\nDjango raises built-in Python exceptions when appropriate as well. See the\nPython documentation for further information on the :ref:`bltin-exceptions`.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":38,"nodeType":"TextFile","repoName":null,"name":"request-response.txt","path":"docs/ref","text":"============================\nRequest and response objects\n============================\n\n.. module:: django.http\n   :synopsis: Classes dealing with HTTP requests and responses.\n\nQuick overview\n==============\n\nDjango uses request and response objects to pass state through the system.\n\nWhen a page is requested, Django creates an :class:`HttpRequest` object that\ncontains metadata about the request. Then Django loads the appropriate view,\npassing the :class:`HttpRequest` as the first argument to the view function.\nEach view is responsible for returning an :class:`HttpResponse` object.\n\nThis document explains the APIs for :class:`HttpRequest` and\n:class:`HttpResponse` objects, which are defined in the :mod:`django.http`\nmodule.\n\n``HttpRequest`` objects\n=======================\n\n.. class:: HttpRequest\n\n.. _httprequest-attributes:\n\nAttributes\n----------\n\nAll attributes should be considered read-only, unless stated otherwise.\n\n.. attribute:: HttpRequest.scheme\n\n    A string representing the scheme of the request (``http`` or ``https``\n    usually).\n\n.. attribute:: HttpRequest.body\n\n    The raw HTTP request body as a bytestring. This is useful for processing\n    data in different ways than conventional HTML forms: binary images,\n    XML payload etc. For processing conventional form data, use\n    :attr:`HttpRequest.POST`.\n\n    You can also read from an ``HttpRequest`` using a file-like interface. See\n    :meth:`HttpRequest.read()`.\n\n.. attribute:: HttpRequest.path\n\n    A string representing the full path to the requested page, not including\n    the scheme or domain.\n\n    Example: ``\"/music/bands/the_beatles/\"``\n\n.. attribute:: HttpRequest.path_info\n\n    Under some Web server configurations, the portion of the URL after the\n    host name is split up into a script prefix portion and a path info\n    portion. The ``path_info`` attribute always contains the path info portion\n    of the path, no matter what Web server is being used. Using this instead\n    of :attr:`~HttpRequest.path` can make your code easier to move between\n    test and deployment servers.\n\n    For example, if the ``WSGIScriptAlias`` for your application is set to\n    ``\"/minfo\"``, then ``path`` might be ``\"/minfo/music/bands/the_beatles/\"``\n    and ``path_info`` would be ``\"/music/bands/the_beatles/\"``.\n\n.. attribute:: HttpRequest.method\n\n    A string representing the HTTP method used in the request. This is\n    guaranteed to be uppercase. For example::\n\n        if request.method == 'GET':\n            do_something()\n        elif request.method == 'POST':\n            do_something_else()\n\n.. attribute:: HttpRequest.encoding\n\n    A string representing the current encoding used to decode form submission\n    data (or ``None``, which means the :setting:`DEFAULT_CHARSET` setting is\n    used). You can write to this attribute to change the encoding used when\n    accessing the form data. Any subsequent attribute accesses (such as reading\n    from :attr:`GET` or :attr:`POST`) will use the new ``encoding`` value.\n    Useful if you know the form data is not in the :setting:`DEFAULT_CHARSET`\n    encoding.\n\n.. attribute:: HttpRequest.content_type\n\n    A string representing the MIME type of the request, parsed from the\n    ``CONTENT_TYPE`` header.\n\n.. attribute:: HttpRequest.content_params\n\n    A dictionary of key/value parameters included in the ``CONTENT_TYPE``\n    header.\n\n.. attribute:: HttpRequest.GET\n\n    A dictionary-like object containing all given HTTP GET parameters. See the\n    :class:`QueryDict` documentation below.\n\n.. attribute:: HttpRequest.POST\n\n    A dictionary-like object containing all given HTTP POST parameters,\n    providing that the request contains form data. See the\n    :class:`QueryDict` documentation below. If you need to access raw or\n    non-form data posted in the request, access this through the\n    :attr:`HttpRequest.body` attribute instead.\n\n    It's possible that a request can come in via POST with an empty ``POST``\n    dictionary -- if, say, a form is requested via the POST HTTP method but\n    does not include form data. Therefore, you shouldn't use ``if request.POST``\n    to check for use of the POST method; instead, use ``if request.method ==\n    \"POST\"`` (see :attr:`HttpRequest.method`).\n\n    ``POST`` does *not* include file-upload information. See :attr:`FILES`.\n\n.. attribute:: HttpRequest.COOKIES\n\n    A dictionary containing all cookies. Keys and values are strings.\n\n.. attribute:: HttpRequest.FILES\n\n    A dictionary-like object containing all uploaded files. Each key in\n    ``FILES`` is the ``name`` from the ``<input type=\"file\" name=\"\">``. Each\n    value in ``FILES`` is an :class:`~django.core.files.uploadedfile.UploadedFile`.\n\n    See :doc:`/topics/files` for more information.\n\n    ``FILES`` will only contain data if the request method was POST and the\n    ``<form>`` that posted to the request had ``enctype=\"multipart/form-data\"``.\n    Otherwise, ``FILES`` will be a blank dictionary-like object.\n\n.. attribute:: HttpRequest.META\n\n    A dictionary containing all available HTTP headers. Available headers\n    depend on the client and server, but here are some examples:\n\n    * ``CONTENT_LENGTH`` -- The length of the request body (as a string).\n    * ``CONTENT_TYPE`` -- The MIME type of the request body.\n    * ``HTTP_ACCEPT`` -- Acceptable content types for the response.\n    * ``HTTP_ACCEPT_ENCODING`` -- Acceptable encodings for the response.\n    * ``HTTP_ACCEPT_LANGUAGE`` -- Acceptable languages for the response.\n    * ``HTTP_HOST`` -- The HTTP Host header sent by the client.\n    * ``HTTP_REFERER`` -- The referring page, if any.\n    * ``HTTP_USER_AGENT`` -- The client's user-agent string.\n    * ``QUERY_STRING`` -- The query string, as a single (unparsed) string.\n    * ``REMOTE_ADDR`` -- The IP address of the client.\n    * ``REMOTE_HOST`` -- The hostname of the client.\n    * ``REMOTE_USER`` -- The user authenticated by the Web server, if any.\n    * ``REQUEST_METHOD`` -- A string such as ``\"GET\"`` or ``\"POST\"``.\n    * ``SERVER_NAME`` -- The hostname of the server.\n    * ``SERVER_PORT`` -- The port of the server (as a string).\n\n    With the exception of ``CONTENT_LENGTH`` and ``CONTENT_TYPE``, as given\n    above, any HTTP headers in the request are converted to ``META`` keys by\n    converting all characters to uppercase, replacing any hyphens with\n    underscores and adding an ``HTTP_`` prefix to the name. So, for example, a\n    header called ``X-Bender`` would be mapped to the ``META`` key\n    ``HTTP_X_BENDER``.\n\n    Note that :djadmin:`runserver` strips all headers with underscores in the\n    name, so you won't see them in ``META``. This prevents header-spoofing\n    based on ambiguity between underscores and dashes both being normalizing to\n    underscores in WSGI environment variables. It matches the behavior of\n    Web servers like Nginx and Apache 2.4+.\n\n    :attr:`HttpRequest.headers` is a simpler way to access all HTTP-prefixed\n    headers, plus ``CONTENT_LENGTH`` and ``CONTENT_TYPE``.\n\n.. attribute:: HttpRequest.headers\n\n    A case insensitive, dict-like object that provides access to all\n    HTTP-prefixed headers (plus ``Content-Length`` and ``Content-Type``) from\n    the request.\n\n    The name of each header is stylized with title-casing (e.g. ``User-Agent``)\n    when it's displayed. You can access headers case-insensitively::\n\n        >>> request.headers\n        {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6', ...}\n\n        >>> 'User-Agent' in request.headers\n        True\n        >>> 'user-agent' in request.headers\n        True\n\n        >>> request.headers['User-Agent']\n        Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)\n        >>> request.headers['user-agent']\n        Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)\n\n        >>> request.headers.get('User-Agent')\n        Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)\n        >>> request.headers.get('user-agent')\n        Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)\n\n    For use in, for example, Django templates, headers can also be looked up\n    using underscores in place of hyphens::\n\n        {{ request.headers.user_agent }}\n\n.. attribute:: HttpRequest.resolver_match\n\n    An instance of :class:`~django.urls.ResolverMatch` representing the\n    resolved URL. This attribute is only set after URL resolving took place,\n    which means it's available in all views but not in middleware which are\n    executed before URL resolving takes place (you can use it in\n    :meth:`process_view` though).\n\nAttributes set by application code\n----------------------------------\n\nDjango doesn't set these attributes itself but makes use of them if set by your\napplication.\n\n.. attribute:: HttpRequest.current_app\n\n    The :ttag:`url` template tag will use its value as the ``current_app``\n    argument to :func:`~django.urls.reverse()`.\n\n.. attribute:: HttpRequest.urlconf\n\n    This will be used as the root URLconf for the current request, overriding\n    the :setting:`ROOT_URLCONF` setting. See\n    :ref:`how-django-processes-a-request` for details.\n\n    ``urlconf`` can be set to ``None`` to revert any changes made by previous\n    middleware and return to using the :setting:`ROOT_URLCONF`.\n\n.. attribute:: HttpRequest.exception_reporter_filter\n\n    This will be used instead of :setting:`DEFAULT_EXCEPTION_REPORTER_FILTER`\n    for the current request. See :ref:`custom-error-reports` for details.\n\n.. attribute:: HttpRequest.exception_reporter_class\n\n    This will be used instead of :setting:`DEFAULT_EXCEPTION_REPORTER` for the\n    current request. See :ref:`custom-error-reports` for details.\n\nAttributes set by middleware\n----------------------------\n\nSome of the middleware included in Django's contrib apps set attributes on the\nrequest. If you don't see the attribute on a request, be sure the appropriate\nmiddleware class is listed in :setting:`MIDDLEWARE`.\n\n.. attribute:: HttpRequest.session\n\n    From the :class:`~django.contrib.sessions.middleware.SessionMiddleware`: A\n    readable and writable, dictionary-like object that represents the current\n    session.\n\n.. attribute:: HttpRequest.site\n\n    From the :class:`~django.contrib.sites.middleware.CurrentSiteMiddleware`:\n    An instance of :class:`~django.contrib.sites.models.Site` or\n    :class:`~django.contrib.sites.requests.RequestSite` as returned by\n    :func:`~django.contrib.sites.shortcuts.get_current_site()`\n    representing the current site.\n\n.. attribute:: HttpRequest.user\n\n    From the :class:`~django.contrib.auth.middleware.AuthenticationMiddleware`:\n    An instance of :setting:`AUTH_USER_MODEL` representing the currently\n    logged-in user. If the user isn't currently logged in, ``user`` will be set\n    to an instance of :class:`~django.contrib.auth.models.AnonymousUser`. You\n    can tell them apart with\n    :attr:`~django.contrib.auth.models.User.is_authenticated`, like so::\n\n        if request.user.is_authenticated:\n            ... # Do something for logged-in users.\n        else:\n            ... # Do something for anonymous users.\n\nMethods\n-------\n\n.. method:: HttpRequest.get_host()\n\n    Returns the originating host of the request using information from the\n    ``HTTP_X_FORWARDED_HOST`` (if :setting:`USE_X_FORWARDED_HOST` is enabled)\n    and ``HTTP_HOST`` headers, in that order. If they don't provide a value,\n    the method uses a combination of ``SERVER_NAME`` and ``SERVER_PORT`` as\n    detailed in :pep:`3333`.\n\n    Example: ``\"127.0.0.1:8000\"``\n\n    .. note:: The :meth:`~HttpRequest.get_host()` method fails when the host is\n        behind multiple proxies. One solution is to use middleware to rewrite\n        the proxy headers, as in the following example::\n\n            class MultipleProxyMiddleware:\n                FORWARDED_FOR_FIELDS = [\n                    'HTTP_X_FORWARDED_FOR',\n                    'HTTP_X_FORWARDED_HOST',\n                    'HTTP_X_FORWARDED_SERVER',\n                ]\n\n                def __init__(self, get_response):\n                    self.get_response = get_response\n\n                def __call__(self, request):\n                    \"\"\"\n                    Rewrites the proxy headers so that only the most\n                    recent proxy is used.\n                    \"\"\"\n                    for field in self.FORWARDED_FOR_FIELDS:\n                        if field in request.META:\n                            if ',' in request.META[field]:\n                                parts = request.META[field].split(',')\n                                request.META[field] = parts[-1].strip()\n                    return self.get_response(request)\n\n        This middleware should be positioned before any other middleware that\n        relies on the value of :meth:`~HttpRequest.get_host()` -- for instance,\n        :class:`~django.middleware.common.CommonMiddleware` or\n        :class:`~django.middleware.csrf.CsrfViewMiddleware`.\n\n.. method:: HttpRequest.get_port()\n\n    Returns the originating port of the request using information from the\n    ``HTTP_X_FORWARDED_PORT`` (if :setting:`USE_X_FORWARDED_PORT` is enabled)\n    and ``SERVER_PORT`` ``META`` variables, in that order.\n\n.. method:: HttpRequest.get_full_path()\n\n    Returns the ``path``, plus an appended query string, if applicable.\n\n    Example: ``\"/music/bands/the_beatles/?print=true\"``\n\n.. method:: HttpRequest.get_full_path_info()\n\n    Like :meth:`get_full_path`, but uses :attr:`path_info` instead of\n    :attr:`path`.\n\n    Example: ``\"/minfo/music/bands/the_beatles/?print=true\"``\n\n.. method:: HttpRequest.build_absolute_uri(location=None)\n\n    Returns the absolute URI form of ``location``. If no location is provided,\n    the location will be set to ``request.get_full_path()``.\n\n    If the location is already an absolute URI, it will not be altered.\n    Otherwise the absolute URI is built using the server variables available in\n    this request. For example:\n\n    >>> request.build_absolute_uri()\n    'https://example.com/music/bands/the_beatles/?print=true'\n    >>> request.build_absolute_uri('/bands/')\n    'https://example.com/bands/'\n    >>> request.build_absolute_uri('https://example2.com/bands/')\n    'https://example2.com/bands/'\n\n    .. note::\n\n        Mixing HTTP and HTTPS on the same site is discouraged, therefore\n        :meth:`~HttpRequest.build_absolute_uri()` will always generate an\n        absolute URI with the same scheme the current request has. If you need\n        to redirect users to HTTPS, it's best to let your Web server redirect\n        all HTTP traffic to HTTPS.\n\n.. method:: HttpRequest.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None)\n\n    Returns a cookie value for a signed cookie, or raises a\n    ``django.core.signing.BadSignature`` exception if the signature is\n    no longer valid. If you provide the ``default`` argument the exception\n    will be suppressed and that default value will be returned instead.\n\n    The optional ``salt`` argument can be used to provide extra protection\n    against brute force attacks on your secret key. If supplied, the\n    ``max_age`` argument will be checked against the signed timestamp\n    attached to the cookie value to ensure the cookie is not older than\n    ``max_age`` seconds.\n\n    For example::\n\n        >>> request.get_signed_cookie('name')\n        'Tony'\n        >>> request.get_signed_cookie('name', salt='name-salt')\n        'Tony' # assuming cookie was set using the same salt\n        >>> request.get_signed_cookie('nonexistent-cookie')\n        ...\n        KeyError: 'nonexistent-cookie'\n        >>> request.get_signed_cookie('nonexistent-cookie', False)\n        False\n        >>> request.get_signed_cookie('cookie-that-was-tampered-with')\n        ...\n        BadSignature: ...\n        >>> request.get_signed_cookie('name', max_age=60)\n        ...\n        SignatureExpired: Signature age 1677.3839159 > 60 seconds\n        >>> request.get_signed_cookie('name', False, max_age=60)\n        False\n\n    See :doc:`cryptographic signing </topics/signing>` for more information.\n\n.. method:: HttpRequest.is_secure()\n\n    Returns ``True`` if the request is secure; that is, if it was made with\n    HTTPS.\n\n.. method:: HttpRequest.accepts(mime_type)\n\n    .. versionadded:: 3.1\n\n    Returns ``True`` if the request ``Accept`` header matches the ``mime_type``\n    argument::\n\n        >>> request.accepts('text/html')\n        True\n\n    Most browsers send ``Accept: */*`` by default, so this would return\n    ``True`` for all content types. Setting an explicit ``Accept`` header in\n    API requests can be useful for returning a different content type for those\n    consumers only. See :ref:`content-negotiation-example` of using\n    ``accepts()`` to return different content to API consumers.\n\n    If a response varies depending on the content of the ``Accept`` header and\n    you are using some form of caching like Django's :mod:`cache middleware\n    <django.middleware.cache>`, you should decorate the view with\n    :func:`vary_on_headers('Accept')\n    <django.views.decorators.vary.vary_on_headers>` so that the responses are\n    properly cached.\n\n.. method:: HttpRequest.is_ajax()\n\n    .. deprecated:: 3.1\n\n    Returns ``True`` if the request was made via an ``XMLHttpRequest``, by\n    checking the ``HTTP_X_REQUESTED_WITH`` header for the string\n    ``'XMLHttpRequest'``. Most modern JavaScript libraries send this header.\n    If you write your own ``XMLHttpRequest`` call (on the browser side), you'll\n    have to set this header manually if you want ``is_ajax()`` to work.\n\n    If a response varies on whether or not it's requested via AJAX and you are\n    using some form of caching like Django's :mod:`cache middleware\n    <django.middleware.cache>`, you should decorate the view with\n    :func:`vary_on_headers('X-Requested-With')\n    <django.views.decorators.vary.vary_on_headers>` so that the responses are\n    properly cached.\n\n.. method:: HttpRequest.read(size=None)\n.. method:: HttpRequest.readline()\n.. method:: HttpRequest.readlines()\n.. method:: HttpRequest.__iter__()\n\n    Methods implementing a file-like interface for reading from an\n    ``HttpRequest`` instance. This makes it possible to consume an incoming\n    request in a streaming fashion. A common use-case would be to process a\n    big XML payload with an iterative parser without constructing a whole\n    XML tree in memory.\n\n    Given this standard interface, an ``HttpRequest`` instance can be\n    passed directly to an XML parser such as\n    :class:`~xml.etree.ElementTree.ElementTree`::\n\n        import xml.etree.ElementTree as ET\n        for element in ET.iterparse(request):\n            process(element)\n\n\n``QueryDict`` objects\n=====================\n\n.. class:: QueryDict\n\nIn an :class:`HttpRequest` object, the :attr:`~HttpRequest.GET` and\n:attr:`~HttpRequest.POST` attributes are instances of ``django.http.QueryDict``,\na dictionary-like class customized to deal with multiple values for the same\nkey. This is necessary because some HTML form elements, notably\n``<select multiple>``, pass multiple values for the same key.\n\nThe ``QueryDict``\\ s at ``request.POST`` and ``request.GET`` will be immutable\nwhen accessed in a normal request/response cycle. To get a mutable version you\nneed to use :meth:`QueryDict.copy`.\n\nMethods\n-------\n\n:class:`QueryDict` implements all the standard dictionary methods because it's\na subclass of dictionary. Exceptions are outlined here:\n\n.. method:: QueryDict.__init__(query_string=None, mutable=False, encoding=None)\n\n    Instantiates a ``QueryDict`` object based on ``query_string``.\n\n    >>> QueryDict('a=1&a=2&c=3')\n    <QueryDict: {'a': ['1', '2'], 'c': ['3']}>\n\n    If ``query_string`` is not passed in, the resulting ``QueryDict`` will be\n    empty (it will have no keys or values).\n\n    Most ``QueryDict``\\ s you encounter, and in particular those at\n    ``request.POST`` and ``request.GET``, will be immutable. If you are\n    instantiating one yourself, you can make it mutable by passing\n    ``mutable=True`` to its ``__init__()``.\n\n    Strings for setting both keys and values will be converted from ``encoding``\n    to ``str``. If ``encoding`` is not set, it defaults to\n    :setting:`DEFAULT_CHARSET`.\n\n.. classmethod:: QueryDict.fromkeys(iterable, value='', mutable=False, encoding=None)\n\n    Creates a new ``QueryDict`` with keys from ``iterable`` and each value\n    equal to ``value``. For example::\n\n        >>> QueryDict.fromkeys(['a', 'a', 'b'], value='val')\n        <QueryDict: {'a': ['val', 'val'], 'b': ['val']}>\n\n.. method:: QueryDict.__getitem__(key)\n\n    Returns the value for the given key. If the key has more than one value,\n    it returns the last value. Raises\n    ``django.utils.datastructures.MultiValueDictKeyError`` if the key does not\n    exist. (This is a subclass of Python's standard :exc:`KeyError`, so you can\n    stick to catching ``KeyError``.)\n\n.. method:: QueryDict.__setitem__(key, value)\n\n    Sets the given key to ``[value]`` (a list whose single element is\n    ``value``). Note that this, as other dictionary functions that have side\n    effects, can only be called on a mutable ``QueryDict`` (such as one that\n    was created via :meth:`QueryDict.copy`).\n\n.. method:: QueryDict.__contains__(key)\n\n    Returns ``True`` if the given key is set. This lets you do, e.g., ``if \"foo\"\n    in request.GET``.\n\n.. method:: QueryDict.get(key, default=None)\n\n    Uses the same logic as :meth:`__getitem__`, with a hook for returning a\n    default value if the key doesn't exist.\n\n.. method:: QueryDict.setdefault(key, default=None)\n\n    Like :meth:`dict.setdefault`, except it uses :meth:`__setitem__` internally.\n\n.. method:: QueryDict.update(other_dict)\n\n    Takes either a ``QueryDict`` or a dictionary. Like :meth:`dict.update`,\n    except it *appends* to the current dictionary items rather than replacing\n    them. For example::\n\n        >>> q = QueryDict('a=1', mutable=True)\n        >>> q.update({'a': '2'})\n        >>> q.getlist('a')\n        ['1', '2']\n        >>> q['a'] # returns the last\n        '2'\n\n.. method:: QueryDict.items()\n\n    Like :meth:`dict.items`, except this uses the same last-value logic as\n    :meth:`__getitem__` and returns an iterator object instead of a view object.\n    For example::\n\n        >>> q = QueryDict('a=1&a=2&a=3')\n        >>> list(q.items())\n        [('a', '3')]\n\n.. method:: QueryDict.values()\n\n    Like :meth:`dict.values`, except this uses the same last-value logic as\n    :meth:`__getitem__` and returns an iterator instead of a view object. For\n    example::\n\n        >>> q = QueryDict('a=1&a=2&a=3')\n        >>> list(q.values())\n        ['3']\n\nIn addition, ``QueryDict`` has the following methods:\n\n.. method:: QueryDict.copy()\n\n    Returns a copy of the object using :func:`copy.deepcopy`. This copy will\n    be mutable even if the original was not.\n\n.. method:: QueryDict.getlist(key, default=None)\n\n    Returns a list of the data with the requested key. Returns an empty list if\n    the key doesn't exist and a default value wasn't provided. It's guaranteed\n    to return a list unless the default value provided isn't a list.\n\n.. method:: QueryDict.setlist(key, list_)\n\n    Sets the given key to ``list_`` (unlike :meth:`__setitem__`).\n\n.. method:: QueryDict.appendlist(key, item)\n\n    Appends an item to the internal list associated with key.\n\n.. method:: QueryDict.setlistdefault(key, default_list=None)\n\n    Like :meth:`setdefault`, except it takes a list of values instead of a\n    single value.\n\n.. method:: QueryDict.lists()\n\n    Like :meth:`items()`, except it includes all values, as a list, for each\n    member of the dictionary. For example::\n\n        >>> q = QueryDict('a=1&a=2&a=3')\n        >>> q.lists()\n        [('a', ['1', '2', '3'])]\n\n.. method:: QueryDict.pop(key)\n\n    Returns a list of values for the given key and removes them from the\n    dictionary. Raises ``KeyError`` if the key does not exist. For example::\n\n        >>> q = QueryDict('a=1&a=2&a=3', mutable=True)\n        >>> q.pop('a')\n        ['1', '2', '3']\n\n.. method:: QueryDict.popitem()\n\n    Removes an arbitrary member of the dictionary (since there's no concept\n    of ordering), and returns a two value tuple containing the key and a list\n    of all values for the key. Raises ``KeyError`` when called on an empty\n    dictionary. For example::\n\n        >>> q = QueryDict('a=1&a=2&a=3', mutable=True)\n        >>> q.popitem()\n        ('a', ['1', '2', '3'])\n\n.. method:: QueryDict.dict()\n\n    Returns a ``dict`` representation of ``QueryDict``. For every (key, list)\n    pair in ``QueryDict``, ``dict`` will have (key, item), where item is one\n    element of the list, using the same logic as :meth:`QueryDict.__getitem__`::\n\n        >>> q = QueryDict('a=1&a=3&a=5')\n        >>> q.dict()\n        {'a': '5'}\n\n.. method:: QueryDict.urlencode(safe=None)\n\n    Returns a string of the data in query string format. For example::\n\n        >>> q = QueryDict('a=2&b=3&b=5')\n        >>> q.urlencode()\n        'a=2&b=3&b=5'\n\n    Use the ``safe`` parameter to pass characters which don't require encoding.\n    For example::\n\n        >>> q = QueryDict(mutable=True)\n        >>> q['next'] = '/a&b/'\n        >>> q.urlencode(safe='/')\n        'next=/a%26b/'\n\n``HttpResponse`` objects\n========================\n\n.. class:: HttpResponse\n\nIn contrast to :class:`HttpRequest` objects, which are created automatically by\nDjango, :class:`HttpResponse` objects are your responsibility. Each view you\nwrite is responsible for instantiating, populating, and returning an\n:class:`HttpResponse`.\n\nThe :class:`HttpResponse` class lives in the :mod:`django.http` module.\n\nUsage\n-----\n\nPassing strings\n~~~~~~~~~~~~~~~\n\nTypical usage is to pass the contents of the page, as a string, bytestring,\nor :class:`memoryview`, to the :class:`HttpResponse` constructor::\n\n    >>> from django.http import HttpResponse\n    >>> response = HttpResponse(\"Here's the text of the Web page.\")\n    >>> response = HttpResponse(\"Text only, please.\", content_type=\"text/plain\")\n    >>> response = HttpResponse(b'Bytestrings are also accepted.')\n    >>> response = HttpResponse(memoryview(b'Memoryview as well.'))\n\nBut if you want to add content incrementally, you can use ``response`` as a\nfile-like object::\n\n    >>> response = HttpResponse()\n    >>> response.write(\"<p>Here's the text of the Web page.</p>\")\n    >>> response.write(\"<p>Here's another paragraph.</p>\")\n\nPassing iterators\n~~~~~~~~~~~~~~~~~\n\nFinally, you can pass ``HttpResponse`` an iterator rather than strings.\n``HttpResponse`` will consume the iterator immediately, store its content as a\nstring, and discard it. Objects with a ``close()`` method such as files and\ngenerators are immediately closed.\n\nIf you need the response to be streamed from the iterator to the client, you\nmust use the :class:`StreamingHttpResponse` class instead.\n\nSetting header fields\n~~~~~~~~~~~~~~~~~~~~~\n\nTo set or remove a header field in your response, treat it like a dictionary::\n\n    >>> response = HttpResponse()\n    >>> response['Age'] = 120\n    >>> del response['Age']\n\nNote that unlike a dictionary, ``del`` doesn't raise ``KeyError`` if the header\nfield doesn't exist.\n\nFor setting the ``Cache-Control`` and ``Vary`` header fields, it is recommended\nto use the :func:`~django.utils.cache.patch_cache_control` and\n:func:`~django.utils.cache.patch_vary_headers` methods from\n:mod:`django.utils.cache`, since these fields can have multiple, comma-separated\nvalues. The \"patch\" methods ensure that other values, e.g. added by a\nmiddleware, are not removed.\n\nHTTP header fields cannot contain newlines. An attempt to set a header field\ncontaining a newline character (CR or LF) will raise ``BadHeaderError``\n\nTelling the browser to treat the response as a file attachment\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nTo tell the browser to treat the response as a file attachment, use the\n``content_type`` argument and set the ``Content-Disposition`` header. For example,\nthis is how you might return a Microsoft Excel spreadsheet::\n\n    >>> response = HttpResponse(my_data, content_type='application/vnd.ms-excel')\n    >>> response['Content-Disposition'] = 'attachment; filename=\"foo.xls\"'\n\nThere's nothing Django-specific about the ``Content-Disposition`` header, but\nit's easy to forget the syntax, so we've included it here.\n\nAttributes\n----------\n\n.. attribute:: HttpResponse.content\n\n    A bytestring representing the content, encoded from a string if necessary.\n\n.. attribute:: HttpResponse.charset\n\n    A string denoting the charset in which the response will be encoded. If not\n    given at ``HttpResponse`` instantiation time, it will be extracted from\n    ``content_type`` and if that is unsuccessful, the\n    :setting:`DEFAULT_CHARSET` setting will be used.\n\n.. attribute:: HttpResponse.status_code\n\n    The :rfc:`HTTP status code <7231#section-6>` for the response.\n\n    Unless :attr:`reason_phrase` is explicitly set, modifying the value of\n    ``status_code`` outside the constructor will also modify the value of\n    ``reason_phrase``.\n\n.. attribute:: HttpResponse.reason_phrase\n\n    The HTTP reason phrase for the response. It uses the :rfc:`HTTP standard's\n    <7231#section-6.1>` default reason phrases.\n\n    Unless explicitly set, ``reason_phrase`` is determined by the value of\n    :attr:`status_code`.\n\n.. attribute:: HttpResponse.streaming\n\n    This is always ``False``.\n\n    This attribute exists so middleware can treat streaming responses\n    differently from regular responses.\n\n.. attribute:: HttpResponse.closed\n\n    ``True`` if the response has been closed.\n\nMethods\n-------\n\n.. method:: HttpResponse.__init__(content=b'', content_type=None, status=200, reason=None, charset=None)\n\n    Instantiates an ``HttpResponse`` object with the given page content and\n    content type.\n\n    ``content`` is most commonly an iterator, bytestring, :class:`memoryview`,\n    or string. Other types will be converted to a bytestring by encoding their\n    string representation. Iterators should return strings or bytestrings and\n    those will be joined together to form the content of the response.\n\n    ``content_type`` is the MIME type optionally completed by a character set\n    encoding and is used to fill the HTTP ``Content-Type`` header. If not\n    specified, it is formed by ``'text/html'`` and the\n    :setting:`DEFAULT_CHARSET` settings, by default:\n    ``\"text/html; charset=utf-8\"``.\n\n    ``status`` is the :rfc:`HTTP status code <7231#section-6>` for the response.\n    You can use Python's :py:class:`http.HTTPStatus` for meaningful aliases,\n    such as ``HTTPStatus.NO_CONTENT``.\n\n    ``reason`` is the HTTP response phrase. If not provided, a default phrase\n    will be used.\n\n    ``charset`` is the charset in which the response will be encoded. If not\n    given it will be extracted from ``content_type``, and if that\n    is unsuccessful, the :setting:`DEFAULT_CHARSET` setting will be used.\n\n.. method:: HttpResponse.__setitem__(header, value)\n\n    Sets the given header name to the given value. Both ``header`` and\n    ``value`` should be strings.\n\n.. method:: HttpResponse.__delitem__(header)\n\n    Deletes the header with the given name. Fails silently if the header\n    doesn't exist. Case-insensitive.\n\n.. method:: HttpResponse.__getitem__(header)\n\n    Returns the value for the given header name. Case-insensitive.\n\n.. method:: HttpResponse.has_header(header)\n\n    Returns ``True`` or ``False`` based on a case-insensitive check for a\n    header with the given name.\n\n.. method:: HttpResponse.setdefault(header, value)\n\n    Sets a header unless it has already been set.\n\n.. method:: HttpResponse.set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None)\n\n    Sets a cookie. The parameters are the same as in the\n    :class:`~http.cookies.Morsel` cookie object in the Python standard library.\n\n    * ``max_age`` should be a number of seconds, or ``None`` (default) if\n      the cookie should last only as long as the client's browser session.\n      If ``expires`` is not specified, it will be calculated.\n    * ``expires`` should either be a string in the format\n      ``\"Wdy, DD-Mon-YY HH:MM:SS GMT\"`` or a ``datetime.datetime`` object\n      in UTC. If ``expires`` is a ``datetime`` object, the ``max_age``\n      will be calculated.\n    * Use ``domain`` if you want to set a cross-domain cookie. For example,\n      ``domain=\"example.com\"`` will set a cookie that is readable by the\n      domains www.example.com, blog.example.com, etc. Otherwise, a cookie will\n      only be readable by the domain that set it.\n    * Use ``secure=True`` if you want the cookie to be only sent to the server\n      when a request is made with the ``https`` scheme.\n    * Use ``httponly=True`` if you want to prevent client-side\n      JavaScript from having access to the cookie.\n\n      HttpOnly_ is a flag included in a Set-Cookie HTTP response header. It's\n      part of the :rfc:`RFC 6265 <6265#section-4.1.2.6>` standard for cookies\n      and can be a useful way to mitigate the risk of a client-side script\n      accessing the protected cookie data.\n    * Use ``samesite='Strict'`` or ``samesite='Lax'`` to tell the browser not\n      to send this cookie when performing a cross-origin request. `SameSite`_\n      isn't supported by all browsers, so it's not a replacement for Django's\n      CSRF protection, but rather a defense in depth measure.\n\n      Use ``samesite='None'`` (string) to explicitly state that this cookie is\n      sent with all same-site and cross-site requests.\n\n    .. _HttpOnly: https://www.owasp.org/index.php/HttpOnly\n    .. _SameSite: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite\n\n    .. versionchanged:: 3.1\n\n        Using ``samesite='None'`` (string) was allowed.\n\n    .. warning::\n\n        :rfc:`RFC 6265 <6265#section-6.1>` states that user agents should\n        support cookies of at least 4096 bytes. For many browsers this is also\n        the maximum size. Django will not raise an exception if there's an\n        attempt to store a cookie of more than 4096 bytes, but many browsers\n        will not set the cookie correctly.\n\n.. method:: HttpResponse.set_signed_cookie(key, value, salt='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None)\n\n    Like :meth:`~HttpResponse.set_cookie()`, but\n    :doc:`cryptographic signing </topics/signing>` the cookie before setting\n    it. Use in conjunction with :meth:`HttpRequest.get_signed_cookie`.\n    You can use the optional ``salt`` argument for added key strength, but\n    you will need to remember to pass it to the corresponding\n    :meth:`HttpRequest.get_signed_cookie` call.\n\n    .. versionchanged:: 3.1\n\n        Using ``samesite='None'`` (string) was allowed.\n\n.. method:: HttpResponse.delete_cookie(key, path='/', domain=None)\n\n    Deletes the cookie with the given key. Fails silently if the key doesn't\n    exist.\n\n    Due to the way cookies work, ``path`` and ``domain`` should be the same\n    values you used in ``set_cookie()`` -- otherwise the cookie may not be\n    deleted.\n\n.. method:: HttpResponse.close()\n\n    This method is called at the end of the request directly by the WSGI\n    server.\n\n.. method:: HttpResponse.write(content)\n\n    This method makes an :class:`HttpResponse` instance a file-like object.\n\n.. method:: HttpResponse.flush()\n\n    This method makes an :class:`HttpResponse` instance a file-like object.\n\n.. method:: HttpResponse.tell()\n\n    This method makes an :class:`HttpResponse` instance a file-like object.\n\n.. method:: HttpResponse.getvalue()\n\n    Returns the value of :attr:`HttpResponse.content`. This method makes\n    an :class:`HttpResponse` instance a stream-like object.\n\n.. method:: HttpResponse.readable()\n\n    Always ``False``. This method makes an :class:`HttpResponse` instance a\n    stream-like object.\n\n.. method:: HttpResponse.seekable()\n\n    Always ``False``. This method makes an :class:`HttpResponse` instance a\n    stream-like object.\n\n.. method:: HttpResponse.writable()\n\n    Always ``True``. This method makes an :class:`HttpResponse` instance a\n    stream-like object.\n\n.. method:: HttpResponse.writelines(lines)\n\n    Writes a list of lines to the response. Line separators are not added. This\n    method makes an :class:`HttpResponse` instance a stream-like object.\n\n.. _ref-httpresponse-subclasses:\n\n``HttpResponse`` subclasses\n---------------------------\n\nDjango includes a number of ``HttpResponse`` subclasses that handle different\ntypes of HTTP responses. Like ``HttpResponse``, these subclasses live in\n:mod:`django.http`.\n\n.. class:: HttpResponseRedirect\n\n    The first argument to the constructor is required -- the path to redirect\n    to. This can be a fully qualified URL\n    (e.g. ``'https://www.yahoo.com/search/'``), an absolute path with no domain\n    (e.g. ``'/search/'``), or even a relative path (e.g. ``'search/'``). In that\n    last case, the client browser will reconstruct the full URL itself\n    according to the current path. See :class:`HttpResponse` for other optional\n    constructor arguments. Note that this returns an HTTP status code 302.\n\n    .. attribute:: HttpResponseRedirect.url\n\n        This read-only attribute represents the URL the response will redirect\n        to (equivalent to the ``Location`` response header).\n\n.. class:: HttpResponsePermanentRedirect\n\n    Like :class:`HttpResponseRedirect`, but it returns a permanent redirect\n    (HTTP status code 301) instead of a \"found\" redirect (status code 302).\n\n.. class:: HttpResponseNotModified\n\n    The constructor doesn't take any arguments and no content should be added\n    to this response. Use this to designate that a page hasn't been modified\n    since the user's last request (status code 304).\n\n.. class:: HttpResponseBadRequest\n\n    Acts just like :class:`HttpResponse` but uses a 400 status code.\n\n.. class:: HttpResponseNotFound\n\n    Acts just like :class:`HttpResponse` but uses a 404 status code.\n\n.. class:: HttpResponseForbidden\n\n    Acts just like :class:`HttpResponse` but uses a 403 status code.\n\n.. class:: HttpResponseNotAllowed\n\n    Like :class:`HttpResponse`, but uses a 405 status code. The first argument\n    to the constructor is required: a list of permitted methods (e.g.\n    ``['GET', 'POST']``).\n\n.. class:: HttpResponseGone\n\n    Acts just like :class:`HttpResponse` but uses a 410 status code.\n\n.. class:: HttpResponseServerError\n\n    Acts just like :class:`HttpResponse` but uses a 500 status code.\n\n.. note::\n\n    If a custom subclass of :class:`HttpResponse` implements a ``render``\n    method, Django will treat it as emulating a\n    :class:`~django.template.response.SimpleTemplateResponse`, and the\n    ``render`` method must itself return a valid response object.\n\nCustom response classes\n~~~~~~~~~~~~~~~~~~~~~~~\n\nIf you find yourself needing a response class that Django doesn't provide, you\ncan create it with the help of :py:class:`http.HTTPStatus`. For example::\n\n    from http import HTTPStatus\n    from django.http import HttpResponse\n\n    class HttpResponseNoContent(HttpResponse):\n        status_code = HTTPStatus.NO_CONTENT\n\n``JsonResponse`` objects\n========================\n\n.. class:: JsonResponse(data, encoder=DjangoJSONEncoder, safe=True, json_dumps_params=None, **kwargs)\n\n    An :class:`HttpResponse` subclass that helps to create a JSON-encoded\n    response. It inherits most behavior from its superclass with a couple\n    differences:\n\n    Its default ``Content-Type`` header is set to :mimetype:`application/json`.\n\n    The first parameter, ``data``, should be a ``dict`` instance. If the\n    ``safe`` parameter is set to ``False`` (see below) it can be any\n    JSON-serializable object.\n\n    The ``encoder``, which defaults to\n    :class:`django.core.serializers.json.DjangoJSONEncoder`, will be used to\n    serialize the data. See :ref:`JSON serialization\n    <serialization-formats-json>` for more details about this serializer.\n\n    The ``safe`` boolean parameter defaults to ``True``. If it's set to\n    ``False``, any object can be passed for serialization (otherwise only\n    ``dict`` instances are allowed). If ``safe`` is ``True`` and a non-``dict``\n    object is passed as the first argument, a :exc:`TypeError` will be raised.\n\n    The ``json_dumps_params`` parameter is a dictionary of keyword arguments\n    to pass to the ``json.dumps()`` call used to generate the response.\n\nUsage\n-----\n\nTypical usage could look like::\n\n    >>> from django.http import JsonResponse\n    >>> response = JsonResponse({'foo': 'bar'})\n    >>> response.content\n    b'{\"foo\": \"bar\"}'\n\nSerializing non-dictionary objects\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIn order to serialize objects other than ``dict`` you must set the ``safe``\nparameter to ``False``::\n\n    >>> response = JsonResponse([1, 2, 3], safe=False)\n\nWithout passing ``safe=False``, a :exc:`TypeError` will be raised.\n\n.. warning::\n\n    Before the `5th edition of ECMAScript\n    <https://www.ecma-international.org/ecma-262/5.1/index.html#sec-11.1.4>`_\n    it was possible to poison the JavaScript ``Array`` constructor. For this\n    reason, Django does not allow passing non-dict objects to the\n    :class:`~django.http.JsonResponse` constructor by default.  However, most\n    modern browsers implement EcmaScript 5 which removes this attack vector.\n    Therefore it is possible to disable this security precaution.\n\nChanging the default JSON encoder\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf you need to use a different JSON encoder class you can pass the ``encoder``\nparameter to the constructor method::\n\n    >>> response = JsonResponse(data, encoder=MyJSONEncoder)\n\n.. _httpresponse-streaming:\n\n``StreamingHttpResponse`` objects\n=================================\n\n.. class:: StreamingHttpResponse\n\nThe :class:`StreamingHttpResponse` class is used to stream a response from\nDjango to the browser. You might want to do this if generating the response\ntakes too long or uses too much memory. For instance, it's useful for\n:ref:`generating large CSV files <streaming-csv-files>`.\n\n.. admonition:: Performance considerations\n\n    Django is designed for short-lived requests. Streaming responses will tie\n    a worker process for the entire duration of the response. This may result\n    in poor performance.\n\n    Generally speaking, you should perform expensive tasks outside of the\n    request-response cycle, rather than resorting to a streamed response.\n\nThe :class:`StreamingHttpResponse` is not a subclass of :class:`HttpResponse`,\nbecause it features a slightly different API. However, it is almost identical,\nwith the following notable differences:\n\n* It should be given an iterator that yields strings as content.\n\n* You cannot access its content, except by iterating the response object\n  itself. This should only occur when the response is returned to the client.\n\n* It has no ``content`` attribute. Instead, it has a\n  :attr:`~StreamingHttpResponse.streaming_content` attribute.\n\n* You cannot use the file-like object ``tell()`` or ``write()`` methods.\n  Doing so will raise an exception.\n\n:class:`StreamingHttpResponse` should only be used in situations where it is\nabsolutely required that the whole content isn't iterated before transferring\nthe data to the client. Because the content can't be accessed, many\nmiddleware can't function normally. For example the ``ETag`` and\n``Content-Length`` headers can't be generated for streaming responses.\n\nAttributes\n----------\n\n.. attribute:: StreamingHttpResponse.streaming_content\n\n    An iterator of the response content, bytestring encoded according to\n    :attr:`HttpResponse.charset`.\n\n.. attribute:: StreamingHttpResponse.status_code\n\n    The :rfc:`HTTP status code <7231#section-6>` for the response.\n\n    Unless :attr:`reason_phrase` is explicitly set, modifying the value of\n    ``status_code`` outside the constructor will also modify the value of\n    ``reason_phrase``.\n\n.. attribute:: StreamingHttpResponse.reason_phrase\n\n    The HTTP reason phrase for the response. It uses the :rfc:`HTTP standard's\n    <7231#section-6.1>` default reason phrases.\n\n    Unless explicitly set, ``reason_phrase`` is determined by the value of\n    :attr:`status_code`.\n\n.. attribute:: StreamingHttpResponse.streaming\n\n    This is always ``True``.\n\n``FileResponse`` objects\n========================\n\n.. class:: FileResponse(open_file, as_attachment=False, filename='', **kwargs)\n\n    :class:`FileResponse` is a subclass of :class:`StreamingHttpResponse`\n    optimized for binary files. It uses :pep:`wsgi.file_wrapper\n    <3333#optional-platform-specific-file-handling>` if provided by the wsgi\n    server, otherwise it streams the file out in small chunks.\n\n    If ``as_attachment=True``, the ``Content-Disposition`` header is set to\n    ``attachment``, which asks the browser to offer the file to the user as a\n    download. Otherwise, a ``Content-Disposition`` header with a value of\n    ``inline`` (the browser default) will be set only if a filename is\n    available.\n\n    If ``open_file`` doesn't have a name or if the name of ``open_file`` isn't\n    appropriate, provide a custom file name using the ``filename``  parameter.\n    Note that if you pass a file-like object like ``io.BytesIO``, it's your\n    task to ``seek()`` it before passing it to ``FileResponse``.\n\n    The ``Content-Length`` and ``Content-Type`` headers are automatically set\n    when they can be guessed from contents of ``open_file``.\n\n``FileResponse`` accepts any file-like object with binary content, for example\na file open in binary mode like so::\n\n    >>> from django.http import FileResponse\n    >>> response = FileResponse(open('myfile.png', 'rb'))\n\nThe file will be closed automatically, so don't open it with a context manager.\n\nMethods\n-------\n\n.. method:: FileResponse.set_headers(open_file)\n\n    This method is automatically called during the response initialization and\n    set various headers (``Content-Length``, ``Content-Type``, and\n    ``Content-Disposition``) depending on ``open_file``.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":39,"nodeType":"TextFile","repoName":null,"name":"clickjacking.txt","path":"docs/ref","text":"========================\nClickjacking Protection\n========================\n\n.. module:: django.middleware.clickjacking\n   :synopsis: Protects against Clickjacking\n\nThe clickjacking middleware and decorators provide easy-to-use protection\nagainst `clickjacking`_.  This type of attack occurs when a malicious site\ntricks a user into clicking on a concealed element of another site which they\nhave loaded in a hidden frame or iframe.\n\n.. _clickjacking: https://en.wikipedia.org/wiki/Clickjacking\n\nAn example of clickjacking\n==========================\n\nSuppose an online store has a page where a logged in user can click \"Buy Now\" to\npurchase an item. A user has chosen to stay logged into the store all the time\nfor convenience. An attacker site might create an \"I Like Ponies\" button on one\nof their own pages, and load the store's page in a transparent iframe such that\nthe \"Buy Now\" button is invisibly overlaid on the \"I Like Ponies\" button. If the\nuser visits the attacker's site, clicking \"I Like Ponies\" will cause an\ninadvertent click on the \"Buy Now\" button and an unknowing purchase of the item.\n\n.. _clickjacking-prevention:\n\nPreventing clickjacking\n=======================\n\nModern browsers honor the `X-Frame-Options`_ HTTP header that indicates whether\nor not a resource is allowed to load within a frame or iframe. If the response\ncontains the header with a value of ``SAMEORIGIN`` then the browser will only\nload the resource in a frame if the request originated from the same site. If\nthe header is set to ``DENY`` then the browser will block the resource from\nloading in a frame no matter which site made the request.\n\n.. _X-Frame-Options: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options\n\nDjango provides a few ways to include this header in responses from your site:\n\n#. A middleware that sets the header in all responses.\n\n#. A set of view decorators that can be used to override the middleware or to\n   only set the header for certain views.\n\nThe ``X-Frame-Options`` HTTP header will only be set by the middleware or view\ndecorators if it is not already present in the response.\n\nHow to use it\n=============\n\nSetting ``X-Frame-Options`` for all responses\n---------------------------------------------\n\nTo set the same ``X-Frame-Options`` value for all responses in your site, put\n``'django.middleware.clickjacking.XFrameOptionsMiddleware'`` to\n:setting:`MIDDLEWARE`::\n\n    MIDDLEWARE = [\n        ...\n        'django.middleware.clickjacking.XFrameOptionsMiddleware',\n        ...\n    ]\n\nThis middleware is enabled in the settings file generated by\n:djadmin:`startproject`.\n\nBy default, the middleware will set the ``X-Frame-Options`` header to\n``DENY`` for every outgoing ``HttpResponse``. If you want any other value for\nthis header instead, set the :setting:`X_FRAME_OPTIONS` setting::\n\n    X_FRAME_OPTIONS = 'SAMEORIGIN'\n\nWhen using the middleware there may be some views where you do **not** want the\n``X-Frame-Options`` header set. For those cases, you can use a view decorator\nthat tells the middleware not to set the header::\n\n    from django.http import HttpResponse\n    from django.views.decorators.clickjacking import xframe_options_exempt\n\n    @xframe_options_exempt\n    def ok_to_load_in_a_frame(request):\n        return HttpResponse(\"This page is safe to load in a frame on any site.\")\n\n.. note::\n\n    If you want to submit a form or access a session cookie within a frame or\n    iframe, you may need to modify the :setting:`CSRF_COOKIE_SAMESITE` or\n    :setting:`SESSION_COOKIE_SAMESITE` settings.\n\nSetting ``X-Frame-Options`` per view\n------------------------------------\n\nTo set the ``X-Frame-Options`` header on a per view basis, Django provides these\ndecorators::\n\n    from django.http import HttpResponse\n    from django.views.decorators.clickjacking import xframe_options_deny\n    from django.views.decorators.clickjacking import xframe_options_sameorigin\n\n    @xframe_options_deny\n    def view_one(request):\n        return HttpResponse(\"I won't display in any frame!\")\n\n    @xframe_options_sameorigin\n    def view_two(request):\n        return HttpResponse(\"Display in a frame if it's from the same origin as me.\")\n\nNote that you can use the decorators in conjunction with the middleware. Use of\na decorator overrides the middleware.\n\nLimitations\n===========\n\nThe ``X-Frame-Options`` header will only protect against clickjacking in a\nmodern browser. Older browsers will quietly ignore the header and need `other\nclickjacking prevention techniques`_.\n\nBrowsers that support ``X-Frame-Options``\n-----------------------------------------\n\n* Internet Explorer 8+\n* Edge\n* Firefox 3.6.9+\n* Opera 10.5+\n* Safari 4+\n* Chrome 4.1+\n\nSee also\n--------\n\nA `complete list`_ of browsers supporting ``X-Frame-Options``.\n\n.. _complete list: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options#Browser_compatibility\n.. _other clickjacking prevention techniques: https://en.wikipedia.org/wiki/Clickjacking#Prevention\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":40,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/ref","text":"=============\nAPI Reference\n=============\n\n.. toctree::\n   :maxdepth: 1\n\n   applications\n   checks\n   class-based-views/index\n   clickjacking\n   contrib/index\n   csrf\n   databases\n   django-admin\n   exceptions\n   files/index\n   forms/index\n   middleware\n   migration-operations\n   models/index\n   paginator\n   request-response\n   schema-editor\n   settings\n   signals\n   templates/index\n   template-response\n   unicode\n   urlresolvers\n   urls\n   utils\n   validators\n   views\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":41,"nodeType":"TextFile","repoName":null,"name":"databases.txt","path":"docs/ref","text":"=========\nDatabases\n=========\n\nDjango officially supports the following databases:\n\n* :ref:`PostgreSQL <postgresql-notes>`\n* :ref:`MariaDB <mariadb-notes>`\n* :ref:`MySQL <mysql-notes>`\n* :ref:`Oracle <oracle-notes>`\n* :ref:`SQLite <sqlite-notes>`\n\nThere are also a number of :ref:`database backends provided by third parties\n<third-party-notes>`.\n\nDjango attempts to support as many features as possible on all database\nbackends. However, not all database backends are alike, and we've had to make\ndesign decisions on which features to support and which assumptions we can make\nsafely.\n\nThis file describes some of the features that might be relevant to Django\nusage. It is not intended as a replacement for server-specific documentation or\nreference manuals.\n\nGeneral notes\n=============\n\n.. _persistent-database-connections:\n\nPersistent connections\n----------------------\n\nPersistent connections avoid the overhead of re-establishing a connection to\nthe database in each request. They're controlled by the\n:setting:`CONN_MAX_AGE` parameter which defines the maximum lifetime of a\nconnection. It can be set independently for each database.\n\nThe default value is ``0``, preserving the historical behavior of closing the\ndatabase connection at the end of each request. To enable persistent\nconnections, set :setting:`CONN_MAX_AGE` to a positive integer of seconds. For\nunlimited persistent connections, set it to ``None``.\n\nConnection management\n~~~~~~~~~~~~~~~~~~~~~\n\nDjango opens a connection to the database when it first makes a database\nquery. It keeps this connection open and reuses it in subsequent requests.\nDjango closes the connection once it exceeds the maximum age defined by\n:setting:`CONN_MAX_AGE` or when it isn't usable any longer.\n\nIn detail, Django automatically opens a connection to the database whenever it\nneeds one and doesn't have one already — either because this is the first\nconnection, or because the previous connection was closed.\n\nAt the beginning of each request, Django closes the connection if it has\nreached its maximum age. If your database terminates idle connections after\nsome time, you should set :setting:`CONN_MAX_AGE` to a lower value, so that\nDjango doesn't attempt to use a connection that has been terminated by the\ndatabase server. (This problem may only affect very low traffic sites.)\n\nAt the end of each request, Django closes the connection if it has reached its\nmaximum age or if it is in an unrecoverable error state. If any database\nerrors have occurred while processing the requests, Django checks whether the\nconnection still works, and closes it if it doesn't. Thus, database errors\naffect at most one request; if the connection becomes unusable, the next\nrequest gets a fresh connection.\n\nCaveats\n~~~~~~~\n\nSince each thread maintains its own connection, your database must support at\nleast as many simultaneous connections as you have worker threads.\n\nSometimes a database won't be accessed by the majority of your views, for\nexample because it's the database of an external system, or thanks to caching.\nIn such cases, you should set :setting:`CONN_MAX_AGE` to a low value or even\n``0``, because it doesn't make sense to maintain a connection that's unlikely\nto be reused. This will help keep the number of simultaneous connections to\nthis database small.\n\nThe development server creates a new thread for each request it handles,\nnegating the effect of persistent connections. Don't enable them during\ndevelopment.\n\nWhen Django establishes a connection to the database, it sets up appropriate\nparameters, depending on the backend being used. If you enable persistent\nconnections, this setup is no longer repeated every request. If you modify\nparameters such as the connection's isolation level or time zone, you should\neither restore Django's defaults at the end of each request, force an\nappropriate value at the beginning of each request, or disable persistent\nconnections.\n\nEncoding\n--------\n\nDjango assumes that all databases use UTF-8 encoding. Using other encodings may\nresult in unexpected behavior such as \"value too long\" errors from your\ndatabase for data that is valid in Django. See the database specific notes\nbelow for information on how to set up your database correctly.\n\n.. _postgresql-notes:\n\nPostgreSQL notes\n================\n\nDjango supports PostgreSQL 9.6 and higher. `psycopg2`_ 2.5.4 or higher is\nrequired, though the latest release is recommended.\n\n.. _psycopg2: https://www.psycopg.org/\n\nPostgreSQL connection settings\n-------------------------------\n\nSee :setting:`HOST` for details.\n\nOptimizing PostgreSQL's configuration\n-------------------------------------\n\nDjango needs the following parameters for its database connections:\n\n- ``client_encoding``: ``'UTF8'``,\n- ``default_transaction_isolation``: ``'read committed'`` by default,\n  or the value set in the connection options (see below),\n- ``timezone``:\n    - when :setting:`USE_TZ` is ``True``, ``'UTC'`` by default, or the\n      :setting:`TIME_ZONE <DATABASE-TIME_ZONE>` value set for the connection,\n    - when :setting:`USE_TZ` is ``False``, the value of the global\n      :setting:`TIME_ZONE` setting.\n\nIf these parameters already have the correct values, Django won't set them for\nevery new connection, which improves performance slightly. You can configure\nthem directly in :file:`postgresql.conf` or more conveniently per database\nuser with `ALTER ROLE`_.\n\nDjango will work just fine without this optimization, but each new connection\nwill do some additional queries to set these parameters.\n\n.. _ALTER ROLE: https://www.postgresql.org/docs/current/sql-alterrole.html\n\n.. _database-isolation-level:\n\nIsolation level\n---------------\n\nLike PostgreSQL itself, Django defaults to the ``READ COMMITTED`` `isolation\nlevel`_. If you need a higher isolation level such as ``REPEATABLE READ`` or\n``SERIALIZABLE``, set it in the :setting:`OPTIONS` part of your database\nconfiguration in :setting:`DATABASES`::\n\n    import psycopg2.extensions\n\n    DATABASES = {\n        # ...\n        'OPTIONS': {\n            'isolation_level': psycopg2.extensions.ISOLATION_LEVEL_SERIALIZABLE,\n        },\n    }\n\n.. note::\n\n    Under higher isolation levels, your application should be prepared to\n    handle exceptions raised on serialization failures. This option is\n    designed for advanced uses.\n\n.. _isolation level: https://www.postgresql.org/docs/current/transaction-iso.html\n\nIndexes for ``varchar`` and ``text`` columns\n--------------------------------------------\n\nWhen specifying ``db_index=True`` on your model fields, Django typically\noutputs a single ``CREATE INDEX`` statement.  However, if the database type\nfor the field is either ``varchar`` or ``text`` (e.g., used by ``CharField``,\n``FileField``, and ``TextField``), then Django will create\nan additional index that uses an appropriate `PostgreSQL operator class`_\nfor the column.  The extra index is necessary to correctly perform\nlookups that use the ``LIKE`` operator in their SQL, as is done with the\n``contains`` and ``startswith`` lookup types.\n\n.. _PostgreSQL operator class: https://www.postgresql.org/docs/current/indexes-opclass.html\n\nMigration operation for adding extensions\n-----------------------------------------\n\nIf you need to add a PostgreSQL extension (like ``hstore``, ``postgis``, etc.)\nusing a migration, use the\n:class:`~django.contrib.postgres.operations.CreateExtension` operation.\n\n.. _postgresql-server-side-cursors:\n\nServer-side cursors\n-------------------\n\nWhen using :meth:`QuerySet.iterator()\n<django.db.models.query.QuerySet.iterator>`, Django opens a :ref:`server-side\ncursor <psycopg2:server-side-cursors>`. By default, PostgreSQL assumes that\nonly the first 10% of the results of cursor queries will be fetched. The query\nplanner spends less time planning the query and starts returning results\nfaster, but this could diminish performance if more than 10% of the results are\nretrieved. PostgreSQL's assumptions on the number of rows retrieved for a\ncursor query is controlled with the `cursor_tuple_fraction`_ option.\n\n.. _cursor_tuple_fraction: https://www.postgresql.org/docs/current/runtime-config-query.html#GUC-CURSOR-TUPLE-FRACTION\n\n.. _transaction-pooling-server-side-cursors:\n\nTransaction pooling and server-side cursors\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nUsing a connection pooler in transaction pooling mode (e.g. `PgBouncer`_)\nrequires disabling server-side cursors for that connection.\n\nServer-side cursors are local to a connection and remain open at the end of a\ntransaction when :setting:`AUTOCOMMIT <DATABASE-AUTOCOMMIT>` is ``True``. A\nsubsequent transaction may attempt to fetch more results from a server-side\ncursor. In transaction pooling mode, there's no guarantee that subsequent\ntransactions will use the same connection. If a different connection is used,\nan error is raised when the transaction references the server-side cursor,\nbecause server-side cursors are only accessible in the connection in which they\nwere created.\n\nOne solution is to disable server-side cursors for a connection in\n:setting:`DATABASES` by setting :setting:`DISABLE_SERVER_SIDE_CURSORS\n<DATABASE-DISABLE_SERVER_SIDE_CURSORS>` to ``True``.\n\nTo benefit from server-side cursors in transaction pooling mode, you could set\nup :doc:`another connection to the database </topics/db/multi-db>` in order to\nperform queries that use server-side cursors. This connection needs to either\nbe directly to the database or to a connection pooler in session pooling mode.\n\nAnother option is to wrap each ``QuerySet`` using server-side cursors in an\n:func:`~django.db.transaction.atomic` block, because it disables ``autocommit``\nfor the duration of the transaction. This way, the server-side cursor will only\nlive for the duration of the transaction.\n\n.. _PgBouncer: https://pgbouncer.github.io/\n\n.. _manually-specified-autoincrement-pk:\n\nManually-specifying values of auto-incrementing primary keys\n------------------------------------------------------------\n\nDjango uses PostgreSQL's `SERIAL data type`_ to store auto-incrementing primary\nkeys. A ``SERIAL`` column is populated with values from a `sequence`_ that\nkeeps track of the next available value. Manually assigning a value to an\nauto-incrementing field doesn't update the field's sequence, which might later\ncause a conflict. For example::\n\n    >>> from django.contrib.auth.models import User\n    >>> User.objects.create(username='alice', pk=1)\n    <User: alice>\n    >>> # The sequence hasn't been updated; its next value is 1.\n    >>> User.objects.create(username='bob')\n    ...\n    IntegrityError: duplicate key value violates unique constraint\n    \"auth_user_pkey\" DETAIL:  Key (id)=(1) already exists.\n\nIf you need to specify such values, reset the sequence afterwards to avoid\nreusing a value that's already in the table. The :djadmin:`sqlsequencereset`\nmanagement command generates the SQL statements to do that.\n\n.. _SERIAL data type: https://www.postgresql.org/docs/current/datatype-numeric.html#DATATYPE-SERIAL\n.. _sequence: https://www.postgresql.org/docs/current/sql-createsequence.html\n\nTest database templates\n-----------------------\n\nYou can use the :setting:`TEST['TEMPLATE'] <TEST_TEMPLATE>` setting to specify\na `template`_ (e.g. ``'template0'``) from which to create a test database.\n\n.. _template: https://www.postgresql.org/docs/current/sql-createdatabase.html\n\nSpeeding up test execution with non-durable settings\n----------------------------------------------------\n\nYou can speed up test execution times by `configuring PostgreSQL to be\nnon-durable <https://www.postgresql.org/docs/current/non-durability.html>`_.\n\n.. warning::\n\n    This is dangerous: it will make your database more susceptible to data loss\n    or corruption in the case of a server crash or power loss. Only use this on\n    a development machine where you can easily restore the entire contents of\n    all databases in the cluster.\n\n.. _mariadb-notes:\n\nMariaDB notes\n=============\n\nDjango supports MariaDB 10.2 and higher.\n\nTo use MariaDB, use the MySQL backend, which is shared between the two. See the\n:ref:`MySQL notes <mysql-notes>` for more details.\n\n.. _mysql-notes:\n\nMySQL notes\n===========\n\nVersion support\n---------------\n\nDjango supports MySQL 5.7 and higher.\n\nDjango's ``inspectdb`` feature uses the ``information_schema`` database, which\ncontains detailed data on all database schemas.\n\nDjango expects the database to support Unicode (UTF-8 encoding) and delegates to\nit the task of enforcing transactions and referential integrity. It is important\nto be aware of the fact that the two latter ones aren't actually enforced by\nMySQL when using the MyISAM storage engine, see the next section.\n\n.. _mysql-storage-engines:\n\nStorage engines\n---------------\n\nMySQL has several `storage engines`_. You can change the default storage engine\nin the server configuration.\n\nMySQL's default storage engine is InnoDB_. This engine is fully transactional\nand supports foreign key references. It's the recommended choice. However, the\nInnoDB autoincrement counter is lost on a MySQL restart because it does not\nremember the ``AUTO_INCREMENT`` value, instead recreating it as \"max(id)+1\".\nThis may result in an inadvertent reuse of :class:`~django.db.models.AutoField`\nvalues.\n\nThe main drawbacks of MyISAM_ are that it doesn't support transactions or\nenforce foreign-key constraints.\n\n.. _storage engines: https://dev.mysql.com/doc/refman/en/storage-engines.html\n.. _MyISAM: https://dev.mysql.com/doc/refman/en/myisam-storage-engine.html\n.. _InnoDB: https://dev.mysql.com/doc/refman/en/innodb-storage-engine.html\n\n.. _mysql-db-api-drivers:\n\nMySQL DB API Drivers\n--------------------\n\nMySQL has a couple drivers that implement the Python Database API described in\n:pep:`249`:\n\n- `mysqlclient`_ is a native driver. It's **the recommended choice**.\n- `MySQL Connector/Python`_ is a pure Python driver from Oracle that does not\n  require the MySQL client library or any Python modules outside the standard\n  library.\n\n.. _mysqlclient: https://pypi.org/project/mysqlclient/\n.. _MySQL Connector/Python: https://dev.mysql.com/downloads/connector/python\n\nThese drivers are thread-safe and provide connection pooling.\n\nIn addition to a DB API driver, Django needs an adapter to access the database\ndrivers from its ORM. Django provides an adapter for mysqlclient while MySQL\nConnector/Python includes `its own`_.\n\n.. _its own: https://dev.mysql.com/doc/connector-python/en/connector-python-django-backend.html\n\nmysqlclient\n~~~~~~~~~~~\n\nDjango requires `mysqlclient`_ 1.4.0 or later.\n\nMySQL Connector/Python\n~~~~~~~~~~~~~~~~~~~~~~\n\nMySQL Connector/Python is available from the `download page`_.\nThe Django adapter is available in versions 1.1.X and later. It may not\nsupport the most recent releases of Django.\n\n.. _download page: https://dev.mysql.com/downloads/connector/python/\n\n.. _mysql-time-zone-definitions:\n\nTime zone definitions\n---------------------\n\nIf you plan on using Django's :doc:`timezone support </topics/i18n/timezones>`,\nuse `mysql_tzinfo_to_sql`_ to load time zone tables into the MySQL database.\nThis needs to be done just once for your MySQL server, not per database.\n\n.. _mysql_tzinfo_to_sql: https://dev.mysql.com/doc/refman/en/mysql-tzinfo-to-sql.html\n\nCreating your database\n----------------------\n\nYou can `create your database`_ using the command-line tools and this SQL::\n\n  CREATE DATABASE <dbname> CHARACTER SET utf8;\n\nThis ensures all tables and columns will use UTF-8 by default.\n\n.. _create your database: https://dev.mysql.com/doc/refman/en/create-database.html\n\n.. _mysql-collation:\n\nCollation settings\n~~~~~~~~~~~~~~~~~~\n\nThe collation setting for a column controls the order in which data is sorted\nas well as what strings compare as equal. It can be set on a database-wide\nlevel and also per-table and per-column. This is `documented thoroughly`_ in\nthe MySQL documentation. In all cases, you set the collation by directly\nmanipulating the database tables; Django doesn't provide a way to set this on\nthe model definition.\n\n.. _documented thoroughly: https://dev.mysql.com/doc/refman/en/charset.html\n\nBy default, with a UTF-8 database, MySQL will use the\n``utf8_general_ci`` collation. This results in all string equality\ncomparisons being done in a *case-insensitive* manner. That is, ``\"Fred\"`` and\n``\"freD\"`` are considered equal at the database level. If you have a unique\nconstraint on a field, it would be illegal to try to insert both ``\"aa\"`` and\n``\"AA\"`` into the same column, since they compare as equal (and, hence,\nnon-unique) with the default collation. If you want case-sensitive comparisons\non a particular column or table, change the column or table to use the\n``utf8_bin`` collation.\n\nPlease note that according to `MySQL Unicode Character Sets`_, comparisons for\nthe ``utf8_general_ci`` collation are faster, but slightly less correct, than\ncomparisons for ``utf8_unicode_ci``. If this is acceptable for your application,\nyou should use ``utf8_general_ci`` because it is faster. If this is not acceptable\n(for example, if you require German dictionary order), use ``utf8_unicode_ci``\nbecause it is more accurate.\n\n.. _MySQL Unicode Character Sets: https://dev.mysql.com/doc/refman/en/charset-unicode-sets.html\n\n.. warning::\n\n    Model formsets validate unique fields in a case-sensitive manner. Thus when\n    using a case-insensitive collation, a formset with unique field values that\n    differ only by case will pass validation, but upon calling ``save()``, an\n    ``IntegrityError`` will be raised.\n\nConnecting to the database\n--------------------------\n\nRefer to the :doc:`settings documentation </ref/settings>`.\n\nConnection settings are used in this order:\n\n#. :setting:`OPTIONS`.\n#. :setting:`NAME`, :setting:`USER`, :setting:`PASSWORD`, :setting:`HOST`,\n   :setting:`PORT`\n#. MySQL option files.\n\nIn other words, if you set the name of the database in :setting:`OPTIONS`,\nthis will take precedence over :setting:`NAME`, which would override\nanything in a `MySQL option file`_.\n\nHere's a sample configuration which uses a MySQL option file::\n\n    # settings.py\n    DATABASES = {\n        'default': {\n            'ENGINE': 'django.db.backends.mysql',\n            'OPTIONS': {\n                'read_default_file': '/path/to/my.cnf',\n            },\n        }\n    }\n\n\n    # my.cnf\n    [client]\n    database = NAME\n    user = USER\n    password = PASSWORD\n    default-character-set = utf8\n\nSeveral other `MySQLdb connection options`_ may be useful, such as ``ssl``,\n``init_command``, and ``sql_mode``.\n\n.. _MySQL option file: https://dev.mysql.com/doc/refman/en/option-files.html\n.. _MySQLdb connection options: https://mysqlclient.readthedocs.io/user_guide.html#functions-and-attributes\n\n.. _mysql-sql-mode:\n\nSetting ``sql_mode``\n~~~~~~~~~~~~~~~~~~~~\n\nFrom MySQL 5.7 onwards, the default value of the ``sql_mode`` option contains\n``STRICT_TRANS_TABLES``. That option escalates warnings into errors when data\nare truncated upon insertion, so Django highly recommends activating a\n`strict mode`_ for MySQL to prevent data loss (either ``STRICT_TRANS_TABLES``\nor ``STRICT_ALL_TABLES``).\n\n.. _strict mode: https://dev.mysql.com/doc/refman/en/sql-mode.html#sql-mode-strict\n\nIf you need to customize the SQL mode, you can set the ``sql_mode`` variable\nlike other MySQL options: either in a config file or with the entry\n``'init_command': \"SET sql_mode='STRICT_TRANS_TABLES'\"`` in the\n:setting:`OPTIONS` part of your database configuration in :setting:`DATABASES`.\n\n.. _mysql-isolation-level:\n\nIsolation level\n~~~~~~~~~~~~~~~\n\nWhen running concurrent loads, database transactions from different sessions\n(say, separate threads handling different requests) may interact with each\nother. These interactions are affected by each session's `transaction isolation\nlevel`_. You can set a connection's isolation level with an\n``'isolation_level'`` entry in the :setting:`OPTIONS` part of your database\nconfiguration in :setting:`DATABASES`. Valid values for\nthis entry are the four standard isolation levels:\n\n* ``'read uncommitted'``\n* ``'read committed'``\n* ``'repeatable read'``\n* ``'serializable'``\n\nor ``None`` to use the server's configured isolation level. However, Django\nworks best with and defaults to read committed rather than MySQL's default,\nrepeatable read. Data loss is possible with repeatable read. In particular,\nyou may see cases where :meth:`~django.db.models.query.QuerySet.get_or_create`\nwill raise an :exc:`~django.db.IntegrityError` but the object won't appear in\na subsequent :meth:`~django.db.models.query.QuerySet.get` call.\n\n.. _transaction isolation level: https://dev.mysql.com/doc/refman/en/innodb-transaction-isolation-levels.html\n\nCreating your tables\n--------------------\n\nWhen Django generates the schema, it doesn't specify a storage engine, so\ntables will be created with whatever default storage engine your database\nserver is configured for. The easiest solution is to set your database server's\ndefault storage engine to the desired engine.\n\nIf you're using a hosting service and can't change your server's default\nstorage engine, you have a couple of options.\n\n* After the tables are created, execute an ``ALTER TABLE`` statement to\n  convert a table to a new storage engine (such as InnoDB)::\n\n      ALTER TABLE <tablename> ENGINE=INNODB;\n\n  This can be tedious if you have a lot of tables.\n\n* Another option is to use the ``init_command`` option for MySQLdb prior to\n  creating your tables::\n\n      'OPTIONS': {\n         'init_command': 'SET default_storage_engine=INNODB',\n      }\n\n  This sets the default storage engine upon connecting to the database.\n  After your tables have been created, you should remove this option as it\n  adds a query that is only needed during table creation to each database\n  connection.\n\nTable names\n-----------\n\nThere are `known issues`_ in even the latest versions of MySQL that can cause the\ncase of a table name to be altered when certain SQL statements are executed\nunder certain conditions. It is recommended that you use lowercase table\nnames, if possible, to avoid any problems that might arise from this behavior.\nDjango uses lowercase table names when it auto-generates table names from\nmodels, so this is mainly a consideration if you are overriding the table name\nvia the :class:`~django.db.models.Options.db_table` parameter.\n\n.. _known issues: https://bugs.mysql.com/bug.php?id=48875\n\nSavepoints\n----------\n\nBoth the Django ORM and MySQL (when using the InnoDB :ref:`storage engine\n<mysql-storage-engines>`) support database :ref:`savepoints\n<topics-db-transactions-savepoints>`.\n\nIf you use the MyISAM storage engine please be aware of the fact that you will\nreceive database-generated errors if you try to use the :ref:`savepoint-related\nmethods of the transactions API <topics-db-transactions-savepoints>`. The reason\nfor this is that detecting the storage engine of a MySQL database/table is an\nexpensive operation so it was decided it isn't worth to dynamically convert\nthese methods in no-op's based in the results of such detection.\n\nNotes on specific fields\n------------------------\n\n.. _mysql-character-fields:\n\nCharacter fields\n~~~~~~~~~~~~~~~~\n\nAny fields that are stored with ``VARCHAR`` column types may have their\n``max_length`` restricted to 255 characters if you are using ``unique=True``\nfor the field. This affects :class:`~django.db.models.CharField`,\n:class:`~django.db.models.SlugField`. See `the MySQL documentation`_ for more\ndetails.\n\n.. _the MySQL documentation: https://dev.mysql.com/doc/refman/en/create-index.html#create-index-column-prefixes\n\n``TextField`` limitations\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\nMySQL can index only the first N chars of a ``BLOB`` or ``TEXT`` column. Since\n``TextField`` doesn't have a defined length, you can't mark it as\n``unique=True``. MySQL will report: \"BLOB/TEXT column '<db_column>' used in key\nspecification without a key length\".\n\n.. _mysql-fractional-seconds:\n\nFractional seconds support for Time and DateTime fields\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nMySQL can store fractional seconds, provided that the column definition\nincludes a fractional indication (e.g. ``DATETIME(6)``).\n\nDjango will not upgrade existing columns to include fractional seconds if the\ndatabase server supports it. If you want to enable them on an existing database,\nit's up to you to either manually update the column on the target database, by\nexecuting a command like::\n\n    ALTER TABLE `your_table` MODIFY `your_datetime_column` DATETIME(6)\n\nor using a :class:`~django.db.migrations.operations.RunSQL` operation in a\n:ref:`data migration <data-migrations>`.\n\n``TIMESTAMP`` columns\n~~~~~~~~~~~~~~~~~~~~~\n\nIf you are using a legacy database that contains ``TIMESTAMP`` columns, you must\nset :setting:`USE_TZ = False <USE_TZ>` to avoid data corruption.\n:djadmin:`inspectdb` maps these columns to\n:class:`~django.db.models.DateTimeField` and if you enable timezone support,\nboth MySQL and Django will attempt to convert the values from UTC to local time.\n\nRow locking with ``QuerySet.select_for_update()``\n-------------------------------------------------\n\nMySQL and MariaDB do not support some options to the ``SELECT ... FOR UPDATE``\nstatement. If ``select_for_update()`` is used with an unsupported option, then\na :exc:`~django.db.NotSupportedError` is raised.\n\n=============== ========= ==========\nOption          MariaDB   MySQL\n=============== ========= ==========\n``SKIP LOCKED``           X (≥8.0.1)\n``NOWAIT``      X (≥10.3) X (≥8.0.1)\n``OF``\n=============== ========= ==========\n\nWhen using ``select_for_update()`` on MySQL, make sure you filter a queryset\nagainst at least set of fields contained in unique constraints or only against\nfields covered by indexes. Otherwise, an exclusive write lock will be acquired\nover the full table for the duration of the transaction.\n\nAutomatic typecasting can cause unexpected results\n--------------------------------------------------\n\nWhen performing a query on a string type, but with an integer value, MySQL will\ncoerce the types of all values in the table to an integer before performing the\ncomparison. If your table contains the values ``'abc'``, ``'def'`` and you\nquery for ``WHERE mycolumn=0``, both rows will match. Similarly, ``WHERE mycolumn=1``\nwill match the value ``'abc1'``. Therefore, string type fields included in Django\nwill always cast the value to a string before using it in a query.\n\nIf you implement custom model fields that inherit from\n:class:`~django.db.models.Field` directly, are overriding\n:meth:`~django.db.models.Field.get_prep_value`, or use\n:class:`~django.db.models.expressions.RawSQL`,\n:meth:`~django.db.models.query.QuerySet.extra`, or\n:meth:`~django.db.models.Manager.raw`, you should ensure that you perform\nappropriate typecasting.\n\n.. _sqlite-notes:\n\nSQLite notes\n============\n\nDjango supports SQLite 3.8.3 and later.\n\nSQLite_ provides an excellent development alternative for applications that\nare predominantly read-only or require a smaller installation footprint. As\nwith all database servers, though, there are some differences that are\nspecific to SQLite that you should be aware of.\n\n.. _SQLite: https://www.sqlite.org/\n\n.. _sqlite-string-matching:\n\nSubstring matching and case sensitivity\n---------------------------------------\n\nFor all SQLite versions, there is some slightly counter-intuitive behavior when\nattempting to match some types of strings.  These are triggered when using the\n:lookup:`iexact` or :lookup:`contains` filters in Querysets. The behavior\nsplits into two cases:\n\n1. For substring matching, all matches are done case-insensitively. That is a\nfilter such as ``filter(name__contains=\"aa\")`` will match a name of ``\"Aabb\"``.\n\n2. For strings containing characters outside the ASCII range, all exact string\nmatches are performed case-sensitively, even when the case-insensitive options\nare passed into the query. So the :lookup:`iexact` filter will behave exactly\nthe same as the :lookup:`exact` filter in these cases.\n\nSome possible workarounds for this are `documented at sqlite.org`_, but they\naren't utilized by the default SQLite backend in Django, as incorporating them\nwould be fairly difficult to do robustly. Thus, Django exposes the default\nSQLite behavior and you should be aware of this when doing case-insensitive or\nsubstring filtering.\n\n.. _documented at sqlite.org: https://www.sqlite.org/faq.html#q18\n\n.. _sqlite-decimal-handling:\n\nDecimal handling\n----------------\n\nSQLite has no real decimal internal type. Decimal values are internally\nconverted to the ``REAL`` data type (8-byte IEEE floating point number), as\nexplained in the `SQLite datatypes documentation`__, so they don't support\ncorrectly-rounded decimal floating point arithmetic.\n\n__ https://www.sqlite.org/datatype3.html#storage_classes_and_datatypes\n\n\"Database is locked\" errors\n---------------------------\n\nSQLite is meant to be a lightweight database, and thus can't support a high\nlevel of concurrency. ``OperationalError: database is locked`` errors indicate\nthat your application is experiencing more concurrency than ``sqlite`` can\nhandle in default configuration. This error means that one thread or process has\nan exclusive lock on the database connection and another thread timed out\nwaiting for the lock the be released.\n\nPython's SQLite wrapper has\na default timeout value that determines how long the second thread is allowed to\nwait on the lock before it times out and raises the ``OperationalError: database\nis locked`` error.\n\nIf you're getting this error, you can solve it by:\n\n* Switching to another database backend. At a certain point SQLite becomes\n  too \"lite\" for real-world applications, and these sorts of concurrency\n  errors indicate you've reached that point.\n\n* Rewriting your code to reduce concurrency and ensure that database\n  transactions are short-lived.\n\n* Increase the default timeout value by setting the ``timeout`` database\n  option::\n\n      'OPTIONS': {\n          # ...\n          'timeout': 20,\n          # ...\n      }\n\n  This will make SQLite wait a bit longer before throwing \"database is locked\"\n  errors; it won't really do anything to solve them.\n\n``QuerySet.select_for_update()`` not supported\n----------------------------------------------\n\nSQLite does not support the ``SELECT ... FOR UPDATE`` syntax. Calling it will\nhave no effect.\n\n\"pyformat\" parameter style in raw queries not supported\n-------------------------------------------------------\n\nFor most backends, raw queries (``Manager.raw()`` or ``cursor.execute()``)\ncan use the \"pyformat\" parameter style, where placeholders in the query\nare given as ``'%(name)s'`` and the parameters are passed as a dictionary\nrather than a list. SQLite does not support this.\n\n.. _sqlite-isolation:\n\nIsolation when using ``QuerySet.iterator()``\n--------------------------------------------\n\nThere are special considerations described in `Isolation In SQLite`_ when\nmodifying a table while iterating over it using :meth:`.QuerySet.iterator`. If\na row is added, changed, or deleted within the loop, then that row may or may\nnot appear, or may appear twice, in subsequent results fetched from the\niterator. Your code must handle this.\n\n.. _`Isolation in SQLite`: https://sqlite.org/isolation.html\n\n.. _sqlite-json1:\n\nEnabling JSON1 extension on SQLite\n----------------------------------\n\nTo use :class:`~django.db.models.JSONField` on SQLite, you need to enable the\n`JSON1 extension`_ on Python's :py:mod:`sqlite3` library. If the extension is\nnot enabled on your installation, a system error (``fields.E180``) will be\nraised.\n\nTo enable the JSON1 extension you can follow the instruction on\n`the wiki page`_.\n\n.. _JSON1 extension: https://www.sqlite.org/json1.html\n.. _the wiki page: https://code.djangoproject.com/wiki/JSON1Extension\n\n.. _oracle-notes:\n\nOracle notes\n============\n\nDjango supports `Oracle Database Server`_ versions 12.2 and higher. Version\n6.0 or higher of the `cx_Oracle`_ Python driver is required.\n\n.. _`Oracle Database Server`: https://www.oracle.com/\n.. _`cx_Oracle`: https://oracle.github.io/python-cx_Oracle/\n\nIn order for the ``python manage.py migrate`` command to work, your Oracle\ndatabase user must have privileges to run the following commands:\n\n* CREATE TABLE\n* CREATE SEQUENCE\n* CREATE PROCEDURE\n* CREATE TRIGGER\n\nTo run a project's test suite, the user usually needs these *additional*\nprivileges:\n\n* CREATE USER\n* ALTER USER\n* DROP USER\n* CREATE TABLESPACE\n* DROP TABLESPACE\n* CREATE SESSION WITH ADMIN OPTION\n* CREATE TABLE WITH ADMIN OPTION\n* CREATE SEQUENCE WITH ADMIN OPTION\n* CREATE PROCEDURE WITH ADMIN OPTION\n* CREATE TRIGGER WITH ADMIN OPTION\n\nWhile the ``RESOURCE`` role has the required ``CREATE TABLE``,\n``CREATE SEQUENCE``, ``CREATE PROCEDURE``, and ``CREATE TRIGGER`` privileges,\nand a user granted ``RESOURCE WITH ADMIN OPTION`` can grant ``RESOURCE``, such\na user cannot grant the individual privileges (e.g. ``CREATE TABLE``), and thus\n``RESOURCE WITH ADMIN OPTION`` is not usually sufficient for running tests.\n\nSome test suites also create views or materialized views; to run these, the\nuser also needs ``CREATE VIEW WITH ADMIN OPTION`` and\n``CREATE MATERIALIZED VIEW WITH ADMIN OPTION`` privileges. In particular, this\nis needed for Django's own test suite.\n\nAll of these privileges are included in the DBA role, which is appropriate\nfor use on a private developer's database.\n\nThe Oracle database backend uses the ``SYS.DBMS_LOB`` and ``SYS.DBMS_RANDOM``\npackages, so your user will require execute permissions on it. It's normally\naccessible to all users by default, but in case it is not, you'll need to grant\npermissions like so:\n\n.. code-block:: sql\n\n    GRANT EXECUTE ON SYS.DBMS_LOB TO user;\n    GRANT EXECUTE ON SYS.DBMS_RANDOM TO user;\n\nConnecting to the database\n--------------------------\n\nTo connect using the service name of your Oracle database, your ``settings.py``\nfile should look something like this::\n\n    DATABASES = {\n        'default': {\n            'ENGINE': 'django.db.backends.oracle',\n            'NAME': 'xe',\n            'USER': 'a_user',\n            'PASSWORD': 'a_password',\n            'HOST': '',\n            'PORT': '',\n        }\n    }\n\n\nIn this case, you should leave both :setting:`HOST` and :setting:`PORT` empty.\nHowever, if you don't use a ``tnsnames.ora`` file or a similar naming method\nand want to connect using the SID (\"xe\" in this example), then fill in both\n:setting:`HOST` and :setting:`PORT` like so::\n\n    DATABASES = {\n        'default': {\n            'ENGINE': 'django.db.backends.oracle',\n            'NAME': 'xe',\n            'USER': 'a_user',\n            'PASSWORD': 'a_password',\n            'HOST': 'dbprod01ned.mycompany.com',\n            'PORT': '1540',\n        }\n    }\n\nYou should either supply both :setting:`HOST` and :setting:`PORT`, or leave\nboth as empty strings. Django will use a different connect descriptor depending\non that choice.\n\nFull DSN and Easy Connect\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\nA Full DSN or Easy Connect string can be used in :setting:`NAME` if both\n:setting:`HOST` and :setting:`PORT` are empty. This format is required when\nusing RAC or pluggable databases without ``tnsnames.ora``, for example.\n\nExample of an Easy Connect string::\n\n    'NAME': 'localhost:1521/orclpdb1',\n\nExample of a full DSN string::\n\n    'NAME': (\n        '(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))'\n        '(CONNECT_DATA=(SERVICE_NAME=orclpdb1)))'\n    ),\n\nThreaded option\n---------------\n\nIf you plan to run Django in a multithreaded environment (e.g. Apache using the\ndefault MPM module on any modern operating system), then you **must** set\nthe ``threaded`` option of your Oracle database configuration to ``True``::\n\n    'OPTIONS': {\n        'threaded': True,\n    },\n\nFailure to do this may result in crashes and other odd behavior.\n\nINSERT ... RETURNING INTO\n-------------------------\n\nBy default, the Oracle backend uses a ``RETURNING INTO`` clause to efficiently\nretrieve the value of an ``AutoField`` when inserting new rows.  This behavior\nmay result in a ``DatabaseError`` in certain unusual setups, such as when\ninserting into a remote table, or into a view with an ``INSTEAD OF`` trigger.\nThe ``RETURNING INTO`` clause can be disabled by setting the\n``use_returning_into`` option of the database configuration to ``False``::\n\n    'OPTIONS': {\n        'use_returning_into': False,\n    },\n\nIn this case, the Oracle backend will use a separate ``SELECT`` query to\nretrieve ``AutoField`` values.\n\nNaming issues\n-------------\n\nOracle imposes a name length limit of 30 characters. To accommodate this, the\nbackend truncates database identifiers to fit, replacing the final four\ncharacters of the truncated name with a repeatable MD5 hash value.\nAdditionally, the backend turns database identifiers to all-uppercase.\n\nTo prevent these transformations (this is usually required only when dealing\nwith legacy databases or accessing tables which belong to other users), use\na quoted name as the value for ``db_table``::\n\n    class LegacyModel(models.Model):\n        class Meta:\n            db_table = '\"name_left_in_lowercase\"'\n\n    class ForeignModel(models.Model):\n        class Meta:\n            db_table = '\"OTHER_USER\".\"NAME_ONLY_SEEMS_OVER_30\"'\n\nQuoted names can also be used with Django's other supported database\nbackends; except for Oracle, however, the quotes have no effect.\n\nWhen running ``migrate``, an ``ORA-06552`` error may be encountered if\ncertain Oracle keywords are used as the name of a model field or the\nvalue of a ``db_column`` option.  Django quotes all identifiers used\nin queries to prevent most such problems, but this error can still\noccur when an Oracle datatype is used as a column name.  In\nparticular, take care to avoid using the names ``date``,\n``timestamp``, ``number`` or ``float`` as a field name.\n\n.. _oracle-null-empty-strings:\n\nNULL and empty strings\n----------------------\n\nDjango generally prefers to use the empty string (``''``) rather than\n``NULL``, but Oracle treats both identically. To get around this, the\nOracle backend ignores an explicit ``null`` option on fields that\nhave the empty string as a possible value and generates DDL as if\n``null=True``. When fetching from the database, it is assumed that\na ``NULL`` value in one of these fields really means the empty\nstring, and the data is silently converted to reflect this assumption.\n\n``TextField`` limitations\n-------------------------\n\nThe Oracle backend stores ``TextFields`` as ``NCLOB`` columns. Oracle imposes\nsome limitations on the usage of such LOB columns in general:\n\n* LOB columns may not be used as primary keys.\n\n* LOB columns may not be used in indexes.\n\n* LOB columns may not be used in a ``SELECT DISTINCT`` list. This means that\n  attempting to use the ``QuerySet.distinct`` method on a model that\n  includes ``TextField`` columns will result in an ``ORA-00932`` error when\n  run against Oracle. As a workaround, use the ``QuerySet.defer`` method in\n  conjunction with ``distinct()`` to prevent ``TextField`` columns from being\n  included in the ``SELECT DISTINCT`` list.\n\n.. _subclassing-database-backends:\n\nSubclassing the built-in database backends\n==========================================\n\nDjango comes with built-in database backends. You may subclass an existing\ndatabase backends to modify its behavior, features, or configuration.\n\nConsider, for example, that you need to change a single database feature.\nFirst, you have to create a new directory with a ``base`` module in it. For\nexample::\n\n    mysite/\n        ...\n        mydbengine/\n            __init__.py\n            base.py\n\nThe ``base.py`` module must contain a class named ``DatabaseWrapper`` that\nsubclasses an existing engine from the ``django.db.backends`` module. Here's an\nexample of subclassing the PostgreSQL engine to change a feature class\n``allows_group_by_selected_pks_on_model``:\n\n.. code-block:: python\n    :caption: mysite/mydbengine/base.py\n\n    from django.db.backends.postgresql import base, features\n\n    class DatabaseFeatures(features.DatabaseFeatures):\n        def allows_group_by_selected_pks_on_model(self, model):\n            return True\n\n    class DatabaseWrapper(base.DatabaseWrapper):\n        features_class = DatabaseFeatures\n\nFinally, you must specify a :setting:`DATABASE-ENGINE` in your ``settings.py``\nfile::\n\n    DATABASES = {\n        'default': {\n            'ENGINE': 'mydbengine',\n            ...\n        },\n    }\n\nYou can see the current list of database engines by looking in\n:source:`django/db/backends`.\n\n.. _third-party-notes:\n\nUsing a 3rd-party database backend\n==================================\n\nIn addition to the officially supported databases, there are backends provided\nby 3rd parties that allow you to use other databases with Django:\n\n* `IBM DB2`_\n* `Microsoft SQL Server`_\n* Firebird_\n* ODBC_\n\nThe Django versions and ORM features supported by these unofficial backends\nvary considerably. Queries regarding the specific capabilities of these\nunofficial backends, along with any support queries, should be directed to\nthe support channels provided by each 3rd party project.\n\n.. _IBM DB2: https://pypi.org/project/ibm_db_django/\n.. _Microsoft SQL Server: https://pypi.org/project/django-pyodbc-azure/\n.. _Firebird: https://github.com/maxirobaina/django-firebird\n.. _ODBC: https://github.com/lionheart/django-pyodbc/\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":42,"nodeType":"TextFile","repoName":null,"name":"contributing.txt","path":"docs/faq","text":"======================\nFAQ: Contributing code\n======================\n\nHow can I get started contributing code to Django?\n==================================================\n\nThanks for asking! We've written an entire document devoted to this question.\nIt's titled :doc:`Contributing to Django </internals/contributing/index>`.\n\nI submitted a bug fix in the ticket system several weeks ago. Why are you ignoring my patch?\n============================================================================================\n\nDon't worry: We're not ignoring you!\n\nIt's important to understand there is a difference between \"a ticket is being\nignored\" and \"a ticket has not been attended to yet.\" Django's ticket system\ncontains hundreds of open tickets, of various degrees of impact on end-user\nfunctionality, and Django's developers have to review and prioritize.\n\nOn top of that: the people who work on Django are all volunteers. As a result,\nthe amount of time that we have to work on the framework is limited and will\nvary from week to week depending on our spare time. If we're busy, we may not\nbe able to spend as much time on Django as we might want.\n\nThe best way to make sure tickets do not get hung up on the way to checkin is\nto make it dead easy, even for someone who may not be intimately familiar with\nthat area of the code, to understand the problem and verify the fix:\n\n* Are there clear instructions on how to reproduce the bug? If this\n  touches a dependency (such as Pillow), a contrib module, or a specific\n  database, are those instructions clear enough even for someone not\n  familiar with it?\n\n* If there are several patches attached to the ticket, is it clear what\n  each one does, which ones can be ignored and which matter?\n\n* Does the patch include a unit test? If not, is there a very clear\n  explanation why not? A test expresses succinctly what the problem is,\n  and shows that the patch actually fixes it.\n\nIf your patch stands no chance of inclusion in Django, we won't ignore it --\nwe'll just close the ticket. So if your ticket is still open, it doesn't mean\nwe're ignoring you; it just means we haven't had time to look at it yet.\n\nWhen and how might I remind the team of a patch I care about?\n=============================================================\n\nA polite, well-timed message to the mailing list is one way to get attention.\nTo determine the right time, you need to keep an eye on the schedule. If you\npost your message right before a release deadline, you're not likely to get the\nsort of attention you require.\n\nGentle IRC reminders can also work -- again, strategically timed if possible.\nDuring a bug sprint would be a very good time, for example.\n\nAnother way to get traction is to pull several related tickets together. When\nthe someone sits down to review a bug in an area they haven't touched for\na while, it can take a few minutes to remember all the fine details of how\nthat area of code works. If you collect several minor bug fixes together into\na similarly themed group, you make an attractive target, as the cost of coming\nup to speed on an area of code can be spread over multiple tickets.\n\nPlease refrain from emailing anyone personally or repeatedly raising the same\nissue over and over. This sort of behavior will not gain you any additional\nattention -- certainly not the attention that you need in order to get your\nissue addressed.\n\nBut I've reminded you several times and you keep ignoring my patch!\n===================================================================\n\nSeriously - we're not ignoring you. If your patch stands no chance of\ninclusion in Django, we'll close the ticket. For all the other tickets, we\nneed to prioritize our efforts, which means that some tickets will be\naddressed before others.\n\nOne of the criteria that is used to prioritize bug fixes is the number of\npeople that will likely be affected by a given bug. Bugs that have the\npotential to affect many people will generally get priority over those that\nare edge cases.\n\nAnother reason that bugs might be ignored for while is if the bug is a symptom\nof a larger problem. While we can spend time writing, testing and applying\nlots of little patches, sometimes the right solution is to rebuild. If a\nrebuild or refactor of a particular component has been proposed or is\nunderway, you may find that bugs affecting that component will not get as much\nattention. Again, this is a matter of prioritizing scarce resources. By\nconcentrating on the rebuild, we can close all the little bugs at once, and\nhopefully prevent other little bugs from appearing in the future.\n\nWhatever the reason, please keep in mind that while you may hit a particular\nbug regularly, it doesn't necessarily follow that every single Django user\nwill hit the same bug. Different users use Django in different ways, stressing\ndifferent parts of the code under different conditions. When we evaluate the\nrelative priorities, we are generally trying to consider the needs of the\nentire community, instead of prioritizing the impact on one particular user.\nThis doesn't mean that we think your problem is unimportant -- just that in the\nlimited time we have available, we will always err on the side of making 10\npeople happy rather than making a single person happy.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":43,"nodeType":"TextFile","repoName":null,"name":"views.txt","path":"docs/ref","text":"==============\nBuilt-in Views\n==============\n\n.. module:: django.views\n   :synopsis: Django's built-in views.\n\nSeveral of Django's built-in views are documented in\n:doc:`/topics/http/views` as well as elsewhere in the documentation.\n\nServing files in development\n============================\n\n.. function:: static.serve(request, path, document_root, show_indexes=False)\n\nThere may be files other than your project's static assets that, for\nconvenience, you'd like to have Django serve for you in local development.\nThe :func:`~django.views.static.serve` view can be used to serve any directory\nyou give it. (This view is **not** hardened for production use and should be\nused only as a development aid; you should serve these files in production\nusing a real front-end web server).\n\nThe most likely example is user-uploaded content in :setting:`MEDIA_ROOT`.\n``django.contrib.staticfiles`` is intended for static assets and has no\nbuilt-in handling for user-uploaded files, but you can have Django serve your\n:setting:`MEDIA_ROOT` by appending something like this to your URLconf::\n\n    from django.conf import settings\n    from django.urls import re_path\n    from django.views.static import serve\n\n    # ... the rest of your URLconf goes here ...\n\n    if settings.DEBUG:\n        urlpatterns += [\n            re_path(r'^media/(?P<path>.*)$', serve, {\n                'document_root': settings.MEDIA_ROOT,\n            }),\n        ]\n\nNote, the snippet assumes your :setting:`MEDIA_URL` has a value of\n``'/media/'``. This will call the :func:`~django.views.static.serve` view,\npassing in the path from the URLconf and the (required) ``document_root``\nparameter.\n\nSince it can become a bit cumbersome to define this URL pattern, Django\nships with a small URL helper function :func:`~django.conf.urls.static.static`\nthat takes as parameters the prefix such as :setting:`MEDIA_URL` and a dotted\npath to a view, such as ``'django.views.static.serve'``. Any other function\nparameter will be transparently passed to the view.\n\n.. _error-views:\n\nError views\n===========\n\nDjango comes with a few views by default for handling HTTP errors. To override\nthese with your own custom views, see :ref:`customizing-error-views`.\n\n.. _http_not_found_view:\n\nThe 404 (page not found) view\n-----------------------------\n\n.. function:: defaults.page_not_found(request, exception, template_name='404.html')\n\nWhen you raise :exc:`~django.http.Http404` from within a view, Django loads a\nspecial view devoted to handling 404 errors. By default, it's the view\n:func:`django.views.defaults.page_not_found`, which either produces a \"Not\nFound\" message or loads and renders the template ``404.html`` if you created it\nin your root template directory.\n\nThe default 404 view will pass two variables to the template: ``request_path``,\nwhich is the URL that resulted in the error, and ``exception``, which is a\nuseful representation of the exception that triggered the view (e.g. containing\nany message passed to a specific ``Http404`` instance).\n\nThree things to note about 404 views:\n\n* The 404 view is also called if Django doesn't find a match after\n  checking every regular expression in the URLconf.\n\n* The 404 view is passed a :class:`~django.template.RequestContext` and\n  will have access to variables supplied by your template context\n  processors (e.g. ``MEDIA_URL``).\n\n* If :setting:`DEBUG` is set to ``True`` (in your settings module), then\n  your 404 view will never be used, and your URLconf will be displayed\n  instead, with some debug information.\n\n.. _http_internal_server_error_view:\n\nThe 500 (server error) view\n---------------------------\n\n.. function:: defaults.server_error(request, template_name='500.html')\n\nSimilarly, Django executes special-case behavior in the case of runtime errors\nin view code. If a view results in an exception, Django will, by default, call\nthe view ``django.views.defaults.server_error``, which either produces a\n\"Server Error\" message or loads and renders the template ``500.html`` if you\ncreated it in your root template directory.\n\nThe default 500 view passes no variables to the ``500.html`` template and is\nrendered with an empty ``Context`` to lessen the chance of additional errors.\n\nIf :setting:`DEBUG` is set to ``True`` (in your settings module), then\nyour 500 view will never be used, and the traceback will be displayed\ninstead, with some debug information.\n\n.. _http_forbidden_view:\n\nThe 403 (HTTP Forbidden) view\n-----------------------------\n\n.. function:: defaults.permission_denied(request, exception, template_name='403.html')\n\nIn the same vein as the 404 and 500 views, Django has a view to handle 403\nForbidden errors. If a view results in a 403 exception then Django will, by\ndefault, call the view ``django.views.defaults.permission_denied``.\n\nThis view loads and renders the template ``403.html`` in your root template\ndirectory, or if this file does not exist, instead serves the text\n\"403 Forbidden\", as per :rfc:`7231#section-6.5.3` (the HTTP 1.1 Specification).\nThe template context contains ``exception``, which is the string\nrepresentation of the exception that triggered the view.\n\n``django.views.defaults.permission_denied`` is triggered by a\n:exc:`~django.core.exceptions.PermissionDenied` exception. To deny access in a\nview you can use code like this::\n\n    from django.core.exceptions import PermissionDenied\n\n    def edit(request, pk):\n        if not request.user.is_staff:\n            raise PermissionDenied\n        # ...\n\n.. _http_bad_request_view:\n\nThe 400 (bad request) view\n--------------------------\n\n.. function:: defaults.bad_request(request, exception, template_name='400.html')\n\nWhen a :exc:`~django.core.exceptions.SuspiciousOperation` is raised in Django,\nit may be handled by a component of Django (for example resetting the session\ndata). If not specifically handled, Django will consider the current request a\n'bad request' instead of a server error.\n\n``django.views.defaults.bad_request``, is otherwise very similar to the\n``server_error`` view, but returns with the status code 400 indicating that\nthe error condition was the result of a client operation. By default, nothing\nrelated to the exception that triggered the view is passed to the template\ncontext, as the exception message might contain sensitive information like\nfilesystem paths.\n\n``bad_request`` views are also only used when :setting:`DEBUG` is ``False``.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":44,"nodeType":"TextFile","repoName":null,"name":"urls.txt","path":"docs/ref","text":"=============================================\n``django.urls`` functions for use in URLconfs\n=============================================\n\n.. module:: django.urls.conf\n    :synopsis: Functions for use in URLconfs.\n\n.. currentmodule:: django.urls\n\n``path()``\n==========\n\n.. function:: path(route, view, kwargs=None, name=None)\n\nReturns an element for inclusion in ``urlpatterns``. For example::\n\n    from django.urls import include, path\n\n    urlpatterns = [\n        path('index/', views.index, name='main-view'),\n        path('bio/<username>/', views.bio, name='bio'),\n        path('articles/<slug:title>/', views.article, name='article-detail'),\n        path('articles/<slug:title>/<int:section>/', views.section, name='article-section'),\n        path('weblog/', include('blog.urls')),\n        ...\n    ]\n\nThe ``route`` argument should be a string or\n:func:`~django.utils.translation.gettext_lazy()` (see\n:ref:`translating-urlpatterns`) that contains a URL pattern. The string\nmay contain angle brackets (like ``<username>`` above) to capture part of the\nURL and send it as a keyword argument to the view. The angle brackets may\ninclude a converter specification (like the ``int`` part of ``<int:section>``)\nwhich limits the characters matched and may also change the type of the\nvariable passed to the view. For example, ``<int:section>`` matches a string\nof decimal digits and converts the value to an ``int``. See\n:ref:`how-django-processes-a-request` for more details.\n\nThe ``view`` argument is a view function or the result of\n:meth:`~django.views.generic.base.View.as_view` for class-based views. It can\nalso be an :func:`django.urls.include`.\n\nThe ``kwargs`` argument allows you to pass additional arguments to the view\nfunction or method. See :ref:`views-extra-options` for an example.\n\nSee :ref:`Naming URL patterns <naming-url-patterns>` for why the ``name``\nargument is useful.\n\n``re_path()``\n=============\n\n.. function:: re_path(route, view, kwargs=None, name=None)\n\nReturns an element for inclusion in ``urlpatterns``. For example::\n\n    from django.urls import include, re_path\n\n    urlpatterns = [\n        re_path(r'^index/$', views.index, name='index'),\n        re_path(r'^bio/(?P<username>\\w+)/$', views.bio, name='bio'),\n        re_path(r'^weblog/', include('blog.urls')),\n        ...\n    ]\n\nThe ``route`` argument should be a string or\n:func:`~django.utils.translation.gettext_lazy()` (see\n:ref:`translating-urlpatterns`) that contains a regular expression compatible\nwith Python's :py:mod:`re` module. Strings typically use raw string syntax\n(``r''``) so that they can contain sequences like ``\\d`` without the need to\nescape the backslash with another backslash. When a match is made, captured\ngroups from the regular expression are passed to the view -- as named arguments\nif the groups are named, and as positional arguments otherwise. The values are\npassed as strings, without any type conversion.\n\nThe ``view``, ``kwargs`` and ``name`` arguments are the same as for\n:func:`~django.urls.path()`.\n\n``include()``\n=============\n\n.. function:: include(module, namespace=None)\n              include(pattern_list)\n              include((pattern_list, app_namespace), namespace=None)\n\n    A function that takes a full Python import path to another URLconf module\n    that should be \"included\" in this place. Optionally, the :term:`application\n    namespace` and :term:`instance namespace` where the entries will be included\n    into can also be specified.\n\n    Usually, the application namespace should be specified by the included\n    module. If an application namespace is set, the ``namespace`` argument\n    can be used to set a different instance namespace.\n\n    ``include()`` also accepts as an argument either an iterable that returns\n    URL patterns or a 2-tuple containing such iterable plus the names of the\n    application namespaces.\n\n    :arg module: URLconf module (or module name)\n    :arg namespace: Instance namespace for the URL entries being included\n    :type namespace: str\n    :arg pattern_list: Iterable of :func:`~django.urls.path` and/or :func:`~django.urls.re_path` instances.\n    :arg app_namespace: Application namespace for the URL entries being included\n    :type app_namespace: str\n\nSee :ref:`including-other-urlconfs` and :ref:`namespaces-and-include`.\n\n``register_converter()``\n========================\n\n.. function:: register_converter(converter, type_name)\n\nThe function for registering a converter for use in :func:`~django.urls.path()`\n``route``\\s.\n\nThe ``converter`` argument is a converter class, and ``type_name`` is the\nconverter name to use in path patterns. See\n:ref:`registering-custom-path-converters` for an example.\n\n==================================================\n``django.conf.urls`` functions for use in URLconfs\n==================================================\n\n.. module:: django.conf.urls\n\n``static()``\n============\n\n.. function:: static.static(prefix, view=django.views.static.serve, **kwargs)\n\nHelper function to return a URL pattern for serving files in debug mode::\n\n    from django.conf import settings\n    from django.conf.urls.static import static\n\n    urlpatterns = [\n        # ... the rest of your URLconf goes here ...\n    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\n``url()``\n=========\n\n.. function:: url(regex, view, kwargs=None, name=None)\n\nThis function is an alias to :func:`django.urls.re_path()`.\n\n.. deprecated:: 3.1\n\n    Alias of :func:`django.urls.re_path` for backwards compatibility.\n\n``handler400``\n==============\n\n.. data:: handler400\n\nA callable, or a string representing the full Python import path to the view\nthat should be called if the HTTP client has sent a request that caused an error\ncondition and a response with a status code of 400.\n\nBy default, this is :func:`django.views.defaults.bad_request`. If you\nimplement a custom view, be sure it accepts ``request`` and ``exception``\narguments and returns an :class:`~django.http.HttpResponseBadRequest`.\n\n``handler403``\n==============\n\n.. data:: handler403\n\nA callable, or a string representing the full Python import path to the view\nthat should be called if the user doesn't have the permissions required to\naccess a resource.\n\nBy default, this is :func:`django.views.defaults.permission_denied`. If you\nimplement a custom view, be sure it accepts ``request`` and ``exception``\narguments and returns an :class:`~django.http.HttpResponseForbidden`.\n\n``handler404``\n==============\n\n.. data:: handler404\n\nA callable, or a string representing the full Python import path to the view\nthat should be called if none of the URL patterns match.\n\nBy default, this is :func:`django.views.defaults.page_not_found`. If you\nimplement a custom view, be sure it accepts ``request`` and ``exception``\narguments and returns an :class:`~django.http.HttpResponseNotFound`.\n\n``handler500``\n==============\n\n.. data:: handler500\n\nA callable, or a string representing the full Python import path to the view\nthat should be called in case of server errors. Server errors happen when you\nhave runtime errors in view code.\n\nBy default, this is :func:`django.views.defaults.server_error`. If you\nimplement a custom view, be sure it accepts a ``request`` argument and returns\nan :class:`~django.http.HttpResponseServerError`.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":45,"nodeType":"TextFile","repoName":null,"name":"settings.txt","path":"docs/ref","text":"========\nSettings\n========\n\n.. contents::\n    :local:\n    :depth: 1\n\n.. warning::\n\n    Be careful when you override settings, especially when the default value\n    is a non-empty list or dictionary, such as :setting:`STATICFILES_FINDERS`.\n    Make sure you keep the components required by the features of Django you\n    wish to use.\n\nCore Settings\n=============\n\nHere's a list of settings available in Django core and their default values.\nSettings provided by contrib apps are listed below, followed by a topical index\nof the core settings. For introductory material, see the :doc:`settings topic\nguide </topics/settings>`.\n\n.. setting:: ABSOLUTE_URL_OVERRIDES\n\n``ABSOLUTE_URL_OVERRIDES``\n--------------------------\n\nDefault: ``{}`` (Empty dictionary)\n\nA dictionary mapping ``\"app_label.model_name\"`` strings to functions that take\na model object and return its URL. This is a way of inserting or overriding\n``get_absolute_url()`` methods on a per-installation basis. Example::\n\n    ABSOLUTE_URL_OVERRIDES = {\n        'blogs.weblog': lambda o: \"/blogs/%s/\" % o.slug,\n        'news.story': lambda o: \"/stories/%s/%s/\" % (o.pub_year, o.slug),\n    }\n\nThe model name used in this setting should be all lowercase, regardless of the\ncase of the actual model class name.\n\n.. setting:: ADMINS\n\n``ADMINS``\n----------\n\nDefault: ``[]`` (Empty list)\n\nA list of all the people who get code error notifications. When\n:setting:`DEBUG=False <DEBUG>` and :class:`~django.utils.log.AdminEmailHandler`\nis configured in :setting:`LOGGING` (done by default), Django emails these\npeople the details of exceptions raised in the request/response cycle.\n\nEach item in the list should be a tuple of (Full name, email address). Example::\n\n    [('John', 'john@example.com'), ('Mary', 'mary@example.com')]\n\n.. setting:: ALLOWED_HOSTS\n\n``ALLOWED_HOSTS``\n-----------------\n\nDefault: ``[]`` (Empty list)\n\nA list of strings representing the host/domain names that this Django site can\nserve. This is a security measure to prevent :ref:`HTTP Host header attacks\n<host-headers-virtual-hosting>`, which are possible even under many\nseemingly-safe web server configurations.\n\nValues in this list can be fully qualified names (e.g. ``'www.example.com'``),\nin which case they will be matched against the request's ``Host`` header\nexactly (case-insensitive, not including port). A value beginning with a period\ncan be used as a subdomain wildcard: ``'.example.com'`` will match\n``example.com``, ``www.example.com``, and any other subdomain of\n``example.com``. A value of ``'*'`` will match anything; in this case you are\nresponsible to provide your own validation of the ``Host`` header (perhaps in a\nmiddleware; if so this middleware must be listed first in\n:setting:`MIDDLEWARE`).\n\nDjango also allows the `fully qualified domain name (FQDN)`_ of any entries.\nSome browsers include a trailing dot in the ``Host`` header which Django\nstrips when performing host validation.\n\n.. _`fully qualified domain name (FQDN)`: https://en.wikipedia.org/wiki/Fully_qualified_domain_name\n\nIf the ``Host`` header (or ``X-Forwarded-Host`` if\n:setting:`USE_X_FORWARDED_HOST` is enabled) does not match any value in this\nlist, the :meth:`django.http.HttpRequest.get_host()` method will raise\n:exc:`~django.core.exceptions.SuspiciousOperation`.\n\nWhen :setting:`DEBUG` is ``True`` and ``ALLOWED_HOSTS`` is empty, the host\nis validated against ``['.localhost', '127.0.0.1', '[::1]']``.\n\n``ALLOWED_HOSTS`` is also :ref:`checked when running tests\n<topics-testing-advanced-multiple-hosts>`.\n\nThis validation only applies via :meth:`~django.http.HttpRequest.get_host()`;\nif your code accesses the ``Host`` header directly from ``request.META`` you\nare bypassing this security protection.\n\n.. versionchanged:: 3.1\n\n    If ``ALLOWED_HOSTS`` is empty and ``DEBUG=True``, subdomains of localhost\n    were allowed.\n\n.. setting:: APPEND_SLASH\n\n``APPEND_SLASH``\n----------------\n\nDefault: ``True``\n\nWhen set to ``True``, if the request URL does not match any of the patterns\nin the URLconf and it doesn't end in a slash, an HTTP redirect is issued to the\nsame URL with a slash appended. Note that the redirect may cause any data\nsubmitted in a POST request to be lost.\n\nThe :setting:`APPEND_SLASH` setting is only used if\n:class:`~django.middleware.common.CommonMiddleware` is installed\n(see :doc:`/topics/http/middleware`). See also :setting:`PREPEND_WWW`.\n\n.. setting:: CACHES\n\n``CACHES``\n----------\n\nDefault::\n\n    {\n        'default': {\n            'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',\n        }\n    }\n\nA dictionary containing the settings for all caches to be used with\nDjango. It is a nested dictionary whose contents maps cache aliases\nto a dictionary containing the options for an individual cache.\n\nThe :setting:`CACHES` setting must configure a ``default`` cache;\nany number of additional caches may also be specified. If you\nare using a cache backend other than the local memory cache, or\nyou need to define multiple caches, other options will be required.\nThe following cache options are available.\n\n.. setting:: CACHES-BACKEND\n\n``BACKEND``\n~~~~~~~~~~~\n\nDefault: ``''`` (Empty string)\n\nThe cache backend to use. The built-in cache backends are:\n\n* ``'django.core.cache.backends.db.DatabaseCache'``\n* ``'django.core.cache.backends.dummy.DummyCache'``\n* ``'django.core.cache.backends.filebased.FileBasedCache'``\n* ``'django.core.cache.backends.locmem.LocMemCache'``\n* ``'django.core.cache.backends.memcached.MemcachedCache'``\n* ``'django.core.cache.backends.memcached.PyLibMCCache'``\n\nYou can use a cache backend that doesn't ship with Django by setting\n:setting:`BACKEND <CACHES-BACKEND>` to a fully-qualified path of a cache\nbackend class (i.e. ``mypackage.backends.whatever.WhateverCache``).\n\n.. setting:: CACHES-KEY_FUNCTION\n\n``KEY_FUNCTION``\n~~~~~~~~~~~~~~~~\n\nA string containing a dotted path to a function (or any callable) that defines how to\ncompose a prefix, version and key into a final cache key. The default\nimplementation is equivalent to the function::\n\n    def make_key(key, key_prefix, version):\n        return ':'.join([key_prefix, str(version), key])\n\nYou may use any key function you want, as long as it has the same\nargument signature.\n\nSee the :ref:`cache documentation <cache_key_transformation>` for more\ninformation.\n\n.. setting:: CACHES-KEY_PREFIX\n\n``KEY_PREFIX``\n~~~~~~~~~~~~~~\n\nDefault: ``''`` (Empty string)\n\nA string that will be automatically included (prepended by default) to\nall cache keys used by the Django server.\n\nSee the :ref:`cache documentation <cache_key_prefixing>` for more information.\n\n.. setting:: CACHES-LOCATION\n\n``LOCATION``\n~~~~~~~~~~~~\n\nDefault: ``''`` (Empty string)\n\nThe location of the cache to use. This might be the directory for a\nfile system cache, a host and port for a memcache server, or an identifying\nname for a local memory cache. e.g.::\n\n    CACHES = {\n        'default': {\n            'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',\n            'LOCATION': '/var/tmp/django_cache',\n        }\n    }\n\n.. setting:: CACHES-OPTIONS\n\n``OPTIONS``\n~~~~~~~~~~~\n\nDefault: ``None``\n\nExtra parameters to pass to the cache backend. Available parameters\nvary depending on your cache backend.\n\nSome information on available parameters can be found in the\n:ref:`cache arguments <cache_arguments>` documentation. For more information,\nconsult your backend module's own documentation.\n\n.. setting:: CACHES-TIMEOUT\n\n``TIMEOUT``\n~~~~~~~~~~~\n\nDefault: ``300``\n\nThe number of seconds before a cache entry is considered stale. If the value of\nthis settings is ``None``, cache entries will not expire.\n\n.. setting:: CACHES-VERSION\n\n``VERSION``\n~~~~~~~~~~~\n\nDefault: ``1``\n\nThe default version number for cache keys generated by the Django server.\n\nSee the :ref:`cache documentation <cache_versioning>` for more information.\n\n.. setting:: CACHE_MIDDLEWARE_ALIAS\n\n``CACHE_MIDDLEWARE_ALIAS``\n--------------------------\n\nDefault: ``default``\n\nThe cache connection to use for the :ref:`cache middleware\n<the-per-site-cache>`.\n\n.. setting:: CACHE_MIDDLEWARE_KEY_PREFIX\n\n``CACHE_MIDDLEWARE_KEY_PREFIX``\n-------------------------------\n\nDefault: ``''`` (Empty string)\n\nA string which will be prefixed to the cache keys generated by the :ref:`cache\nmiddleware <the-per-site-cache>`. This prefix is combined with the\n:setting:`KEY_PREFIX <CACHES-KEY_PREFIX>` setting; it does not replace it.\n\nSee :doc:`/topics/cache`.\n\n.. setting:: CACHE_MIDDLEWARE_SECONDS\n\n``CACHE_MIDDLEWARE_SECONDS``\n----------------------------\n\nDefault: ``600``\n\nThe default number of seconds to cache a page for the :ref:`cache middleware\n<the-per-site-cache>`.\n\nSee :doc:`/topics/cache`.\n\n.. _settings-csrf:\n\n.. setting:: CSRF_COOKIE_AGE\n\n``CSRF_COOKIE_AGE``\n-------------------\n\nDefault: ``31449600`` (approximately 1 year, in seconds)\n\nThe age of CSRF cookies, in seconds.\n\nThe reason for setting a long-lived expiration time is to avoid problems in\nthe case of a user closing a browser or bookmarking a page and then loading\nthat page from a browser cache. Without persistent cookies, the form submission\nwould fail in this case.\n\nSome browsers (specifically Internet Explorer) can disallow the use of\npersistent cookies or can have the indexes to the cookie jar corrupted on disk,\nthereby causing CSRF protection checks to (sometimes intermittently) fail.\nChange this setting to ``None`` to use session-based CSRF cookies, which\nkeep the cookies in-memory instead of on persistent storage.\n\n.. setting:: CSRF_COOKIE_DOMAIN\n\n``CSRF_COOKIE_DOMAIN``\n----------------------\n\nDefault: ``None``\n\nThe domain to be used when setting the CSRF cookie.  This can be useful for\neasily allowing cross-subdomain requests to be excluded from the normal cross\nsite request forgery protection.  It should be set to a string such as\n``\"example.com\"`` to allow a POST request from a form on one subdomain to be\naccepted by a view served from another subdomain.\n\nPlease note that the presence of this setting does not imply that Django's CSRF\nprotection is safe from cross-subdomain attacks by default - please see the\n:ref:`CSRF limitations <csrf-limitations>` section.\n\n.. setting:: CSRF_COOKIE_HTTPONLY\n\n``CSRF_COOKIE_HTTPONLY``\n------------------------\n\nDefault: ``False``\n\nWhether to use ``HttpOnly`` flag on the CSRF cookie. If this is set to\n``True``, client-side JavaScript will not be able to access the CSRF cookie.\n\nDesignating the CSRF cookie as ``HttpOnly`` doesn't offer any practical\nprotection because CSRF is only to protect against cross-domain attacks. If an\nattacker can read the cookie via JavaScript, they're already on the same domain\nas far as the browser knows, so they can do anything they like anyway. (XSS is\na much bigger hole than CSRF.)\n\nAlthough the setting offers little practical benefit, it's sometimes required\nby security auditors.\n\nIf you enable this and need to send the value of the CSRF token with an AJAX\nrequest, your JavaScript must pull the value :ref:`from a hidden CSRF token\nform input <acquiring-csrf-token-from-html>` instead of :ref:`from the cookie\n<acquiring-csrf-token-from-cookie>`.\n\nSee :setting:`SESSION_COOKIE_HTTPONLY` for details on ``HttpOnly``.\n\n.. setting:: CSRF_COOKIE_NAME\n\n``CSRF_COOKIE_NAME``\n--------------------\n\nDefault: ``'csrftoken'``\n\nThe name of the cookie to use for the CSRF authentication token. This can be\nwhatever you want (as long as it's different from the other cookie names in\nyour application). See :doc:`/ref/csrf`.\n\n.. setting:: CSRF_COOKIE_PATH\n\n``CSRF_COOKIE_PATH``\n--------------------\n\nDefault: ``'/'``\n\nThe path set on the CSRF cookie. This should either match the URL path of your\nDjango installation or be a parent of that path.\n\nThis is useful if you have multiple Django instances running under the same\nhostname. They can use different cookie paths, and each instance will only see\nits own CSRF cookie.\n\n.. setting:: CSRF_COOKIE_SAMESITE\n\n``CSRF_COOKIE_SAMESITE``\n------------------------\n\nDefault: ``'Lax'``\n\nThe value of the `SameSite`_ flag on the CSRF cookie. This flag prevents the\ncookie from being sent in cross-site requests.\n\nSee :setting:`SESSION_COOKIE_SAMESITE` for details about ``SameSite``.\n\n.. versionchanged:: 3.1\n\n    Setting ``CSRF_COOKIE_SAMESITE = 'None'`` was allowed.\n\n.. setting:: CSRF_COOKIE_SECURE\n\n``CSRF_COOKIE_SECURE``\n----------------------\n\nDefault: ``False``\n\nWhether to use a secure cookie for the CSRF cookie. If this is set to ``True``,\nthe cookie will be marked as \"secure\", which means browsers may ensure that the\ncookie is only sent with an HTTPS connection.\n\n.. setting:: CSRF_USE_SESSIONS\n\n``CSRF_USE_SESSIONS``\n---------------------\n\nDefault: ``False``\n\nWhether to store the CSRF token in the user's session instead of in a cookie.\nIt requires the use of :mod:`django.contrib.sessions`.\n\nStoring the CSRF token in a cookie (Django's default) is safe, but storing it\nin the session is common practice in other web frameworks and therefore\nsometimes demanded by security auditors.\n\nSince the :ref:`default error views <error-views>` require the CSRF token,\n:class:`~django.contrib.sessions.middleware.SessionMiddleware` must appear in\n:setting:`MIDDLEWARE` before any middleware that may raise an exception to\ntrigger an error view (such as :exc:`~django.core.exceptions.PermissionDenied`)\nif you're using ``CSRF_USE_SESSIONS``. See :ref:`middleware-ordering`.\n\n.. setting:: CSRF_FAILURE_VIEW\n\n``CSRF_FAILURE_VIEW``\n---------------------\n\nDefault: ``'django.views.csrf.csrf_failure'``\n\nA dotted path to the view function to be used when an incoming request is\nrejected by the :doc:`CSRF protection </ref/csrf>`. The function should have\nthis signature::\n\n    def csrf_failure(request, reason=\"\"):\n        ...\n\nwhere ``reason`` is a short message (intended for developers or logging, not\nfor end users) indicating the reason the request was rejected. It should return\nan :class:`~django.http.HttpResponseForbidden`.\n\n``django.views.csrf.csrf_failure()`` accepts an additional ``template_name``\nparameter that defaults to ``'403_csrf.html'``. If a template with that name\nexists, it will be used to render the page.\n\n.. setting:: CSRF_HEADER_NAME\n\n``CSRF_HEADER_NAME``\n--------------------\n\nDefault: ``'HTTP_X_CSRFTOKEN'``\n\nThe name of the request header used for CSRF authentication.\n\nAs with other HTTP headers in ``request.META``, the header name received from\nthe server is normalized by converting all characters to uppercase, replacing\nany hyphens with underscores, and adding an ``'HTTP_'`` prefix to the name.\nFor example, if your client sends a ``'X-XSRF-TOKEN'`` header, the setting\nshould be ``'HTTP_X_XSRF_TOKEN'``.\n\n.. setting:: CSRF_TRUSTED_ORIGINS\n\n``CSRF_TRUSTED_ORIGINS``\n------------------------\n\nDefault: ``[]`` (Empty list)\n\nA list of hosts which are trusted origins for unsafe requests (e.g. ``POST``).\nFor a :meth:`secure <django.http.HttpRequest.is_secure>` unsafe\nrequest, Django's CSRF protection requires that the request have a ``Referer``\nheader that matches the origin present in the ``Host`` header. This prevents,\nfor example, a ``POST`` request from ``subdomain.example.com`` from succeeding\nagainst ``api.example.com``. If you need cross-origin unsafe requests over\nHTTPS, continuing the example, add ``\"subdomain.example.com\"`` to this list.\nThe setting also supports subdomains, so you could add ``\".example.com\"``, for\nexample, to allow access from all subdomains of ``example.com``.\n\n.. setting:: DATABASES\n\n``DATABASES``\n-------------\n\nDefault: ``{}`` (Empty dictionary)\n\nA dictionary containing the settings for all databases to be used with\nDjango. It is a nested dictionary whose contents map a database alias\nto a dictionary containing the options for an individual database.\n\nThe :setting:`DATABASES` setting must configure a ``default`` database;\nany number of additional databases may also be specified.\n\nThe simplest possible settings file is for a single-database setup using\nSQLite. This can be configured using the following::\n\n    DATABASES = {\n        'default': {\n            'ENGINE': 'django.db.backends.sqlite3',\n            'NAME': 'mydatabase',\n        }\n    }\n\nWhen connecting to other database backends, such as MariaDB, MySQL, Oracle, or\nPostgreSQL, additional connection parameters will be required. See\nthe :setting:`ENGINE <DATABASE-ENGINE>` setting below on how to specify\nother database types. This example is for PostgreSQL::\n\n    DATABASES = {\n        'default': {\n            'ENGINE': 'django.db.backends.postgresql',\n            'NAME': 'mydatabase',\n            'USER': 'mydatabaseuser',\n            'PASSWORD': 'mypassword',\n            'HOST': '127.0.0.1',\n            'PORT': '5432',\n        }\n    }\n\nThe following inner options that may be required for more complex\nconfigurations are available:\n\n.. setting:: DATABASE-ATOMIC_REQUESTS\n\n``ATOMIC_REQUESTS``\n~~~~~~~~~~~~~~~~~~~\n\nDefault: ``False``\n\nSet this to ``True`` to wrap each view in a transaction on this database. See\n:ref:`tying-transactions-to-http-requests`.\n\n.. setting:: DATABASE-AUTOCOMMIT\n\n``AUTOCOMMIT``\n~~~~~~~~~~~~~~\n\nDefault: ``True``\n\nSet this to ``False`` if you want to :ref:`disable Django's transaction\nmanagement <deactivate-transaction-management>` and implement your own.\n\n.. setting:: DATABASE-ENGINE\n\n``ENGINE``\n~~~~~~~~~~\n\nDefault: ``''`` (Empty string)\n\nThe database backend to use. The built-in database backends are:\n\n* ``'django.db.backends.postgresql'``\n* ``'django.db.backends.mysql'``\n* ``'django.db.backends.sqlite3'``\n* ``'django.db.backends.oracle'``\n\nYou can use a database backend that doesn't ship with Django by setting\n``ENGINE`` to a fully-qualified path (i.e. ``mypackage.backends.whatever``).\n\n.. setting:: HOST\n\n``HOST``\n~~~~~~~~\n\nDefault: ``''`` (Empty string)\n\nWhich host to use when connecting to the database. An empty string means\nlocalhost. Not used with SQLite.\n\nIf this value starts with a forward slash (``'/'``) and you're using MySQL,\nMySQL will connect via a Unix socket to the specified socket. For example::\n\n    \"HOST\": '/var/run/mysql'\n\nIf you're using MySQL and this value *doesn't* start with a forward slash, then\nthis value is assumed to be the host.\n\nIf you're using PostgreSQL, by default (empty :setting:`HOST`), the connection\nto the database is done through UNIX domain sockets ('local' lines in\n``pg_hba.conf``). If your UNIX domain socket is not in the standard location,\nuse the same value of ``unix_socket_directory`` from ``postgresql.conf``.\nIf you want to connect through TCP sockets, set :setting:`HOST` to 'localhost'\nor '127.0.0.1' ('host' lines in ``pg_hba.conf``).\nOn Windows, you should always define :setting:`HOST`, as UNIX domain sockets\nare not available.\n\n.. setting:: NAME\n\n``NAME``\n~~~~~~~~\n\nDefault: ``''`` (Empty string)\n\nThe name of the database to use. For SQLite, it's the full path to the database\nfile. When specifying the path, always use forward slashes, even on Windows\n(e.g. ``C:/homes/user/mysite/sqlite3.db``).\n\n.. setting:: CONN_MAX_AGE\n\n``CONN_MAX_AGE``\n~~~~~~~~~~~~~~~~\n\nDefault: ``0``\n\nThe lifetime of a database connection, as an integer of seconds. Use ``0`` to\nclose database connections at the end of each request — Django's historical\nbehavior — and ``None`` for unlimited persistent connections.\n\n.. setting:: OPTIONS\n\n``OPTIONS``\n~~~~~~~~~~~\n\nDefault: ``{}`` (Empty dictionary)\n\nExtra parameters to use when connecting to the database. Available parameters\nvary depending on your database backend.\n\nSome information on available parameters can be found in the\n:doc:`Database Backends </ref/databases>` documentation. For more information,\nconsult your backend module's own documentation.\n\n.. setting:: PASSWORD\n\n``PASSWORD``\n~~~~~~~~~~~~\n\nDefault: ``''`` (Empty string)\n\nThe password to use when connecting to the database. Not used with SQLite.\n\n.. setting:: PORT\n\n``PORT``\n~~~~~~~~\n\nDefault: ``''`` (Empty string)\n\nThe port to use when connecting to the database. An empty string means the\ndefault port. Not used with SQLite.\n\n.. setting:: DATABASE-TIME_ZONE\n\n``TIME_ZONE``\n~~~~~~~~~~~~~\n\nDefault: ``None``\n\nA string representing the time zone for this database connection or ``None``.\nThis inner option of the :setting:`DATABASES` setting accepts the same values\nas the general :setting:`TIME_ZONE` setting.\n\nWhen :setting:`USE_TZ` is ``True`` and this option is set, reading datetimes\nfrom the database returns aware datetimes in this time zone instead of UTC.\nWhen :setting:`USE_TZ` is ``False``, it is an error to set this option.\n\n* If the database backend doesn't support time zones (e.g. SQLite, MySQL,\n  Oracle), Django reads and writes datetimes in local time according to this\n  option if it is set and in UTC if it isn't.\n\n  Changing the connection time zone changes how datetimes are read from and\n  written to the database.\n\n  * If Django manages the database and you don't have a strong reason to do\n    otherwise, you should leave this option unset. It's best to store datetimes\n    in UTC because it avoids ambiguous or nonexistent datetimes during daylight\n    saving time changes. Also, receiving datetimes in UTC keeps datetime\n    arithmetic simple — there's no need for the ``normalize()`` method provided\n    by pytz.\n\n  * If you're connecting to a third-party database that stores datetimes in a\n    local time rather than UTC, then you must set this option to the\n    appropriate time zone. Likewise, if Django manages the database but\n    third-party systems connect to the same database and expect to find\n    datetimes in local time, then you must set this option.\n\n* If the database backend supports time zones (e.g. PostgreSQL), the\n  ``TIME_ZONE`` option is very rarely needed. It can be changed at any time;\n  the database takes care of converting datetimes to the desired time zone.\n\n  Setting the time zone of the database connection may be useful for running\n  raw SQL queries involving date/time functions provided by the database, such\n  as ``date_trunc``, because their results depend on the time zone.\n\n  However, this has a downside: receiving all datetimes in local time makes\n  datetime arithmetic more tricky — you must call the ``normalize()`` method\n  provided by pytz after each operation.\n\n  Consider converting to local time explicitly with ``AT TIME ZONE`` in raw SQL\n  queries instead of setting the ``TIME_ZONE`` option.\n\n.. versionchanged:: 3.1\n\n  Using this option when the database backend supports time zones was allowed.\n\n.. setting:: DATABASE-DISABLE_SERVER_SIDE_CURSORS\n\n``DISABLE_SERVER_SIDE_CURSORS``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nDefault: ``False``\n\nSet this to ``True`` if you want to disable the use of server-side cursors with\n:meth:`.QuerySet.iterator`. :ref:`transaction-pooling-server-side-cursors`\ndescribes the use case.\n\nThis is a PostgreSQL-specific setting.\n\n.. setting:: USER\n\n``USER``\n~~~~~~~~\n\nDefault: ``''`` (Empty string)\n\nThe username to use when connecting to the database. Not used with SQLite.\n\n.. setting:: DATABASE-TEST\n\n``TEST``\n~~~~~~~~\n\nDefault: ``{}`` (Empty dictionary)\n\nA dictionary of settings for test databases; for more details about the\ncreation and use of test databases, see :ref:`the-test-database`.\n\nHere's an example with a test database configuration::\n\n    DATABASES = {\n        'default': {\n            'ENGINE': 'django.db.backends.postgresql',\n            'USER': 'mydatabaseuser',\n            'NAME': 'mydatabase',\n            'TEST': {\n                'NAME': 'mytestdatabase',\n            },\n        },\n    }\n\nThe following keys in the ``TEST`` dictionary are available:\n\n.. setting:: TEST_CHARSET\n\n``CHARSET``\n^^^^^^^^^^^\n\nDefault: ``None``\n\nThe character set encoding used to create the test database. The value of this\nstring is passed directly through to the database, so its format is\nbackend-specific.\n\nSupported by the PostgreSQL_ (``postgresql``) and MySQL_ (``mysql``) backends.\n\n.. _PostgreSQL: https://www.postgresql.org/docs/current/multibyte.html\n.. _MySQL: https://dev.mysql.com/doc/refman/en/charset-charsets.html\n\n.. setting:: TEST_COLLATION\n\n``COLLATION``\n^^^^^^^^^^^^^\n\nDefault: ``None``\n\nThe collation order to use when creating the test database. This value is\npassed directly to the backend, so its format is backend-specific.\n\nOnly supported for the ``mysql`` backend (see the `MySQL manual`_ for details).\n\n.. _MySQL manual: MySQL_\n\n.. setting:: TEST_DEPENDENCIES\n\n``DEPENDENCIES``\n^^^^^^^^^^^^^^^^\n\nDefault: ``['default']``, for all databases other than ``default``,\nwhich has no dependencies.\n\nThe creation-order dependencies of the database. See the documentation\non :ref:`controlling the creation order of test databases\n<topics-testing-creation-dependencies>` for details.\n\n.. setting:: TEST_MIGRATE\n\n``MIGRATE``\n^^^^^^^^^^^\n\n.. versionadded:: 3.1\n\nDefault: ``True``\n\nWhen set to ``False``, migrations won't run when creating the test database.\n\n.. setting:: TEST_MIRROR\n\n``MIRROR``\n^^^^^^^^^^\n\nDefault: ``None``\n\nThe alias of the database that this database should mirror during\ntesting.\n\nThis setting exists to allow for testing of primary/replica\n(referred to as master/slave by some databases)\nconfigurations of multiple databases. See the documentation on\n:ref:`testing primary/replica configurations\n<topics-testing-primaryreplica>` for details.\n\n.. setting:: TEST_NAME\n\n``NAME``\n^^^^^^^^\n\nDefault: ``None``\n\nThe name of database to use when running the test suite.\n\nIf the default value (``None``) is used with the SQLite database engine, the\ntests will use a memory resident database. For all other database engines the\ntest database will use the name ``'test_' + DATABASE_NAME``.\n\nSee :ref:`the-test-database`.\n\n.. setting:: TEST_SERIALIZE\n\n``SERIALIZE``\n^^^^^^^^^^^^^\n\nBoolean value to control whether or not the default test runner serializes the\ndatabase into an in-memory JSON string before running tests (used to restore\nthe database state between tests if you don't have transactions). You can set\nthis to ``False`` to speed up creation time if you don't have any test classes\nwith :ref:`serialized_rollback=True <test-case-serialized-rollback>`.\n\n.. setting:: TEST_TEMPLATE\n\n``TEMPLATE``\n^^^^^^^^^^^^\n\nThis is a PostgreSQL-specific setting.\n\nThe name of a `template`_ (e.g. ``'template0'``) from which to create the test\ndatabase.\n\n.. _template: https://www.postgresql.org/docs/current/sql-createdatabase.html\n\n.. setting:: TEST_CREATE\n\n``CREATE_DB``\n^^^^^^^^^^^^^\n\nDefault: ``True``\n\nThis is an Oracle-specific setting.\n\nIf it is set to ``False``, the test tablespaces won't be automatically created\nat the beginning of the tests or dropped at the end.\n\n.. setting:: TEST_USER_CREATE\n\n``CREATE_USER``\n^^^^^^^^^^^^^^^\n\nDefault: ``True``\n\nThis is an Oracle-specific setting.\n\nIf it is set to ``False``, the test user won't be automatically created at the\nbeginning of the tests and dropped at the end.\n\n.. setting:: TEST_USER\n\n``USER``\n^^^^^^^^\n\nDefault: ``None``\n\nThis is an Oracle-specific setting.\n\nThe username to use when connecting to the Oracle database that will be used\nwhen running tests. If not provided, Django will use ``'test_' + USER``.\n\n.. setting:: TEST_PASSWD\n\n``PASSWORD``\n^^^^^^^^^^^^\n\nDefault: ``None``\n\nThis is an Oracle-specific setting.\n\nThe password to use when connecting to the Oracle database that will be used\nwhen running tests. If not provided, Django will generate a random password.\n\n.. setting:: TEST_ORACLE_MANAGED_FILES\n\n``ORACLE_MANAGED_FILES``\n^^^^^^^^^^^^^^^^^^^^^^^^\n\nDefault: ``False``\n\nThis is an Oracle-specific setting.\n\nIf set to ``True``, Oracle Managed Files (OMF) tablespaces will be used.\n:setting:`DATAFILE` and :setting:`DATAFILE_TMP` will be ignored.\n\n.. setting:: TEST_TBLSPACE\n\n``TBLSPACE``\n^^^^^^^^^^^^\n\nDefault: ``None``\n\nThis is an Oracle-specific setting.\n\nThe name of the tablespace that will be used when running tests. If not\nprovided, Django will use ``'test_' + USER``.\n\n.. setting:: TEST_TBLSPACE_TMP\n\n``TBLSPACE_TMP``\n^^^^^^^^^^^^^^^^\n\nDefault: ``None``\n\nThis is an Oracle-specific setting.\n\nThe name of the temporary tablespace that will be used when running tests. If\nnot provided, Django will use ``'test_' + USER + '_temp'``.\n\n.. setting:: DATAFILE\n\n``DATAFILE``\n^^^^^^^^^^^^\n\nDefault: ``None``\n\nThis is an Oracle-specific setting.\n\nThe name of the datafile to use for the TBLSPACE. If not provided, Django will\nuse ``TBLSPACE + '.dbf'``.\n\n.. setting:: DATAFILE_TMP\n\n``DATAFILE_TMP``\n^^^^^^^^^^^^^^^^\n\nDefault: ``None``\n\nThis is an Oracle-specific setting.\n\nThe name of the datafile to use for the TBLSPACE_TMP. If not provided, Django\nwill use ``TBLSPACE_TMP + '.dbf'``.\n\n.. setting:: DATAFILE_MAXSIZE\n\n``DATAFILE_MAXSIZE``\n^^^^^^^^^^^^^^^^^^^^\n\nDefault: ``'500M'``\n\nThis is an Oracle-specific setting.\n\nThe maximum size that the DATAFILE is allowed to grow to.\n\n.. setting:: DATAFILE_TMP_MAXSIZE\n\n``DATAFILE_TMP_MAXSIZE``\n^^^^^^^^^^^^^^^^^^^^^^^^\n\nDefault: ``'500M'``\n\nThis is an Oracle-specific setting.\n\nThe maximum size that the DATAFILE_TMP is allowed to grow to.\n\n.. setting:: DATAFILE_SIZE\n\n``DATAFILE_SIZE``\n^^^^^^^^^^^^^^^^^\n\nDefault: ``'50M'``\n\nThis is an Oracle-specific setting.\n\nThe initial size of the DATAFILE.\n\n.. setting:: DATAFILE_TMP_SIZE\n\n``DATAFILE_TMP_SIZE``\n^^^^^^^^^^^^^^^^^^^^^\n\nDefault: ``'50M'``\n\nThis is an Oracle-specific setting.\n\nThe initial size of the DATAFILE_TMP.\n\n.. setting:: DATAFILE_EXTSIZE\n\n``DATAFILE_EXTSIZE``\n^^^^^^^^^^^^^^^^^^^^\n\nDefault: ``'25M'``\n\nThis is an Oracle-specific setting.\n\nThe amount by which the DATAFILE is extended when more space is required.\n\n.. setting:: DATAFILE_TMP_EXTSIZE\n\n``DATAFILE_TMP_EXTSIZE``\n^^^^^^^^^^^^^^^^^^^^^^^^\n\nDefault: ``'25M'``\n\nThis is an Oracle-specific setting.\n\nThe amount by which the DATAFILE_TMP is extended when more space is required.\n\n.. setting:: DATA_UPLOAD_MAX_MEMORY_SIZE\n\nDATA_UPLOAD_MAX_MEMORY_SIZE\n---------------------------\n\nDefault: ``2621440`` (i.e. 2.5 MB).\n\nThe maximum size in bytes that a request body may be before a\n:exc:`~django.core.exceptions.SuspiciousOperation` (``RequestDataTooBig``) is\nraised. The check is done when accessing ``request.body`` or ``request.POST``\nand is calculated against the total request size excluding any file upload\ndata. You can set this to ``None`` to disable the check. Applications that are\nexpected to receive unusually large form posts should tune this setting.\n\nThe amount of request data is correlated to the amount of memory needed to\nprocess the request and populate the GET and POST dictionaries. Large requests\ncould be used as a denial-of-service attack vector if left unchecked. Since web\nservers don't typically perform deep request inspection, it's not possible to\nperform a similar check at that level.\n\nSee also :setting:`FILE_UPLOAD_MAX_MEMORY_SIZE`.\n\n.. setting:: DATA_UPLOAD_MAX_NUMBER_FIELDS\n\nDATA_UPLOAD_MAX_NUMBER_FIELDS\n-----------------------------\n\nDefault: ``1000``\n\nThe maximum number of parameters that may be received via GET or POST before a\n:exc:`~django.core.exceptions.SuspiciousOperation` (``TooManyFields``) is\nraised. You can set this to ``None`` to disable the check. Applications that\nare expected to receive an unusually large number of form fields should tune\nthis setting.\n\nThe number of request parameters is correlated to the amount of time needed to\nprocess the request and populate the GET and POST dictionaries. Large requests\ncould be used as a denial-of-service attack vector if left unchecked. Since web\nservers don't typically perform deep request inspection, it's not possible to\nperform a similar check at that level.\n\n.. setting:: DATABASE_ROUTERS\n\n``DATABASE_ROUTERS``\n--------------------\n\nDefault: ``[]`` (Empty list)\n\nThe list of routers that will be used to determine which database\nto use when performing a database query.\n\nSee the documentation on :ref:`automatic database routing in multi\ndatabase configurations <topics-db-multi-db-routing>`.\n\n.. setting:: DATE_FORMAT\n\n``DATE_FORMAT``\n---------------\n\nDefault: ``'N j, Y'`` (e.g. ``Feb. 4, 2003``)\n\nThe default formatting to use for displaying date fields in any part of the\nsystem. Note that if :setting:`USE_L10N` is set to ``True``, then the\nlocale-dictated format has higher precedence and will be applied instead. See\n:tfilter:`allowed date format strings <date>`.\n\nSee also :setting:`DATETIME_FORMAT`, :setting:`TIME_FORMAT` and :setting:`SHORT_DATE_FORMAT`.\n\n.. setting:: DATE_INPUT_FORMATS\n\n``DATE_INPUT_FORMATS``\n----------------------\n\nDefault::\n\n    [\n        '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'\n        '%b %d %Y', '%b %d, %Y',            # 'Oct 25 2006', 'Oct 25, 2006'\n        '%d %b %Y', '%d %b, %Y',            # '25 Oct 2006', '25 Oct, 2006'\n        '%B %d %Y', '%B %d, %Y',            # 'October 25 2006', 'October 25, 2006'\n        '%d %B %Y', '%d %B, %Y',            # '25 October 2006', '25 October, 2006'\n    ]\n\nA list of formats that will be accepted when inputting data on a date field.\nFormats will be tried in order, using the first valid one. Note that these\nformat strings use Python's :ref:`datetime module syntax\n<strftime-strptime-behavior>`, not the format strings from the :tfilter:`date`\ntemplate filter.\n\nWhen :setting:`USE_L10N` is ``True``, the locale-dictated format has higher\nprecedence and will be applied instead.\n\nSee also :setting:`DATETIME_INPUT_FORMATS` and :setting:`TIME_INPUT_FORMATS`.\n\n.. setting:: DATETIME_FORMAT\n\n``DATETIME_FORMAT``\n-------------------\n\nDefault: ``'N j, Y, P'`` (e.g. ``Feb. 4, 2003, 4 p.m.``)\n\nThe default formatting to use for displaying datetime fields in any part of the\nsystem. Note that if :setting:`USE_L10N` is set to ``True``, then the\nlocale-dictated format has higher precedence and will be applied instead. See\n:tfilter:`allowed date format strings <date>`.\n\nSee also :setting:`DATE_FORMAT`, :setting:`TIME_FORMAT` and :setting:`SHORT_DATETIME_FORMAT`.\n\n.. setting:: DATETIME_INPUT_FORMATS\n\n``DATETIME_INPUT_FORMATS``\n--------------------------\n\nDefault::\n\n    [\n        '%Y-%m-%d %H:%M:%S',     # '2006-10-25 14:30:59'\n        '%Y-%m-%d %H:%M:%S.%f',  # '2006-10-25 14:30:59.000200'\n        '%Y-%m-%d %H:%M',        # '2006-10-25 14:30'\n        '%m/%d/%Y %H:%M:%S',     # '10/25/2006 14:30:59'\n        '%m/%d/%Y %H:%M:%S.%f',  # '10/25/2006 14:30:59.000200'\n        '%m/%d/%Y %H:%M',        # '10/25/2006 14:30'\n        '%m/%d/%y %H:%M:%S',     # '10/25/06 14:30:59'\n        '%m/%d/%y %H:%M:%S.%f',  # '10/25/06 14:30:59.000200'\n        '%m/%d/%y %H:%M',        # '10/25/06 14:30'\n    ]\n\nA list of formats that will be accepted when inputting data on a datetime\nfield. Formats will be tried in order, using the first valid one. Note that\nthese format strings use Python's :ref:`datetime module syntax\n<strftime-strptime-behavior>`, not the format strings from the :tfilter:`date`\ntemplate filter. Date-only formats are not included as datetime fields will\nautomatically try :setting:`DATE_INPUT_FORMATS` in last resort.\n\nWhen :setting:`USE_L10N` is ``True``, the locale-dictated format has higher\nprecedence and will be applied instead.\n\nSee also :setting:`DATE_INPUT_FORMATS` and :setting:`TIME_INPUT_FORMATS`.\n\n.. versionchanged:: 3.1\n\n    In older versions, the default is a list containing also date-only formats.\n\n.. setting:: DEBUG\n\n``DEBUG``\n---------\n\nDefault: ``False``\n\nA boolean that turns on/off debug mode.\n\nNever deploy a site into production with :setting:`DEBUG` turned on.\n\nOne of the main features of debug mode is the display of detailed error pages.\nIf your app raises an exception when :setting:`DEBUG` is ``True``, Django will\ndisplay a detailed traceback, including a lot of metadata about your\nenvironment, such as all the currently defined Django settings (from\n``settings.py``).\n\nAs a security measure, Django will *not* include settings that might be\nsensitive, such as :setting:`SECRET_KEY`. Specifically, it will exclude any\nsetting whose name includes any of the following:\n\n* ``'API'``\n* ``'KEY'``\n* ``'PASS'``\n* ``'SECRET'``\n* ``'SIGNATURE'``\n* ``'TOKEN'``\n\nNote that these are *partial* matches. ``'PASS'`` will also match PASSWORD,\njust as ``'TOKEN'`` will also match TOKENIZED and so on.\n\nStill, note that there are always going to be sections of your debug output\nthat are inappropriate for public consumption. File paths, configuration\noptions and the like all give attackers extra information about your server.\n\nIt is also important to remember that when running with :setting:`DEBUG`\nturned on, Django will remember every SQL query it executes. This is useful\nwhen you're debugging, but it'll rapidly consume memory on a production server.\n\nFinally, if :setting:`DEBUG` is ``False``, you also need to properly set\nthe :setting:`ALLOWED_HOSTS` setting. Failing to do so will result in all\nrequests being returned as \"Bad Request (400)\".\n\n.. note::\n\n    The default :file:`settings.py` file created by :djadmin:`django-admin\n    startproject <startproject>` sets ``DEBUG = True`` for convenience.\n\n.. setting:: DEBUG_PROPAGATE_EXCEPTIONS\n\n``DEBUG_PROPAGATE_EXCEPTIONS``\n------------------------------\n\nDefault: ``False``\n\nIf set to ``True``, Django's exception handling of view functions\n(:data:`~django.conf.urls.handler500`, or the debug view if :setting:`DEBUG`\nis ``True``) and logging of 500 responses (:ref:`django-request-logger`) is\nskipped and exceptions propagate upwards.\n\nThis can be useful for some test setups. It shouldn't be used on a live site\nunless you want your web server (instead of Django) to generate \"Internal\nServer Error\" responses. In that case, make sure your server doesn't show the\nstack trace or other sensitive information in the response.\n\n.. setting:: DECIMAL_SEPARATOR\n\n``DECIMAL_SEPARATOR``\n---------------------\n\nDefault: ``'.'`` (Dot)\n\nDefault decimal separator used when formatting decimal numbers.\n\nNote that if :setting:`USE_L10N` is set to ``True``, then the locale-dictated\nformat has higher precedence and will be applied instead.\n\nSee also :setting:`NUMBER_GROUPING`, :setting:`THOUSAND_SEPARATOR` and\n:setting:`USE_THOUSAND_SEPARATOR`.\n\n\n.. setting:: DEFAULT_CHARSET\n\n``DEFAULT_CHARSET``\n-------------------\n\nDefault: ``'utf-8'``\n\nDefault charset to use for all ``HttpResponse`` objects, if a MIME type isn't\nmanually specified. Used when constructing the ``Content-Type`` header.\n\n.. setting:: DEFAULT_EXCEPTION_REPORTER\n\n``DEFAULT_EXCEPTION_REPORTER``\n------------------------------\n\n.. versionadded:: 3.1\n\nDefault: ``'``:class:`django.views.debug.ExceptionReporter`\\ ``'``\n\nDefault exception reporter class to be used if none has been assigned to the\n:class:`~django.http.HttpRequest` instance yet. See\n:ref:`custom-error-reports`.\n\n.. setting:: DEFAULT_EXCEPTION_REPORTER_FILTER\n\n``DEFAULT_EXCEPTION_REPORTER_FILTER``\n-------------------------------------\n\nDefault: ``'``:class:`django.views.debug.SafeExceptionReporterFilter`\\ ``'``\n\nDefault exception reporter filter class to be used if none has been assigned to\nthe :class:`~django.http.HttpRequest` instance yet.\nSee :ref:`Filtering error reports<filtering-error-reports>`.\n\n.. setting:: DEFAULT_FILE_STORAGE\n\n``DEFAULT_FILE_STORAGE``\n------------------------\n\nDefault: ``'``:class:`django.core.files.storage.FileSystemStorage`\\ ``'``\n\nDefault file storage class to be used for any file-related operations that don't\nspecify a particular storage system. See :doc:`/topics/files`.\n\n.. setting:: DEFAULT_FROM_EMAIL\n\n``DEFAULT_FROM_EMAIL``\n----------------------\n\nDefault: ``'webmaster@localhost'``\n\nDefault email address to use for various automated correspondence from the\nsite manager(s). This doesn't include error messages sent to :setting:`ADMINS`\nand :setting:`MANAGERS`; for that, see :setting:`SERVER_EMAIL`.\n\n.. setting:: DEFAULT_INDEX_TABLESPACE\n\n``DEFAULT_INDEX_TABLESPACE``\n----------------------------\n\nDefault: ``''`` (Empty string)\n\nDefault tablespace to use for indexes on fields that don't specify\none, if the backend supports it (see :doc:`/topics/db/tablespaces`).\n\n.. setting:: DEFAULT_TABLESPACE\n\n``DEFAULT_TABLESPACE``\n----------------------\n\nDefault: ``''`` (Empty string)\n\nDefault tablespace to use for models that don't specify one, if the\nbackend supports it (see :doc:`/topics/db/tablespaces`).\n\n.. setting:: DISALLOWED_USER_AGENTS\n\n``DISALLOWED_USER_AGENTS``\n--------------------------\n\nDefault: ``[]`` (Empty list)\n\nList of compiled regular expression objects representing User-Agent strings\nthat are not allowed to visit any page, systemwide. Use this for bots/crawlers.\nThis is only used if ``CommonMiddleware`` is installed (see\n:doc:`/topics/http/middleware`).\n\n.. setting:: EMAIL_BACKEND\n\n``EMAIL_BACKEND``\n-----------------\n\nDefault: ``'``:class:`django.core.mail.backends.smtp.EmailBackend`\\ ``'``\n\nThe backend to use for sending emails. For the list of available backends see\n:doc:`/topics/email`.\n\n.. setting:: EMAIL_FILE_PATH\n\n``EMAIL_FILE_PATH``\n-------------------\n\nDefault: Not defined\n\nThe directory used by the :ref:`file email backend <topic-email-file-backend>`\nto store output files.\n\n.. versionchanged:: 3.1\n\n    Support for :class:`pathlib.Path` was added.\n\n.. setting:: EMAIL_HOST\n\n``EMAIL_HOST``\n--------------\n\nDefault: ``'localhost'``\n\nThe host to use for sending email.\n\nSee also :setting:`EMAIL_PORT`.\n\n.. setting:: EMAIL_HOST_PASSWORD\n\n``EMAIL_HOST_PASSWORD``\n-----------------------\n\nDefault: ``''`` (Empty string)\n\nPassword to use for the SMTP server defined in :setting:`EMAIL_HOST`. This\nsetting is used in conjunction with :setting:`EMAIL_HOST_USER` when\nauthenticating to the SMTP server. If either of these settings is empty,\nDjango won't attempt authentication.\n\nSee also :setting:`EMAIL_HOST_USER`.\n\n.. setting:: EMAIL_HOST_USER\n\n``EMAIL_HOST_USER``\n-------------------\n\nDefault: ``''`` (Empty string)\n\nUsername to use for the SMTP server defined in :setting:`EMAIL_HOST`.\nIf empty, Django won't attempt authentication.\n\nSee also :setting:`EMAIL_HOST_PASSWORD`.\n\n.. setting:: EMAIL_PORT\n\n``EMAIL_PORT``\n--------------\n\nDefault: ``25``\n\nPort to use for the SMTP server defined in :setting:`EMAIL_HOST`.\n\n.. setting:: EMAIL_SUBJECT_PREFIX\n\n``EMAIL_SUBJECT_PREFIX``\n------------------------\n\nDefault: ``'[Django] '``\n\nSubject-line prefix for email messages sent with ``django.core.mail.mail_admins``\nor ``django.core.mail.mail_managers``. You'll probably want to include the\ntrailing space.\n\n.. setting:: EMAIL_USE_LOCALTIME\n\n``EMAIL_USE_LOCALTIME``\n-----------------------\n\nDefault: ``False``\n\nWhether to send the SMTP ``Date`` header of email messages in the local time\nzone (``True``) or in UTC (``False``).\n\n.. setting:: EMAIL_USE_TLS\n\n``EMAIL_USE_TLS``\n-----------------\n\nDefault: ``False``\n\nWhether to use a TLS (secure) connection when talking to the SMTP server.\nThis is used for explicit TLS connections, generally on port 587. If you are\nexperiencing hanging connections, see the implicit TLS setting\n:setting:`EMAIL_USE_SSL`.\n\n.. setting:: EMAIL_USE_SSL\n\n``EMAIL_USE_SSL``\n-----------------\n\nDefault: ``False``\n\nWhether to use an implicit TLS (secure) connection when talking to the SMTP\nserver. In most email documentation this type of TLS connection is referred\nto as SSL. It is generally used on port 465. If you are experiencing problems,\nsee the explicit TLS setting :setting:`EMAIL_USE_TLS`.\n\nNote that :setting:`EMAIL_USE_TLS`/:setting:`EMAIL_USE_SSL` are mutually\nexclusive, so only set one of those settings to ``True``.\n\n.. setting:: EMAIL_SSL_CERTFILE\n\n``EMAIL_SSL_CERTFILE``\n----------------------\n\nDefault: ``None``\n\nIf :setting:`EMAIL_USE_SSL` or :setting:`EMAIL_USE_TLS` is ``True``, you can\noptionally specify the path to a PEM-formatted certificate chain file to use\nfor the SSL connection.\n\n.. setting:: EMAIL_SSL_KEYFILE\n\n``EMAIL_SSL_KEYFILE``\n---------------------\n\nDefault: ``None``\n\nIf :setting:`EMAIL_USE_SSL` or :setting:`EMAIL_USE_TLS` is ``True``, you can\noptionally specify the path to a PEM-formatted private key file to use for the\nSSL connection.\n\nNote that setting :setting:`EMAIL_SSL_CERTFILE` and :setting:`EMAIL_SSL_KEYFILE`\ndoesn't result in any certificate checking. They're passed to the underlying SSL\nconnection. Please refer to the documentation of Python's\n:func:`python:ssl.wrap_socket` function for details on how the certificate chain\nfile and private key file are handled.\n\n.. setting:: EMAIL_TIMEOUT\n\n``EMAIL_TIMEOUT``\n-----------------\n\nDefault: ``None``\n\nSpecifies a timeout in seconds for blocking operations like the connection\nattempt.\n\n.. setting:: FILE_UPLOAD_HANDLERS\n\n``FILE_UPLOAD_HANDLERS``\n------------------------\n\nDefault::\n\n    [\n        'django.core.files.uploadhandler.MemoryFileUploadHandler',\n        'django.core.files.uploadhandler.TemporaryFileUploadHandler',\n    ]\n\nA list of handlers to use for uploading. Changing this setting allows complete\ncustomization -- even replacement -- of Django's upload process.\n\nSee :doc:`/topics/files` for details.\n\n.. setting:: FILE_UPLOAD_MAX_MEMORY_SIZE\n\n``FILE_UPLOAD_MAX_MEMORY_SIZE``\n-------------------------------\n\nDefault: ``2621440`` (i.e. 2.5 MB).\n\nThe maximum size (in bytes) that an upload will be before it gets streamed to\nthe file system. See :doc:`/topics/files` for details.\n\nSee also :setting:`DATA_UPLOAD_MAX_MEMORY_SIZE`.\n\n.. setting:: FILE_UPLOAD_DIRECTORY_PERMISSIONS\n\n``FILE_UPLOAD_DIRECTORY_PERMISSIONS``\n-------------------------------------\n\nDefault: ``None``\n\nThe numeric mode to apply to directories created in the process of uploading\nfiles.\n\nThis setting also determines the default permissions for collected static\ndirectories when using the :djadmin:`collectstatic` management command. See\n:djadmin:`collectstatic` for details on overriding it.\n\nThis value mirrors the functionality and caveats of the\n:setting:`FILE_UPLOAD_PERMISSIONS` setting.\n\n.. setting:: FILE_UPLOAD_PERMISSIONS\n\n``FILE_UPLOAD_PERMISSIONS``\n---------------------------\n\nDefault: ``0o644``\n\nThe numeric mode (i.e. ``0o644``) to set newly uploaded files to. For\nmore information about what these modes mean, see the documentation for\n:func:`os.chmod`.\n\nIf this isn't given or is ``None``, you'll get operating-system\ndependent behavior. On most platforms, temporary files will have a mode\nof ``0o600``, and files saved from memory will be saved using the\nsystem's standard umask.\n\nFor security reasons, these permissions aren't applied to the temporary files\nthat are stored in :setting:`FILE_UPLOAD_TEMP_DIR`.\n\nThis setting also determines the default permissions for collected static files\nwhen using the :djadmin:`collectstatic` management command. See\n:djadmin:`collectstatic` for details on overriding it.\n\n.. warning::\n\n    **Always prefix the mode with a 0.**\n\n    If you're not familiar with file modes, please note that the leading\n    ``0`` is very important: it indicates an octal number, which is the\n    way that modes must be specified. If you try to use ``644``, you'll\n    get totally incorrect behavior.\n\n.. setting:: FILE_UPLOAD_TEMP_DIR\n\n``FILE_UPLOAD_TEMP_DIR``\n------------------------\n\nDefault: ``None``\n\nThe directory to store data to (typically files larger than\n:setting:`FILE_UPLOAD_MAX_MEMORY_SIZE`) temporarily while uploading files.\nIf ``None``, Django will use the standard temporary directory for the operating\nsystem. For example, this will default to ``/tmp`` on \\*nix-style operating\nsystems.\n\nSee :doc:`/topics/files` for details.\n\n.. setting:: FIRST_DAY_OF_WEEK\n\n``FIRST_DAY_OF_WEEK``\n---------------------\n\nDefault: ``0`` (Sunday)\n\nA number representing the first day of the week. This is especially useful\nwhen displaying a calendar. This value is only used when not using\nformat internationalization, or when a format cannot be found for the\ncurrent locale.\n\nThe value must be an integer from 0 to 6, where 0 means Sunday, 1 means\nMonday and so on.\n\n.. setting:: FIXTURE_DIRS\n\n``FIXTURE_DIRS``\n----------------\n\nDefault: ``[]`` (Empty list)\n\nList of directories searched for fixture files, in addition to the\n``fixtures`` directory of each application, in search order.\n\nNote that these paths should use Unix-style forward slashes, even on Windows.\n\nSee :ref:`initial-data-via-fixtures` and :ref:`topics-testing-fixtures`.\n\n.. setting:: FORCE_SCRIPT_NAME\n\n``FORCE_SCRIPT_NAME``\n---------------------\n\nDefault: ``None``\n\nIf not ``None``, this will be used as the value of the ``SCRIPT_NAME``\nenvironment variable in any HTTP request. This setting can be used to override\nthe server-provided value of ``SCRIPT_NAME``, which may be a rewritten version\nof the preferred value or not supplied at all. It is also used by\n:func:`django.setup()` to set the URL resolver script prefix outside of the\nrequest/response cycle (e.g. in management commands and standalone scripts) to\ngenerate correct URLs when ``SCRIPT_NAME`` is not ``/``.\n\n.. setting:: FORM_RENDERER\n\n``FORM_RENDERER``\n-----------------\n\nDefault: ``'``:class:`django.forms.renderers.DjangoTemplates`\\ ``'``\n\nThe class that renders form widgets. It must implement :ref:`the low-level\nrender API <low-level-widget-render-api>`.\n\n.. setting:: FORMAT_MODULE_PATH\n\n``FORMAT_MODULE_PATH``\n----------------------\n\nDefault: ``None``\n\nA full Python path to a Python package that contains custom format definitions\nfor project locales. If not ``None``, Django will check for a ``formats.py``\nfile, under the directory named as the current locale, and will use the\nformats defined in this file.\n\nFor example, if :setting:`FORMAT_MODULE_PATH` is set to ``mysite.formats``,\nand current language is ``en`` (English), Django will expect a directory tree\nlike::\n\n    mysite/\n        formats/\n            __init__.py\n            en/\n                __init__.py\n                formats.py\n\nYou can also set this setting to a list of Python paths, for example::\n\n    FORMAT_MODULE_PATH = [\n        'mysite.formats',\n        'some_app.formats',\n    ]\n\nWhen Django searches for a certain format, it will go through all given Python\npaths until it finds a module that actually defines the given format. This\nmeans that formats defined in packages farther up in the list will take\nprecedence over the same formats in packages farther down.\n\nAvailable formats are:\n\n* :setting:`DATE_FORMAT`\n* :setting:`DATE_INPUT_FORMATS`\n* :setting:`DATETIME_FORMAT`,\n* :setting:`DATETIME_INPUT_FORMATS`\n* :setting:`DECIMAL_SEPARATOR`\n* :setting:`FIRST_DAY_OF_WEEK`\n* :setting:`MONTH_DAY_FORMAT`\n* :setting:`NUMBER_GROUPING`\n* :setting:`SHORT_DATE_FORMAT`\n* :setting:`SHORT_DATETIME_FORMAT`\n* :setting:`THOUSAND_SEPARATOR`\n* :setting:`TIME_FORMAT`\n* :setting:`TIME_INPUT_FORMATS`\n* :setting:`YEAR_MONTH_FORMAT`\n\n.. setting:: IGNORABLE_404_URLS\n\n``IGNORABLE_404_URLS``\n----------------------\n\nDefault: ``[]`` (Empty list)\n\nList of compiled regular expression objects describing URLs that should be\nignored when reporting HTTP 404 errors via email (see\n:doc:`/howto/error-reporting`). Regular expressions are matched against\n:meth:`request's full paths <django.http.HttpRequest.get_full_path>` (including\nquery string, if any). Use this if your site does not provide a commonly\nrequested file such as ``favicon.ico`` or ``robots.txt``.\n\nThis is only used if\n:class:`~django.middleware.common.BrokenLinkEmailsMiddleware` is enabled (see\n:doc:`/topics/http/middleware`).\n\n.. setting:: INSTALLED_APPS\n\n``INSTALLED_APPS``\n------------------\n\nDefault: ``[]`` (Empty list)\n\nA list of strings designating all applications that are enabled in this\nDjango installation. Each string should be a dotted Python path to:\n\n* an application configuration class (preferred), or\n* a package containing an application.\n\n:doc:`Learn more about application configurations </ref/applications>`.\n\n.. admonition:: Use the application registry for introspection\n\n    Your code should never access :setting:`INSTALLED_APPS` directly. Use\n    :attr:`django.apps.apps` instead.\n\n.. admonition:: Application names and labels must be unique in\n                :setting:`INSTALLED_APPS`\n\n    Application :attr:`names <django.apps.AppConfig.name>` — the dotted Python\n    path to the application package — must be unique. There is no way to\n    include the same application twice, short of duplicating its code under\n    another name.\n\n    Application :attr:`labels <django.apps.AppConfig.label>` — by default the\n    final part of the name — must be unique too. For example, you can't\n    include both ``django.contrib.auth`` and ``myproject.auth``. However, you\n    can relabel an application with a custom configuration that defines a\n    different :attr:`~django.apps.AppConfig.label`.\n\n    These rules apply regardless of whether :setting:`INSTALLED_APPS`\n    references application configuration classes or application packages.\n\nWhen several applications provide different versions of the same resource\n(template, static file, management command, translation), the application\nlisted first in :setting:`INSTALLED_APPS` has precedence.\n\n.. setting:: INTERNAL_IPS\n\n``INTERNAL_IPS``\n----------------\n\nDefault: ``[]`` (Empty list)\n\nA list of IP addresses, as strings, that:\n\n* Allow the :func:`~django.template.context_processors.debug` context processor\n  to add some variables to the template context.\n* Can use the :ref:`admindocs bookmarklets <admindocs-bookmarklets>` even if\n  not logged in as a staff user.\n* Are marked as \"internal\" (as opposed to \"EXTERNAL\") in\n  :class:`~django.utils.log.AdminEmailHandler` emails.\n\n.. setting:: LANGUAGE_CODE\n\n``LANGUAGE_CODE``\n-----------------\n\nDefault: ``'en-us'``\n\nA string representing the language code for this installation. This should be in\nstandard :term:`language ID format <language code>`. For example, U.S. English\nis ``\"en-us\"``. See also the `list of language identifiers`_ and\n:doc:`/topics/i18n/index`.\n\n:setting:`USE_I18N` must be active for this setting to have any effect.\n\nIt serves two purposes:\n\n* If the locale middleware isn't in use, it decides which translation is served\n  to all users.\n* If the locale middleware is active, it provides a fallback language in case the\n  user's preferred language can't be determined or is not supported by the\n  website. It also provides the fallback translation when a translation for a\n  given literal doesn't exist for the user's preferred language.\n\nSee :ref:`how-django-discovers-language-preference` for more details.\n\n.. _list of language identifiers: http://www.i18nguy.com/unicode/language-identifiers.html\n\n.. setting:: LANGUAGE_COOKIE_AGE\n\n``LANGUAGE_COOKIE_AGE``\n-----------------------\n\nDefault: ``None`` (expires at browser close)\n\nThe age of the language cookie, in seconds.\n\n.. setting:: LANGUAGE_COOKIE_DOMAIN\n\n``LANGUAGE_COOKIE_DOMAIN``\n--------------------------\n\nDefault: ``None``\n\nThe domain to use for the language cookie. Set this to a string such as\n``\"example.com\"`` for cross-domain cookies, or use ``None`` for a standard\ndomain cookie.\n\nBe cautious when updating this setting on a production site. If you update\nthis setting to enable cross-domain cookies on a site that previously used\nstandard domain cookies, existing user cookies that have the old domain\nwill not be updated. This will result in site users being unable to switch\nthe language as long as these cookies persist. The only safe and reliable\noption to perform the switch is to change the language cookie name\npermanently (via the :setting:`LANGUAGE_COOKIE_NAME` setting) and to add\na middleware that copies the value from the old cookie to a new one and then\ndeletes the old one.\n\n.. setting:: LANGUAGE_COOKIE_HTTPONLY\n\n``LANGUAGE_COOKIE_HTTPONLY``\n----------------------------\n\nDefault: ``False``\n\nWhether to use ``HttpOnly`` flag on the language cookie. If this is set to\n``True``, client-side JavaScript will not be able to access the language\ncookie.\n\nSee :setting:`SESSION_COOKIE_HTTPONLY` for details on ``HttpOnly``.\n\n.. setting:: LANGUAGE_COOKIE_NAME\n\n``LANGUAGE_COOKIE_NAME``\n------------------------\n\nDefault: ``'django_language'``\n\nThe name of the cookie to use for the language cookie. This can be whatever\nyou want (as long as it's different from the other cookie names in your\napplication). See :doc:`/topics/i18n/index`.\n\n.. setting:: LANGUAGE_COOKIE_PATH\n\n``LANGUAGE_COOKIE_PATH``\n------------------------\n\nDefault: ``'/'``\n\nThe path set on the language cookie. This should either match the URL path of your\nDjango installation or be a parent of that path.\n\nThis is useful if you have multiple Django instances running under the same\nhostname. They can use different cookie paths and each instance will only see\nits own language cookie.\n\nBe cautious when updating this setting on a production site. If you update this\nsetting to use a deeper path than it previously used, existing user cookies that\nhave the old path will not be updated. This will result in site users being\nunable to switch the language as long as these cookies persist. The only safe\nand reliable option to perform the switch is to change the language cookie name\npermanently (via the :setting:`LANGUAGE_COOKIE_NAME` setting), and to add\na middleware that copies the value from the old cookie to a new one and then\ndeletes the one.\n\n.. setting:: LANGUAGE_COOKIE_SAMESITE\n\n``LANGUAGE_COOKIE_SAMESITE``\n----------------------------\n\nDefault: ``None``\n\nThe value of the `SameSite`_ flag on the language cookie. This flag prevents the\ncookie from being sent in cross-site requests.\n\nSee :setting:`SESSION_COOKIE_SAMESITE` for details about ``SameSite``.\n\n.. versionchanged:: 3.1\n\n    Setting ``LANGUAGE_COOKIE_SAMESITE = 'None'`` was allowed.\n\n.. setting:: LANGUAGE_COOKIE_SECURE\n\n``LANGUAGE_COOKIE_SECURE``\n--------------------------\n\nDefault: ``False``\n\nWhether to use a secure cookie for the language cookie. If this is set to\n``True``, the cookie will be marked as \"secure\", which means browsers may\nensure that the cookie is only sent under an HTTPS connection.\n\n.. setting:: LANGUAGES\n\n``LANGUAGES``\n-------------\n\nDefault: A list of all available languages. This list is continually growing\nand including a copy here would inevitably become rapidly out of date. You can\nsee the current list of translated languages by looking in\n:source:`django/conf/global_settings.py`.\n\nThe list is a list of two-tuples in the format\n(:term:`language code<language code>`, ``language name``) -- for example,\n``('ja', 'Japanese')``.\nThis specifies which languages are available for language selection. See\n:doc:`/topics/i18n/index`.\n\nGenerally, the default value should suffice. Only set this setting if you want\nto restrict language selection to a subset of the Django-provided languages.\n\nIf you define a custom :setting:`LANGUAGES` setting, you can mark the\nlanguage names as translation strings using the\n:func:`~django.utils.translation.gettext_lazy` function.\n\nHere's a sample settings file::\n\n    from django.utils.translation import gettext_lazy as _\n\n    LANGUAGES = [\n        ('de', _('German')),\n        ('en', _('English')),\n    ]\n\n.. setting:: LANGUAGES_BIDI\n\n``LANGUAGES_BIDI``\n------------------\n\nDefault: A list of all language codes that are written right-to-left. You can\nsee the current list of these languages by looking in\n:source:`django/conf/global_settings.py`.\n\nThe list contains :term:`language codes<language code>` for languages that are\nwritten right-to-left.\n\nGenerally, the default value should suffice. Only set this setting if you want\nto restrict language selection to a subset of the Django-provided languages.\nIf you define a custom :setting:`LANGUAGES` setting, the list of bidirectional\nlanguages may contain language codes which are not enabled on a given site.\n\n.. setting:: LOCALE_PATHS\n\n``LOCALE_PATHS``\n----------------\n\nDefault: ``[]`` (Empty list)\n\nA list of directories where Django looks for translation files.\nSee :ref:`how-django-discovers-translations`.\n\nExample::\n\n    LOCALE_PATHS = [\n        '/home/www/project/common_files/locale',\n        '/var/local/translations/locale',\n    ]\n\nDjango will look within each of these paths for the ``<locale_code>/LC_MESSAGES``\ndirectories containing the actual translation files.\n\n.. setting:: LOGGING\n\n``LOGGING``\n-----------\n\nDefault: A logging configuration dictionary.\n\nA data structure containing configuration information. The contents of\nthis data structure will be passed as the argument to the\nconfiguration method described in :setting:`LOGGING_CONFIG`.\n\nAmong other things, the default logging configuration passes HTTP 500 server\nerrors to an email log handler when :setting:`DEBUG` is ``False``. See also\n:ref:`configuring-logging`.\n\nYou can see the default logging configuration by looking in\n:source:`django/utils/log.py`.\n\n.. setting:: LOGGING_CONFIG\n\n``LOGGING_CONFIG``\n------------------\n\nDefault: ``'logging.config.dictConfig'``\n\nA path to a callable that will be used to configure logging in the\nDjango project. Points at an instance of Python's :ref:`dictConfig\n<logging-config-dictschema>` configuration method by default.\n\nIf you set :setting:`LOGGING_CONFIG` to ``None``, the logging\nconfiguration process will be skipped.\n\n.. setting:: MANAGERS\n\n``MANAGERS``\n------------\n\nDefault: ``[]`` (Empty list)\n\nA list in the same format as :setting:`ADMINS` that specifies who should get\nbroken link notifications when\n:class:`~django.middleware.common.BrokenLinkEmailsMiddleware` is enabled.\n\n.. setting:: MEDIA_ROOT\n\n``MEDIA_ROOT``\n--------------\n\nDefault: ``''`` (Empty string)\n\nAbsolute filesystem path to the directory that will hold :doc:`user-uploaded\nfiles </topics/files>`.\n\nExample: ``\"/var/www/example.com/media/\"``\n\nSee also :setting:`MEDIA_URL`.\n\n.. warning::\n\n    :setting:`MEDIA_ROOT` and :setting:`STATIC_ROOT` must have different\n    values. Before :setting:`STATIC_ROOT` was introduced, it was common to\n    rely or fallback on :setting:`MEDIA_ROOT` to also serve static files;\n    however, since this can have serious security implications, there is a\n    validation check to prevent it.\n\n.. setting:: MEDIA_URL\n\n``MEDIA_URL``\n-------------\n\nDefault: ``''`` (Empty string)\n\nURL that handles the media served from :setting:`MEDIA_ROOT`, used\nfor :doc:`managing stored files </topics/files>`. It must end in a slash if set\nto a non-empty value. You will need to :ref:`configure these files to be served\n<serving-uploaded-files-in-development>` in both development and production\nenvironments.\n\nIf you want to use ``{{ MEDIA_URL }}`` in your templates, add\n``'django.template.context_processors.media'`` in the ``'context_processors'``\noption of :setting:`TEMPLATES`.\n\nExample: ``\"http://media.example.com/\"``\n\n.. warning::\n\n    There are security risks if you are accepting uploaded content from\n    untrusted users! See the security guide's topic on\n    :ref:`user-uploaded-content-security` for mitigation details.\n\n.. warning::\n\n    :setting:`MEDIA_URL` and :setting:`STATIC_URL` must have different\n    values. See :setting:`MEDIA_ROOT` for more details.\n\n.. note::\n\n    If :setting:`MEDIA_URL` is a relative path, then it will be prefixed by the\n    server-provided value of ``SCRIPT_NAME`` (or ``/`` if not set). This makes\n    it easier to serve a Django application in a subpath without adding an\n    extra configuration to the settings.\n\n.. setting:: MIDDLEWARE\n\n``MIDDLEWARE``\n--------------\n\nDefault: ``None``\n\nA list of middleware to use. See :doc:`/topics/http/middleware`.\n\n.. setting:: MIGRATION_MODULES\n\n``MIGRATION_MODULES``\n---------------------\n\nDefault: ``{}`` (Empty dictionary)\n\nA dictionary specifying the package where migration modules can be found on a\nper-app basis. The default value of this setting is an empty dictionary, but\nthe default package name for migration modules is ``migrations``.\n\nExample::\n\n    {'blog': 'blog.db_migrations'}\n\nIn this case, migrations pertaining to the ``blog`` app will be contained in\nthe ``blog.db_migrations`` package.\n\nIf you provide the ``app_label`` argument, :djadmin:`makemigrations` will\nautomatically create the package if it doesn't already exist.\n\nWhen you supply ``None`` as a value for an app, Django will consider the app as\nan app without migrations regardless of an existing ``migrations`` submodule.\nThis can be used, for example, in a test settings file to skip migrations while\ntesting (tables will still be created for the apps' models). To disable\nmigrations for all apps during tests, you can set the\n:setting:`MIGRATE <TEST_MIGRATE>` to ``False`` instead. If\n``MIGRATION_MODULES`` is used in your general project settings, remember to use\nthe :option:`migrate --run-syncdb` option if you want to create tables for the\napp.\n\n.. setting:: MONTH_DAY_FORMAT\n\n``MONTH_DAY_FORMAT``\n--------------------\n\nDefault: ``'F j'``\n\nThe default formatting to use for date fields on Django admin change-list\npages -- and, possibly, by other parts of the system -- in cases when only the\nmonth and day are displayed.\n\nFor example, when a Django admin change-list page is being filtered by a date\ndrilldown, the header for a given day displays the day and month. Different\nlocales have different formats. For example, U.S. English would say\n\"January 1,\" whereas Spanish might say \"1 Enero.\"\n\nNote that if :setting:`USE_L10N` is set to ``True``, then the corresponding\nlocale-dictated format has higher precedence and will be applied.\n\nSee :tfilter:`allowed date format strings <date>`. See also\n:setting:`DATE_FORMAT`, :setting:`DATETIME_FORMAT`,\n:setting:`TIME_FORMAT` and :setting:`YEAR_MONTH_FORMAT`.\n\n.. setting:: NUMBER_GROUPING\n\n``NUMBER_GROUPING``\n-------------------\n\nDefault: ``0``\n\nNumber of digits grouped together on the integer part of a number.\n\nCommon use is to display a thousand separator. If this setting is ``0``, then\nno grouping will be applied to the number. If this setting is greater than\n``0``, then :setting:`THOUSAND_SEPARATOR` will be used as the separator between\nthose groups.\n\nSome locales use non-uniform digit grouping, e.g. ``10,00,00,000`` in\n``en_IN``. For this case, you can provide a sequence with the number of digit\ngroup sizes to be applied. The first number defines the size of the group\npreceding the decimal delimiter, and each number that follows defines the size\nof preceding groups. If the sequence is terminated with ``-1``, no further\ngrouping is performed. If the sequence terminates with a ``0``, the last group\nsize is used for the remainder of the number.\n\nExample tuple for ``en_IN``::\n\n    NUMBER_GROUPING = (3, 2, 0)\n\nNote that if :setting:`USE_L10N` is set to ``True``, then the locale-dictated\nformat has higher precedence and will be applied instead.\n\nSee also :setting:`DECIMAL_SEPARATOR`, :setting:`THOUSAND_SEPARATOR` and\n:setting:`USE_THOUSAND_SEPARATOR`.\n\n.. setting:: PREPEND_WWW\n\n``PREPEND_WWW``\n---------------\n\nDefault: ``False``\n\nWhether to prepend the \"www.\" subdomain to URLs that don't have it. This is only\nused if :class:`~django.middleware.common.CommonMiddleware` is installed\n(see :doc:`/topics/http/middleware`). See also :setting:`APPEND_SLASH`.\n\n.. setting:: ROOT_URLCONF\n\n``ROOT_URLCONF``\n----------------\n\nDefault: Not defined\n\nA string representing the full Python import path to your root URLconf, for\nexample ``\"mydjangoapps.urls\"``. Can be overridden on a per-request basis by\nsetting the attribute ``urlconf`` on the incoming ``HttpRequest``\nobject. See :ref:`how-django-processes-a-request` for details.\n\n.. setting:: SECRET_KEY\n\n``SECRET_KEY``\n--------------\n\nDefault: ``''`` (Empty string)\n\nA secret key for a particular Django installation. This is used to provide\n:doc:`cryptographic signing </topics/signing>`, and should be set to a unique,\nunpredictable value.\n\n:djadmin:`django-admin startproject <startproject>` automatically adds a\nrandomly-generated ``SECRET_KEY`` to each new project.\n\nUses of the key shouldn't assume that it's text or bytes. Every use should go\nthrough :func:`~django.utils.encoding.force_str` or\n:func:`~django.utils.encoding.force_bytes` to convert it to the desired type.\n\nDjango will refuse to start if :setting:`SECRET_KEY` is not set.\n\n.. warning::\n\n    **Keep this value secret.**\n\n    Running Django with a known :setting:`SECRET_KEY` defeats many of Django's\n    security protections, and can lead to privilege escalation and remote code\n    execution vulnerabilities.\n\nThe secret key is used for:\n\n* All :doc:`sessions </topics/http/sessions>` if you are using\n  any other session backend than ``django.contrib.sessions.backends.cache``,\n  or are using the default\n  :meth:`~django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash()`.\n* All :doc:`messages </ref/contrib/messages>` if you are using\n  :class:`~django.contrib.messages.storage.cookie.CookieStorage` or\n  :class:`~django.contrib.messages.storage.fallback.FallbackStorage`.\n* All :class:`~django.contrib.auth.views.PasswordResetView` tokens.\n* Any usage of :doc:`cryptographic signing </topics/signing>`, unless a\n  different key is provided.\n\nIf you rotate your secret key, all of the above will be invalidated.\nSecret keys are not used for passwords of users and key rotation will not\naffect them.\n\n.. note::\n\n    The default :file:`settings.py` file created by :djadmin:`django-admin\n    startproject <startproject>` creates a unique ``SECRET_KEY`` for\n    convenience.\n\n.. setting:: SECURE_BROWSER_XSS_FILTER\n\n``SECURE_BROWSER_XSS_FILTER``\n-----------------------------\n\nDefault: ``False``\n\nIf ``True``, the :class:`~django.middleware.security.SecurityMiddleware` sets\nthe :ref:`x-xss-protection` header on all responses that do not already have it.\n\nModern browsers don't honor ``X-XSS-Protection`` HTTP header anymore. Although\nthe setting offers little practical benefit, you may still want to set the\nheader if you support older browsers.\n\n.. setting:: SECURE_CONTENT_TYPE_NOSNIFF\n\n``SECURE_CONTENT_TYPE_NOSNIFF``\n-------------------------------\n\nDefault: ``True``\n\nIf ``True``, the :class:`~django.middleware.security.SecurityMiddleware`\nsets the :ref:`x-content-type-options` header on all responses that do not\nalready have it.\n\n.. setting:: SECURE_HSTS_INCLUDE_SUBDOMAINS\n\n``SECURE_HSTS_INCLUDE_SUBDOMAINS``\n----------------------------------\n\nDefault: ``False``\n\nIf ``True``, the :class:`~django.middleware.security.SecurityMiddleware` adds\nthe ``includeSubDomains`` directive to the :ref:`http-strict-transport-security`\nheader. It has no effect unless :setting:`SECURE_HSTS_SECONDS` is set to a\nnon-zero value.\n\n.. warning::\n    Setting this incorrectly can irreversibly (for the value of\n    :setting:`SECURE_HSTS_SECONDS`) break your site. Read the\n    :ref:`http-strict-transport-security` documentation first.\n\n.. setting:: SECURE_HSTS_PRELOAD\n\n``SECURE_HSTS_PRELOAD``\n-----------------------\n\nDefault: ``False``\n\nIf ``True``, the :class:`~django.middleware.security.SecurityMiddleware` adds\nthe ``preload`` directive to the :ref:`http-strict-transport-security`\nheader. It has no effect unless :setting:`SECURE_HSTS_SECONDS` is set to a\nnon-zero value.\n\n.. setting:: SECURE_HSTS_SECONDS\n\n``SECURE_HSTS_SECONDS``\n-----------------------\n\nDefault: ``0``\n\nIf set to a non-zero integer value, the\n:class:`~django.middleware.security.SecurityMiddleware` sets the\n:ref:`http-strict-transport-security` header on all responses that do not\nalready have it.\n\n.. warning::\n    Setting this incorrectly can irreversibly (for some time) break your site.\n    Read the :ref:`http-strict-transport-security` documentation first.\n\n.. setting:: SECURE_PROXY_SSL_HEADER\n\n``SECURE_PROXY_SSL_HEADER``\n---------------------------\n\nDefault: ``None``\n\nA tuple representing a HTTP header/value combination that signifies a request\nis secure. This controls the behavior of the request object's ``is_secure()``\nmethod.\n\nBy default, ``is_secure()`` determines if a request is secure by confirming\nthat a requested URL uses ``https://``. This method is important for Django's\nCSRF protection, and it may be used by your own code or third-party apps.\n\nIf your Django app is behind a proxy, though, the proxy may be \"swallowing\"\nwhether the original request uses HTTPS or not. If there is a non-HTTPS\nconnection between the proxy and Django then ``is_secure()`` would always\nreturn ``False`` -- even for requests that were made via HTTPS by the end user.\nIn contrast, if there is an HTTPS connection between the proxy and Django then\n``is_secure()`` would always return ``True`` -- even for requests that were\nmade originally via HTTP.\n\nIn this situation, configure your proxy to set a custom HTTP header that tells\nDjango whether the request came in via HTTPS, and set\n``SECURE_PROXY_SSL_HEADER`` so that Django knows what header to look for.\n\nSet a tuple with two elements -- the name of the header to look for and the\nrequired value. For example::\n\n    SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\nThis tells Django to trust the ``X-Forwarded-Proto`` header that comes from our\nproxy, and any time its value is ``'https'``, then the request is guaranteed to\nbe secure (i.e., it originally came in via HTTPS).\n\nYou should *only* set this setting if you control your proxy or have some other\nguarantee that it sets/strips this header appropriately.\n\nNote that the header needs to be in the format as used by ``request.META`` --\nall caps and likely starting with ``HTTP_``. (Remember, Django automatically\nadds ``'HTTP_'`` to the start of x-header names before making the header\navailable in ``request.META``.)\n\n.. warning::\n\n    **Modifying this setting can compromise your site's security. Ensure you\n    fully understand your setup before changing it.**\n\n    Make sure ALL of the following are true before setting this (assuming the\n    values from the example above):\n\n    * Your Django app is behind a proxy.\n    * Your proxy strips the ``X-Forwarded-Proto`` header from all incoming\n      requests. In other words, if end users include that header in their\n      requests, the proxy will discard it.\n    * Your proxy sets the ``X-Forwarded-Proto`` header and sends it to Django,\n      but only for requests that originally come in via HTTPS.\n\n    If any of those are not true, you should keep this setting set to ``None``\n    and find another way of determining HTTPS, perhaps via custom middleware.\n\n.. setting:: SECURE_REDIRECT_EXEMPT\n\n``SECURE_REDIRECT_EXEMPT``\n--------------------------\n\nDefault: ``[]`` (Empty list)\n\nIf a URL path matches a regular expression in this list, the request will not be\nredirected to HTTPS. The\n:class:`~django.middleware.security.SecurityMiddleware` strips leading slashes\nfrom URL paths, so patterns shouldn't include them, e.g.\n``SECURE_REDIRECT_EXEMPT = [r'^no-ssl/$', …]``. If\n:setting:`SECURE_SSL_REDIRECT` is ``False``, this setting has no effect.\n\n.. setting:: SECURE_REFERRER_POLICY\n\n``SECURE_REFERRER_POLICY``\n--------------------------\n\nDefault: ``'same-origin'``\n\nIf configured, the :class:`~django.middleware.security.SecurityMiddleware` sets\nthe :ref:`referrer-policy` header on all responses that do not already have it\nto the value provided.\n\n.. versionchanged:: 3.1\n\n    In older versions, the default value is ``None``.\n\n.. setting:: SECURE_SSL_HOST\n\n``SECURE_SSL_HOST``\n-------------------\n\nDefault: ``None``\n\nIf a string (e.g. ``secure.example.com``), all SSL redirects will be directed\nto this host rather than the originally-requested host\n(e.g. ``www.example.com``). If :setting:`SECURE_SSL_REDIRECT` is ``False``, this\nsetting has no effect.\n\n.. setting:: SECURE_SSL_REDIRECT\n\n``SECURE_SSL_REDIRECT``\n-----------------------\n\nDefault: ``False``\n\nIf ``True``, the :class:`~django.middleware.security.SecurityMiddleware`\n:ref:`redirects <ssl-redirect>` all non-HTTPS requests to HTTPS (except for\nthose URLs matching a regular expression listed in\n:setting:`SECURE_REDIRECT_EXEMPT`).\n\n.. note::\n\n   If turning this to ``True`` causes infinite redirects, it probably means\n   your site is running behind a proxy and can't tell which requests are secure\n   and which are not. Your proxy likely sets a header to indicate secure\n   requests; you can correct the problem by finding out what that header is and\n   configuring the :setting:`SECURE_PROXY_SSL_HEADER` setting accordingly.\n\n.. setting:: SERIALIZATION_MODULES\n\n``SERIALIZATION_MODULES``\n-------------------------\n\nDefault: Not defined\n\nA dictionary of modules containing serializer definitions (provided as\nstrings), keyed by a string identifier for that serialization type. For\nexample, to define a YAML serializer, use::\n\n    SERIALIZATION_MODULES = {'yaml': 'path.to.yaml_serializer'}\n\n.. setting:: SERVER_EMAIL\n\n``SERVER_EMAIL``\n----------------\n\nDefault: ``'root@localhost'``\n\nThe email address that error messages come from, such as those sent to\n:setting:`ADMINS` and :setting:`MANAGERS`.\n\n.. admonition:: Why are my emails sent from a different address?\n\n    This address is used only for error messages. It is *not* the address that\n    regular email messages sent with :meth:`~django.core.mail.send_mail()`\n    come from; for that, see :setting:`DEFAULT_FROM_EMAIL`.\n\n.. setting:: SHORT_DATE_FORMAT\n\n``SHORT_DATE_FORMAT``\n---------------------\n\nDefault: ``'m/d/Y'`` (e.g. ``12/31/2003``)\n\nAn available formatting that can be used for displaying date fields on\ntemplates. Note that if :setting:`USE_L10N` is set to ``True``, then the\ncorresponding locale-dictated format has higher precedence and will be applied.\nSee :tfilter:`allowed date format strings <date>`.\n\nSee also :setting:`DATE_FORMAT` and :setting:`SHORT_DATETIME_FORMAT`.\n\n.. setting:: SHORT_DATETIME_FORMAT\n\n``SHORT_DATETIME_FORMAT``\n-------------------------\n\nDefault: ``'m/d/Y P'`` (e.g. ``12/31/2003 4 p.m.``)\n\nAn available formatting that can be used for displaying datetime fields on\ntemplates. Note that if :setting:`USE_L10N` is set to ``True``, then the\ncorresponding locale-dictated format has higher precedence and will be applied.\nSee :tfilter:`allowed date format strings <date>`.\n\nSee also :setting:`DATE_FORMAT` and :setting:`SHORT_DATE_FORMAT`.\n\n.. setting:: SIGNING_BACKEND\n\n``SIGNING_BACKEND``\n-------------------\n\nDefault: ``'django.core.signing.TimestampSigner'``\n\nThe backend used for signing cookies and other data.\n\nSee also the :doc:`/topics/signing` documentation.\n\n.. setting:: SILENCED_SYSTEM_CHECKS\n\n``SILENCED_SYSTEM_CHECKS``\n--------------------------\n\nDefault: ``[]`` (Empty list)\n\nA list of identifiers of messages generated by the system check framework\n(i.e. ``[\"models.W001\"]``) that you wish to permanently acknowledge and ignore.\nSilenced checks will not be output to the console.\n\nSee also the :doc:`/ref/checks` documentation.\n\n.. setting:: TEMPLATES\n\n``TEMPLATES``\n-------------\n\nDefault: ``[]`` (Empty list)\n\nA list containing the settings for all template engines to be used with\nDjango. Each item of the list is a dictionary containing the options for an\nindividual engine.\n\nHere's a setup that tells the Django template engine to load templates from the\n``templates`` subdirectory inside each installed application::\n\n    TEMPLATES = [\n        {\n            'BACKEND': 'django.template.backends.django.DjangoTemplates',\n            'APP_DIRS': True,\n        },\n    ]\n\nThe following options are available for all backends.\n\n.. setting:: TEMPLATES-BACKEND\n\n``BACKEND``\n~~~~~~~~~~~\n\nDefault: Not defined\n\nThe template backend to use. The built-in template backends are:\n\n* ``'django.template.backends.django.DjangoTemplates'``\n* ``'django.template.backends.jinja2.Jinja2'``\n\nYou can use a template backend that doesn't ship with Django by setting\n``BACKEND`` to a fully-qualified path (i.e. ``'mypackage.whatever.Backend'``).\n\n.. setting:: TEMPLATES-NAME\n\n``NAME``\n~~~~~~~~\n\nDefault: see below\n\nThe alias for this particular template engine. It's an identifier that allows\nselecting an engine for rendering. Aliases must be unique across all\nconfigured template engines.\n\nIt defaults to the name of the module defining the engine class, i.e. the\nnext to last piece of :setting:`BACKEND <TEMPLATES-BACKEND>`, when it isn't\nprovided. For example if the backend is ``'mypackage.whatever.Backend'`` then\nits default name is ``'whatever'``.\n\n.. setting:: TEMPLATES-DIRS\n\n``DIRS``\n~~~~~~~~\n\nDefault: ``[]`` (Empty list)\n\nDirectories where the engine should look for template source files, in search\norder.\n\n.. setting:: TEMPLATES-APP_DIRS\n\n``APP_DIRS``\n~~~~~~~~~~~~\n\nDefault: ``False``\n\nWhether the engine should look for template source files inside installed\napplications.\n\n.. note::\n\n    The default :file:`settings.py` file created by :djadmin:`django-admin\n    startproject <startproject>` sets ``'APP_DIRS': True``.\n\n.. setting:: TEMPLATES-OPTIONS\n\n``OPTIONS``\n~~~~~~~~~~~\n\nDefault: ``{}`` (Empty dict)\n\nExtra parameters to pass to the template backend. Available parameters vary\ndepending on the template backend. See\n:class:`~django.template.backends.django.DjangoTemplates` and\n:class:`~django.template.backends.jinja2.Jinja2` for the options of the\nbuilt-in backends.\n\n.. setting:: TEST_RUNNER\n\n``TEST_RUNNER``\n---------------\n\nDefault: ``'django.test.runner.DiscoverRunner'``\n\nThe name of the class to use for starting the test suite. See\n:ref:`other-testing-frameworks`.\n\n.. setting:: TEST_NON_SERIALIZED_APPS\n\n``TEST_NON_SERIALIZED_APPS``\n----------------------------\n\nDefault: ``[]`` (Empty list)\n\nIn order to restore the database state between tests for\n``TransactionTestCase``\\s and database backends without transactions, Django\nwill :ref:`serialize the contents of all apps <test-case-serialized-rollback>`\nwhen it starts the test run so it can then reload from that copy before running\ntests that need it.\n\nThis slows down the startup time of the test runner; if you have apps that\nyou know don't need this feature, you can add their full names in here (e.g.\n``'django.contrib.contenttypes'``) to exclude them from this serialization\nprocess.\n\n.. setting:: THOUSAND_SEPARATOR\n\n``THOUSAND_SEPARATOR``\n----------------------\n\nDefault: ``','`` (Comma)\n\nDefault thousand separator used when formatting numbers. This setting is\nused only when :setting:`USE_THOUSAND_SEPARATOR` is ``True`` and\n:setting:`NUMBER_GROUPING` is greater than ``0``.\n\nNote that if :setting:`USE_L10N` is set to ``True``, then the locale-dictated\nformat has higher precedence and will be applied instead.\n\nSee also :setting:`NUMBER_GROUPING`, :setting:`DECIMAL_SEPARATOR` and\n:setting:`USE_THOUSAND_SEPARATOR`.\n\n.. setting:: TIME_FORMAT\n\n``TIME_FORMAT``\n---------------\n\nDefault: ``'P'`` (e.g. ``4 p.m.``)\n\nThe default formatting to use for displaying time fields in any part of the\nsystem. Note that if :setting:`USE_L10N` is set to ``True``, then the\nlocale-dictated format has higher precedence and will be applied instead. See\n:tfilter:`allowed date format strings <date>`.\n\nSee also :setting:`DATE_FORMAT` and :setting:`DATETIME_FORMAT`.\n\n.. setting:: TIME_INPUT_FORMATS\n\n``TIME_INPUT_FORMATS``\n----------------------\n\nDefault::\n\n    [\n        '%H:%M:%S',     # '14:30:59'\n        '%H:%M:%S.%f',  # '14:30:59.000200'\n        '%H:%M',        # '14:30'\n    ]\n\nA list of formats that will be accepted when inputting data on a time field.\nFormats will be tried in order, using the first valid one. Note that these\nformat strings use Python's :ref:`datetime module syntax\n<strftime-strptime-behavior>`, not the format strings from the :tfilter:`date`\ntemplate filter.\n\nWhen :setting:`USE_L10N` is ``True``, the locale-dictated format has higher\nprecedence and will be applied instead.\n\nSee also :setting:`DATE_INPUT_FORMATS` and :setting:`DATETIME_INPUT_FORMATS`.\n\n.. setting:: TIME_ZONE\n\n``TIME_ZONE``\n-------------\n\nDefault: ``'America/Chicago'``\n\nA string representing the time zone for this installation. See the `list of\ntime zones`_.\n\n.. note::\n    Since Django was first released with the :setting:`TIME_ZONE` set to\n    ``'America/Chicago'``, the global setting (used if nothing is defined in\n    your project's ``settings.py``) remains ``'America/Chicago'`` for backwards\n    compatibility. New project templates default to ``'UTC'``.\n\nNote that this isn't necessarily the time zone of the server. For example, one\nserver may serve multiple Django-powered sites, each with a separate time zone\nsetting.\n\nWhen :setting:`USE_TZ` is ``False``, this is the time zone in which Django\nwill store all datetimes. When :setting:`USE_TZ` is ``True``, this is the\ndefault time zone that Django will use to display datetimes in templates and\nto interpret datetimes entered in forms.\n\nOn Unix environments (where :func:`time.tzset` is implemented), Django sets the\n``os.environ['TZ']`` variable to the time zone you specify in the\n:setting:`TIME_ZONE` setting. Thus, all your views and models will\nautomatically operate in this time zone. However, Django won't set the ``TZ``\nenvironment variable if you're using the manual configuration option as\ndescribed in :ref:`manually configuring settings\n<settings-without-django-settings-module>`. If Django doesn't set the ``TZ``\nenvironment variable, it's up to you to ensure your processes are running in\nthe correct environment.\n\n.. note::\n    Django cannot reliably use alternate time zones in a Windows environment.\n    If you're running Django on Windows, :setting:`TIME_ZONE` must be set to\n    match the system time zone.\n\n.. _list of time zones: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones\n\n.. setting:: USE_I18N\n\n``USE_I18N``\n------------\n\nDefault: ``True``\n\nA boolean that specifies whether Django's translation system should be enabled.\nThis provides a way to turn it off, for performance. If this is set to\n``False``, Django will make some optimizations so as not to load the\ntranslation machinery.\n\nSee also :setting:`LANGUAGE_CODE`, :setting:`USE_L10N` and :setting:`USE_TZ`.\n\n.. note::\n\n    The default :file:`settings.py` file created by :djadmin:`django-admin\n    startproject <startproject>` includes ``USE_I18N = True`` for convenience.\n\n.. setting:: USE_L10N\n\n``USE_L10N``\n------------\n\nDefault: ``False``\n\nA boolean that specifies if localized formatting of data will be enabled by\ndefault or not. If this is set to ``True``, e.g. Django will display numbers and\ndates using the format of the current locale.\n\nSee also :setting:`LANGUAGE_CODE`, :setting:`USE_I18N` and :setting:`USE_TZ`.\n\n.. note::\n\n    The default :file:`settings.py` file created by :djadmin:`django-admin\n    startproject <startproject>` includes ``USE_L10N = True`` for convenience.\n\n.. setting:: USE_THOUSAND_SEPARATOR\n\n``USE_THOUSAND_SEPARATOR``\n--------------------------\n\nDefault: ``False``\n\nA boolean that specifies whether to display numbers using a thousand separator.\nWhen :setting:`USE_L10N` is set to ``True`` and if this is also set to\n``True``, Django will use the values of :setting:`THOUSAND_SEPARATOR` and\n:setting:`NUMBER_GROUPING` to format numbers unless the locale already has an\nexisting thousands separator. If there is a thousands separator in the locale\nformat, it will have higher precedence and will be applied instead.\n\nSee also :setting:`DECIMAL_SEPARATOR`, :setting:`NUMBER_GROUPING` and\n:setting:`THOUSAND_SEPARATOR`.\n\n.. setting:: USE_TZ\n\n``USE_TZ``\n----------\n\nDefault: ``False``\n\nA boolean that specifies if datetimes will be timezone-aware by default or not.\nIf this is set to ``True``, Django will use timezone-aware datetimes internally.\nOtherwise, Django will use naive datetimes in local time.\n\nSee also :setting:`TIME_ZONE`, :setting:`USE_I18N` and :setting:`USE_L10N`.\n\n.. note::\n\n    The default :file:`settings.py` file created by\n    :djadmin:`django-admin startproject <startproject>` includes\n    ``USE_TZ = True`` for convenience.\n\n.. setting:: USE_X_FORWARDED_HOST\n\n``USE_X_FORWARDED_HOST``\n------------------------\n\nDefault: ``False``\n\nA boolean that specifies whether to use the ``X-Forwarded-Host`` header in\npreference to the ``Host`` header. This should only be enabled if a proxy\nwhich sets this header is in use.\n\nThis setting takes priority over :setting:`USE_X_FORWARDED_PORT`. Per\n:rfc:`7239#section-5.3`, the ``X-Forwarded-Host`` header can include the port\nnumber, in which case you shouldn't use :setting:`USE_X_FORWARDED_PORT`.\n\n.. setting:: USE_X_FORWARDED_PORT\n\n``USE_X_FORWARDED_PORT``\n------------------------\n\nDefault: ``False``\n\nA boolean that specifies whether to use the ``X-Forwarded-Port`` header in\npreference to the ``SERVER_PORT`` ``META`` variable. This should only be\nenabled if a proxy which sets this header is in use.\n\n:setting:`USE_X_FORWARDED_HOST` takes priority over this setting.\n\n.. setting:: WSGI_APPLICATION\n\n``WSGI_APPLICATION``\n--------------------\n\nDefault: ``None``\n\nThe full Python path of the WSGI application object that Django's built-in\nservers (e.g. :djadmin:`runserver`) will use. The :djadmin:`django-admin\nstartproject <startproject>` management command will create a standard\n``wsgi.py`` file with an ``application`` callable in it, and point this setting\nto that ``application``.\n\nIf not set, the return value of ``django.core.wsgi.get_wsgi_application()``\nwill be used. In this case, the behavior of :djadmin:`runserver` will be\nidentical to previous Django versions.\n\n.. setting:: YEAR_MONTH_FORMAT\n\n``YEAR_MONTH_FORMAT``\n---------------------\n\nDefault: ``'F Y'``\n\nThe default formatting to use for date fields on Django admin change-list\npages -- and, possibly, by other parts of the system -- in cases when only the\nyear and month are displayed.\n\nFor example, when a Django admin change-list page is being filtered by a date\ndrilldown, the header for a given month displays the month and the year.\nDifferent locales have different formats. For example, U.S. English would say\n\"January 2006,\" whereas another locale might say \"2006/January.\"\n\nNote that if :setting:`USE_L10N` is set to ``True``, then the corresponding\nlocale-dictated format has higher precedence and will be applied.\n\nSee :tfilter:`allowed date format strings <date>`. See also\n:setting:`DATE_FORMAT`, :setting:`DATETIME_FORMAT`, :setting:`TIME_FORMAT`\nand :setting:`MONTH_DAY_FORMAT`.\n\n.. setting:: X_FRAME_OPTIONS\n\n``X_FRAME_OPTIONS``\n-------------------\n\nDefault: ``'DENY'``\n\nThe default value for the X-Frame-Options header used by\n:class:`~django.middleware.clickjacking.XFrameOptionsMiddleware`. See the\n:doc:`clickjacking protection </ref/clickjacking/>` documentation.\n\nAuth\n====\n\nSettings for :mod:`django.contrib.auth`.\n\n.. setting:: AUTHENTICATION_BACKENDS\n\n``AUTHENTICATION_BACKENDS``\n---------------------------\n\nDefault: ``['django.contrib.auth.backends.ModelBackend']``\n\nA list of authentication backend classes (as strings) to use when attempting to\nauthenticate a user. See the :ref:`authentication backends documentation\n<authentication-backends>` for details.\n\n.. setting:: AUTH_USER_MODEL\n\n``AUTH_USER_MODEL``\n-------------------\n\nDefault: ``'auth.User'``\n\nThe model to use to represent a User. See :ref:`auth-custom-user`.\n\n.. warning::\n    You cannot change the AUTH_USER_MODEL setting during the lifetime of\n    a project (i.e. once you have made and migrated models that depend on it)\n    without serious effort. It is intended to be set at the project start,\n    and the model it refers to must be available in the first migration of\n    the app that it lives in.\n    See :ref:`auth-custom-user` for more details.\n\n.. setting:: LOGIN_REDIRECT_URL\n\n``LOGIN_REDIRECT_URL``\n----------------------\n\nDefault: ``'/accounts/profile/'``\n\nThe URL or :ref:`named URL pattern <naming-url-patterns>` where requests are\nredirected after login when the :class:`~django.contrib.auth.views.LoginView`\ndoesn't get a ``next`` GET parameter.\n\n.. setting:: LOGIN_URL\n\n``LOGIN_URL``\n-------------\n\nDefault: ``'/accounts/login/'``\n\nThe URL or :ref:`named URL pattern <naming-url-patterns>` where requests are\nredirected for login when using the\n:func:`~django.contrib.auth.decorators.login_required` decorator,\n:class:`~django.contrib.auth.mixins.LoginRequiredMixin`, or\n:class:`~django.contrib.auth.mixins.AccessMixin`.\n\n.. setting:: LOGOUT_REDIRECT_URL\n\n``LOGOUT_REDIRECT_URL``\n-----------------------\n\nDefault: ``None``\n\nThe URL or :ref:`named URL pattern <naming-url-patterns>` where requests are\nredirected after logout if :class:`~django.contrib.auth.views.LogoutView`\ndoesn't have a ``next_page`` attribute.\n\nIf ``None``, no redirect will be performed and the logout view will be\nrendered.\n\n.. setting:: PASSWORD_RESET_TIMEOUT\n\n``PASSWORD_RESET_TIMEOUT``\n--------------------------\n\n.. versionadded:: 3.1\n\nDefault: ``259200`` (3 days, in seconds)\n\nThe number of seconds a password reset link is valid for.\n\nUsed by the :class:`~django.contrib.auth.views.PasswordResetConfirmView`.\n\n.. note::\n\n   Reducing the value of this timeout doesn't make any difference to the\n   ability of an attacker to brute-force a password reset token. Tokens are\n   designed to be safe from brute-forcing without any timeout.\n\n   This timeout exists to protect against some unlikely attack scenarios, such\n   as someone gaining access to email archives that may contain old, unused\n   password reset tokens.\n\n.. setting:: PASSWORD_RESET_TIMEOUT_DAYS\n\n``PASSWORD_RESET_TIMEOUT_DAYS``\n-------------------------------\n\nDefault: ``3``\n\nThe number of days a password reset link is valid for.\n\nUsed by the :class:`~django.contrib.auth.views.PasswordResetConfirmView`.\n\n.. deprecated:: 3.1\n\n    This setting is deprecated. Use :setting:`PASSWORD_RESET_TIMEOUT` instead.\n\n.. setting:: PASSWORD_HASHERS\n\n``PASSWORD_HASHERS``\n--------------------\n\nSee :ref:`auth_password_storage`.\n\nDefault::\n\n    [\n        'django.contrib.auth.hashers.PBKDF2PasswordHasher',\n        'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',\n        'django.contrib.auth.hashers.Argon2PasswordHasher',\n        'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',\n    ]\n\n.. setting:: AUTH_PASSWORD_VALIDATORS\n\n``AUTH_PASSWORD_VALIDATORS``\n----------------------------\n\nDefault: ``[]`` (Empty list)\n\nThe list of validators that are used to check the strength of user's passwords.\nSee :ref:`password-validation` for more details. By default, no validation is\nperformed and all passwords are accepted.\n\n.. _settings-messages:\n\nMessages\n========\n\nSettings for :mod:`django.contrib.messages`.\n\n.. setting:: MESSAGE_LEVEL\n\n``MESSAGE_LEVEL``\n-----------------\n\nDefault: ``messages.INFO``\n\nSets the minimum message level that will be recorded by the messages\nframework. See :ref:`message levels <message-level>` for more details.\n\n.. admonition:: Important\n\n   If you override ``MESSAGE_LEVEL`` in your settings file and rely on any of\n   the built-in constants, you must import the constants module directly to\n   avoid the potential for circular imports, e.g.::\n\n       from django.contrib.messages import constants as message_constants\n       MESSAGE_LEVEL = message_constants.DEBUG\n\n   If desired, you may specify the numeric values for the constants directly\n   according to the values in the above :ref:`constants table\n   <message-level-constants>`.\n\n.. setting:: MESSAGE_STORAGE\n\n``MESSAGE_STORAGE``\n-------------------\n\nDefault: ``'django.contrib.messages.storage.fallback.FallbackStorage'``\n\nControls where Django stores message data. Valid values are:\n\n* ``'django.contrib.messages.storage.fallback.FallbackStorage'``\n* ``'django.contrib.messages.storage.session.SessionStorage'``\n* ``'django.contrib.messages.storage.cookie.CookieStorage'``\n\nSee :ref:`message storage backends <message-storage-backends>` for more details.\n\nThe backends that use cookies --\n:class:`~django.contrib.messages.storage.cookie.CookieStorage` and\n:class:`~django.contrib.messages.storage.fallback.FallbackStorage` --\nuse the value of :setting:`SESSION_COOKIE_DOMAIN`, :setting:`SESSION_COOKIE_SECURE`\nand :setting:`SESSION_COOKIE_HTTPONLY` when setting their cookies.\n\n.. setting:: MESSAGE_TAGS\n\n``MESSAGE_TAGS``\n----------------\n\nDefault::\n\n    {\n        messages.DEBUG: 'debug',\n        messages.INFO: 'info',\n        messages.SUCCESS: 'success',\n        messages.WARNING: 'warning',\n        messages.ERROR: 'error',\n    }\n\nThis sets the mapping of message level to message tag, which is typically\nrendered as a CSS class in HTML. If you specify a value, it will extend\nthe default. This means you only have to specify those values which you need\nto override. See :ref:`message-displaying` above for more details.\n\n.. admonition:: Important\n\n   If you override ``MESSAGE_TAGS`` in your settings file and rely on any of\n   the built-in constants, you must import the ``constants`` module directly to\n   avoid the potential for circular imports, e.g.::\n\n       from django.contrib.messages import constants as message_constants\n       MESSAGE_TAGS = {message_constants.INFO: ''}\n\n   If desired, you may specify the numeric values for the constants directly\n   according to the values in the above :ref:`constants table\n   <message-level-constants>`.\n\n.. _settings-sessions:\n\nSessions\n========\n\nSettings for :mod:`django.contrib.sessions`.\n\n.. setting:: SESSION_CACHE_ALIAS\n\n``SESSION_CACHE_ALIAS``\n-----------------------\n\nDefault: ``'default'``\n\nIf you're using :ref:`cache-based session storage <cached-sessions-backend>`,\nthis selects the cache to use.\n\n.. setting:: SESSION_COOKIE_AGE\n\n``SESSION_COOKIE_AGE``\n----------------------\n\nDefault: ``1209600`` (2 weeks, in seconds)\n\nThe age of session cookies, in seconds.\n\n.. setting:: SESSION_COOKIE_DOMAIN\n\n``SESSION_COOKIE_DOMAIN``\n-------------------------\n\nDefault: ``None``\n\nThe domain to use for session cookies. Set this to a string such as\n``\"example.com\"`` for cross-domain cookies, or use ``None`` for a standard\ndomain cookie.\n\nBe cautious when updating this setting on a production site. If you update\nthis setting to enable cross-domain cookies on a site that previously used\nstandard domain cookies, existing user cookies will be set to the old\ndomain. This may result in them being unable to log in as long as these cookies\npersist.\n\nThis setting also affects cookies set by :mod:`django.contrib.messages`.\n\n.. setting:: SESSION_COOKIE_HTTPONLY\n\n``SESSION_COOKIE_HTTPONLY``\n---------------------------\n\nDefault: ``True``\n\nWhether to use ``HttpOnly`` flag on the session cookie. If this is set to\n``True``, client-side JavaScript will not be able to access the session\ncookie.\n\nHttpOnly_ is a flag included in a Set-Cookie HTTP response header. It's part of\nthe :rfc:`6265#section-4.1.2.6` standard for cookies and can be a useful way to\nmitigate the risk of a client-side script accessing the protected cookie data.\n\nThis makes it less trivial for an attacker to escalate a cross-site scripting\nvulnerability into full hijacking of a user's session. There aren't many good\nreasons for turning this off. Your code shouldn't read session cookies from\nJavaScript.\n\n.. _HttpOnly: https://www.owasp.org/index.php/HttpOnly\n\n.. setting:: SESSION_COOKIE_NAME\n\n``SESSION_COOKIE_NAME``\n-----------------------\n\nDefault: ``'sessionid'``\n\nThe name of the cookie to use for sessions. This can be whatever you want\n(as long as it's different from the other cookie names in your application).\n\n.. setting:: SESSION_COOKIE_PATH\n\n``SESSION_COOKIE_PATH``\n-----------------------\n\nDefault: ``'/'``\n\nThe path set on the session cookie. This should either match the URL path of your\nDjango installation or be parent of that path.\n\nThis is useful if you have multiple Django instances running under the same\nhostname. They can use different cookie paths, and each instance will only see\nits own session cookie.\n\n.. setting:: SESSION_COOKIE_SAMESITE\n\n``SESSION_COOKIE_SAMESITE``\n---------------------------\n\nDefault: ``'Lax'``\n\nThe value of the `SameSite`_ flag on the session cookie. This flag prevents the\ncookie from being sent in cross-site requests thus preventing CSRF attacks and\nmaking some methods of stealing session cookie impossible.\n\nPossible values for the setting are:\n\n* ``'Strict'``: prevents the cookie from being sent by the browser to the\n  target site in all cross-site browsing context, even when following a regular\n  link.\n\n  For example, for a GitHub-like website this would mean that if a logged-in\n  user follows a link to a private GitHub project posted on a corporate\n  discussion forum or email, GitHub will not receive the session cookie and the\n  user won't be able to access the project. A bank website, however, most\n  likely doesn't want to allow any transactional pages to be linked from\n  external sites so the ``'Strict'`` flag would be appropriate.\n\n* ``'Lax'`` (default): provides a balance between security and usability for\n  websites that want to maintain user's logged-in session after the user\n  arrives from an external link.\n\n  In the GitHub scenario, the session cookie would be allowed when following a\n  regular link from an external website and be blocked in CSRF-prone request\n  methods (e.g. ``POST``).\n\n* ``'None'`` (string): the session cookie will be sent with all same-site and\n  cross-site requests.\n\n* ``False``: disables the flag.\n\n.. versionchanged:: 3.1\n\n    Setting ``SESSION_COOKIE_SAMESITE = 'None'`` was allowed.\n\n.. _SameSite: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite\n\n.. setting:: SESSION_COOKIE_SECURE\n\n``SESSION_COOKIE_SECURE``\n-------------------------\n\nDefault: ``False``\n\nWhether to use a secure cookie for the session cookie. If this is set to\n``True``, the cookie will be marked as \"secure\", which means browsers may\nensure that the cookie is only sent under an HTTPS connection.\n\nLeaving this setting off isn't a good idea because an attacker could capture an\nunencrypted session cookie with a packet sniffer and use the cookie to hijack\nthe user's session.\n\n.. setting:: SESSION_ENGINE\n\n``SESSION_ENGINE``\n------------------\n\nDefault: ``'django.contrib.sessions.backends.db'``\n\nControls where Django stores session data. Included engines are:\n\n* ``'django.contrib.sessions.backends.db'``\n* ``'django.contrib.sessions.backends.file'``\n* ``'django.contrib.sessions.backends.cache'``\n* ``'django.contrib.sessions.backends.cached_db'``\n* ``'django.contrib.sessions.backends.signed_cookies'``\n\nSee :ref:`configuring-sessions` for more details.\n\n.. setting:: SESSION_EXPIRE_AT_BROWSER_CLOSE\n\n``SESSION_EXPIRE_AT_BROWSER_CLOSE``\n-----------------------------------\n\nDefault: ``False``\n\nWhether to expire the session when the user closes their browser. See\n:ref:`browser-length-vs-persistent-sessions`.\n\n.. setting:: SESSION_FILE_PATH\n\n``SESSION_FILE_PATH``\n---------------------\n\nDefault: ``None``\n\nIf you're using file-based session storage, this sets the directory in\nwhich Django will store session data. When the default value (``None``) is\nused, Django will use the standard temporary directory for the system.\n\n\n.. setting:: SESSION_SAVE_EVERY_REQUEST\n\n``SESSION_SAVE_EVERY_REQUEST``\n------------------------------\n\nDefault: ``False``\n\nWhether to save the session data on every request. If this is ``False``\n(default), then the session data will only be saved if it has been modified --\nthat is, if any of its dictionary values have been assigned or deleted. Empty\nsessions won't be created, even if this setting is active.\n\n.. setting:: SESSION_SERIALIZER\n\n``SESSION_SERIALIZER``\n----------------------\n\nDefault: ``'django.contrib.sessions.serializers.JSONSerializer'``\n\nFull import path of a serializer class to use for serializing session data.\nIncluded serializers are:\n\n* ``'django.contrib.sessions.serializers.PickleSerializer'``\n* ``'django.contrib.sessions.serializers.JSONSerializer'``\n\nSee :ref:`session_serialization` for details, including a warning regarding\npossible remote code execution when using\n:class:`~django.contrib.sessions.serializers.PickleSerializer`.\n\nSites\n=====\n\nSettings for :mod:`django.contrib.sites`.\n\n.. setting:: SITE_ID\n\n``SITE_ID``\n-----------\n\nDefault: Not defined\n\nThe ID, as an integer, of the current site in the ``django_site`` database\ntable. This is used so that application data can hook into specific sites\nand a single database can manage content for multiple sites.\n\n\n.. _settings-staticfiles:\n\nStatic Files\n============\n\nSettings for :mod:`django.contrib.staticfiles`.\n\n.. setting:: STATIC_ROOT\n\n``STATIC_ROOT``\n---------------\n\nDefault: ``None``\n\nThe absolute path to the directory where :djadmin:`collectstatic` will collect\nstatic files for deployment.\n\nExample: ``\"/var/www/example.com/static/\"``\n\nIf the :doc:`staticfiles</ref/contrib/staticfiles>` contrib app is enabled\n(as in the default project template), the :djadmin:`collectstatic` management\ncommand will collect static files into this directory. See the how-to on\n:doc:`managing static files</howto/static-files/index>` for more details about\nusage.\n\n.. warning::\n\n    This should be an initially empty destination directory for collecting\n    your static files from their permanent locations into one directory for\n    ease of deployment; it is **not** a place to store your static files\n    permanently. You should do that in directories that will be found by\n    :doc:`staticfiles</ref/contrib/staticfiles>`’s\n    :setting:`finders<STATICFILES_FINDERS>`, which by default, are\n    ``'static/'`` app sub-directories and any directories you include in\n    :setting:`STATICFILES_DIRS`).\n\n.. setting:: STATIC_URL\n\n``STATIC_URL``\n--------------\n\nDefault: ``None``\n\nURL to use when referring to static files located in :setting:`STATIC_ROOT`.\n\nExample: ``\"/static/\"`` or ``\"http://static.example.com/\"``\n\nIf not ``None``, this will be used as the base path for\n:ref:`asset definitions<form-asset-paths>` (the ``Media`` class) and the\n:doc:`staticfiles app</ref/contrib/staticfiles>`.\n\nIt must end in a slash if set to a non-empty value.\n\nYou may need to :ref:`configure these files to be served in development\n<serving-static-files-in-development>` and will definitely need to do so\n:doc:`in production </howto/static-files/deployment>`.\n\n.. note::\n\n    If :setting:`STATIC_URL` is a relative path, then it will be prefixed by\n    the server-provided value of ``SCRIPT_NAME`` (or ``/`` if not set). This\n    makes it easier to serve a Django application in a subpath without adding\n    an extra configuration to the settings.\n\n.. setting:: STATICFILES_DIRS\n\n``STATICFILES_DIRS``\n--------------------\n\nDefault: ``[]`` (Empty list)\n\nThis setting defines the additional locations the staticfiles app will traverse\nif the ``FileSystemFinder`` finder is enabled, e.g. if you use the\n:djadmin:`collectstatic` or :djadmin:`findstatic` management command or use the\nstatic file serving view.\n\nThis should be set to a list of strings that contain full paths to\nyour additional files directory(ies) e.g.::\n\n    STATICFILES_DIRS = [\n        \"/home/special.polls.com/polls/static\",\n        \"/home/polls.com/polls/static\",\n        \"/opt/webfiles/common\",\n    ]\n\nNote that these paths should use Unix-style forward slashes, even on Windows\n(e.g. ``\"C:/Users/user/mysite/extra_static_content\"``).\n\n.. _staticfiles-dirs-prefixes:\n\nPrefixes (optional)\n~~~~~~~~~~~~~~~~~~~\n\nIn case you want to refer to files in one of the locations with an additional\nnamespace, you can **optionally** provide a prefix as ``(prefix, path)``\ntuples, e.g.::\n\n    STATICFILES_DIRS = [\n        # ...\n        (\"downloads\", \"/opt/webfiles/stats\"),\n    ]\n\nFor example, assuming you have :setting:`STATIC_URL` set to ``'/static/'``, the\n:djadmin:`collectstatic` management command would collect the \"stats\" files\nin a ``'downloads'`` subdirectory of :setting:`STATIC_ROOT`.\n\nThis would allow you to refer to the local file\n``'/opt/webfiles/stats/polls_20101022.tar.gz'`` with\n``'/static/downloads/polls_20101022.tar.gz'`` in your templates, e.g.:\n\n.. code-block:: html+django\n\n    <a href=\"{% static \"downloads/polls_20101022.tar.gz\" %}\">\n\n.. setting:: STATICFILES_STORAGE\n\n``STATICFILES_STORAGE``\n-----------------------\n\nDefault: ``'django.contrib.staticfiles.storage.StaticFilesStorage'``\n\nThe file storage engine to use when collecting static files with the\n:djadmin:`collectstatic` management command.\n\nA ready-to-use instance of the storage backend defined in this setting\ncan be found at ``django.contrib.staticfiles.storage.staticfiles_storage``.\n\nFor an example, see :ref:`staticfiles-from-cdn`.\n\n.. setting:: STATICFILES_FINDERS\n\n``STATICFILES_FINDERS``\n-----------------------\n\nDefault::\n\n    [\n        'django.contrib.staticfiles.finders.FileSystemFinder',\n        'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n    ]\n\nThe list of finder backends that know how to find static files in\nvarious locations.\n\nThe default will find files stored in the :setting:`STATICFILES_DIRS` setting\n(using ``django.contrib.staticfiles.finders.FileSystemFinder``) and in a\n``static`` subdirectory of each app (using\n``django.contrib.staticfiles.finders.AppDirectoriesFinder``). If multiple\nfiles with the same name are present, the first file that is found will be\nused.\n\nOne finder is disabled by default:\n``django.contrib.staticfiles.finders.DefaultStorageFinder``. If added to\nyour :setting:`STATICFILES_FINDERS` setting, it will look for static files in\nthe default file storage as defined by the :setting:`DEFAULT_FILE_STORAGE`\nsetting.\n\n.. note::\n\n    When using the ``AppDirectoriesFinder`` finder, make sure your apps\n    can be found by staticfiles by adding the app to the\n    :setting:`INSTALLED_APPS` setting of your site.\n\nStatic file finders are currently considered a private interface, and this\ninterface is thus undocumented.\n\nCore Settings Topical Index\n===========================\n\nCache\n-----\n* :setting:`CACHES`\n* :setting:`CACHE_MIDDLEWARE_ALIAS`\n* :setting:`CACHE_MIDDLEWARE_KEY_PREFIX`\n* :setting:`CACHE_MIDDLEWARE_SECONDS`\n\nDatabase\n--------\n* :setting:`DATABASES`\n* :setting:`DATABASE_ROUTERS`\n* :setting:`DEFAULT_INDEX_TABLESPACE`\n* :setting:`DEFAULT_TABLESPACE`\n\nDebugging\n---------\n* :setting:`DEBUG`\n* :setting:`DEBUG_PROPAGATE_EXCEPTIONS`\n\nEmail\n-----\n* :setting:`ADMINS`\n* :setting:`DEFAULT_CHARSET`\n* :setting:`DEFAULT_FROM_EMAIL`\n* :setting:`EMAIL_BACKEND`\n* :setting:`EMAIL_FILE_PATH`\n* :setting:`EMAIL_HOST`\n* :setting:`EMAIL_HOST_PASSWORD`\n* :setting:`EMAIL_HOST_USER`\n* :setting:`EMAIL_PORT`\n* :setting:`EMAIL_SSL_CERTFILE`\n* :setting:`EMAIL_SSL_KEYFILE`\n* :setting:`EMAIL_SUBJECT_PREFIX`\n* :setting:`EMAIL_TIMEOUT`\n* :setting:`EMAIL_USE_LOCALTIME`\n* :setting:`EMAIL_USE_TLS`\n* :setting:`MANAGERS`\n* :setting:`SERVER_EMAIL`\n\nError reporting\n---------------\n* :setting:`DEFAULT_EXCEPTION_REPORTER`\n* :setting:`DEFAULT_EXCEPTION_REPORTER_FILTER`\n* :setting:`IGNORABLE_404_URLS`\n* :setting:`MANAGERS`\n* :setting:`SILENCED_SYSTEM_CHECKS`\n\n.. _file-upload-settings:\n\nFile uploads\n------------\n* :setting:`DEFAULT_FILE_STORAGE`\n* :setting:`FILE_UPLOAD_HANDLERS`\n* :setting:`FILE_UPLOAD_MAX_MEMORY_SIZE`\n* :setting:`FILE_UPLOAD_PERMISSIONS`\n* :setting:`FILE_UPLOAD_TEMP_DIR`\n* :setting:`MEDIA_ROOT`\n* :setting:`MEDIA_URL`\n\nForms\n-----\n* :setting:`FORM_RENDERER`\n\nGlobalization (``i18n``/``l10n``)\n---------------------------------\n* :setting:`DATE_FORMAT`\n* :setting:`DATE_INPUT_FORMATS`\n* :setting:`DATETIME_FORMAT`\n* :setting:`DATETIME_INPUT_FORMATS`\n* :setting:`DECIMAL_SEPARATOR`\n* :setting:`FIRST_DAY_OF_WEEK`\n* :setting:`FORMAT_MODULE_PATH`\n* :setting:`LANGUAGE_CODE`\n* :setting:`LANGUAGE_COOKIE_AGE`\n* :setting:`LANGUAGE_COOKIE_DOMAIN`\n* :setting:`LANGUAGE_COOKIE_HTTPONLY`\n* :setting:`LANGUAGE_COOKIE_NAME`\n* :setting:`LANGUAGE_COOKIE_PATH`\n* :setting:`LANGUAGE_COOKIE_SAMESITE`\n* :setting:`LANGUAGE_COOKIE_SECURE`\n* :setting:`LANGUAGES`\n* :setting:`LANGUAGES_BIDI`\n* :setting:`LOCALE_PATHS`\n* :setting:`MONTH_DAY_FORMAT`\n* :setting:`NUMBER_GROUPING`\n* :setting:`SHORT_DATE_FORMAT`\n* :setting:`SHORT_DATETIME_FORMAT`\n* :setting:`THOUSAND_SEPARATOR`\n* :setting:`TIME_FORMAT`\n* :setting:`TIME_INPUT_FORMATS`\n* :setting:`TIME_ZONE`\n* :setting:`USE_I18N`\n* :setting:`USE_L10N`\n* :setting:`USE_THOUSAND_SEPARATOR`\n* :setting:`USE_TZ`\n* :setting:`YEAR_MONTH_FORMAT`\n\nHTTP\n----\n* :setting:`DATA_UPLOAD_MAX_MEMORY_SIZE`\n* :setting:`DATA_UPLOAD_MAX_NUMBER_FIELDS`\n* :setting:`DEFAULT_CHARSET`\n* :setting:`DISALLOWED_USER_AGENTS`\n* :setting:`FORCE_SCRIPT_NAME`\n* :setting:`INTERNAL_IPS`\n* :setting:`MIDDLEWARE`\n* Security\n\n  * :setting:`SECURE_BROWSER_XSS_FILTER`\n  * :setting:`SECURE_CONTENT_TYPE_NOSNIFF`\n  * :setting:`SECURE_HSTS_INCLUDE_SUBDOMAINS`\n  * :setting:`SECURE_HSTS_PRELOAD`\n  * :setting:`SECURE_HSTS_SECONDS`\n  * :setting:`SECURE_PROXY_SSL_HEADER`\n  * :setting:`SECURE_REDIRECT_EXEMPT`\n  * :setting:`SECURE_REFERRER_POLICY`\n  * :setting:`SECURE_SSL_HOST`\n  * :setting:`SECURE_SSL_REDIRECT`\n* :setting:`SIGNING_BACKEND`\n* :setting:`USE_X_FORWARDED_HOST`\n* :setting:`USE_X_FORWARDED_PORT`\n* :setting:`WSGI_APPLICATION`\n\nLogging\n-------\n* :setting:`LOGGING`\n* :setting:`LOGGING_CONFIG`\n\nModels\n------\n* :setting:`ABSOLUTE_URL_OVERRIDES`\n* :setting:`FIXTURE_DIRS`\n* :setting:`INSTALLED_APPS`\n\nSecurity\n--------\n* Cross Site Request Forgery Protection\n\n  * :setting:`CSRF_COOKIE_DOMAIN`\n  * :setting:`CSRF_COOKIE_NAME`\n  * :setting:`CSRF_COOKIE_PATH`\n  * :setting:`CSRF_COOKIE_SAMESITE`\n  * :setting:`CSRF_COOKIE_SECURE`\n  * :setting:`CSRF_FAILURE_VIEW`\n  * :setting:`CSRF_HEADER_NAME`\n  * :setting:`CSRF_TRUSTED_ORIGINS`\n  * :setting:`CSRF_USE_SESSIONS`\n\n* :setting:`SECRET_KEY`\n* :setting:`X_FRAME_OPTIONS`\n\nSerialization\n-------------\n* :setting:`DEFAULT_CHARSET`\n* :setting:`SERIALIZATION_MODULES`\n\nTemplates\n---------\n* :setting:`TEMPLATES`\n\nTesting\n-------\n* Database: :setting:`TEST <DATABASE-TEST>`\n* :setting:`TEST_NON_SERIALIZED_APPS`\n* :setting:`TEST_RUNNER`\n\nURLs\n----\n* :setting:`APPEND_SLASH`\n* :setting:`PREPEND_WWW`\n* :setting:`ROOT_URLCONF`\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":46,"nodeType":"TextFile","repoName":null,"name":"file.txt","path":"docs/ref/files","text":"===================\nThe ``File`` object\n===================\n\nThe :mod:`django.core.files` module and its submodules contain built-in classes\nfor basic file handling in Django.\n\n.. currentmodule:: django.core.files\n\nThe ``File`` class\n==================\n\n.. class:: File(file_object)\n\n    The :class:`File` class is a thin wrapper around a Python\n    :py:term:`file object` with some Django-specific additions.\n    Internally, Django uses this class when it needs to represent a file.\n\n    :class:`File` objects have the following attributes and methods:\n\n    .. attribute:: name\n\n        The name of the file including the relative path from\n        :setting:`MEDIA_ROOT`.\n\n    .. attribute:: size\n\n        The size of the file in bytes.\n\n    .. attribute:: file\n\n        The underlying :py:term:`file object` that this class wraps.\n\n        .. admonition:: Be careful with this attribute in subclasses.\n\n            Some subclasses of :class:`File`, including\n            :class:`~django.core.files.base.ContentFile` and\n            :class:`~django.db.models.fields.files.FieldFile`, may replace this\n            attribute with an object other than a Python :py:term:`file object`.\n            In these cases, this attribute may itself be a :class:`File`\n            subclass (and not necessarily the same subclass). Whenever\n            possible, use the attributes and methods of the subclass itself\n            rather than the those of the subclass's ``file`` attribute.\n\n    .. attribute:: mode\n\n        The read/write mode for the file.\n\n    .. method:: open(mode=None)\n\n        Open or reopen the file (which also does ``File.seek(0)``).\n        The ``mode`` argument allows the same values\n        as Python's built-in :func:`python:open()`.\n\n        When reopening a file, ``mode`` will override whatever mode the file\n        was originally opened with; ``None`` means to reopen with the original\n        mode.\n\n        It can be used as a context manager, e.g. ``with file.open() as f:``.\n\n    .. method:: __iter__()\n\n        Iterate over the file yielding one line at a time.\n\n    .. method:: chunks(chunk_size=None)\n\n        Iterate over the file yielding \"chunks\" of a given size. ``chunk_size``\n        defaults to 64 KB.\n\n        This is especially useful with very large files since it allows them to\n        be streamed off disk and avoids storing the whole file in memory.\n\n    .. method:: multiple_chunks(chunk_size=None)\n\n        Returns ``True`` if the file is large enough to require multiple chunks\n        to access all of its content give some ``chunk_size``.\n\n    .. method:: close()\n\n        Close the file.\n\n    In addition to the listed methods, :class:`~django.core.files.File` exposes\n    the following attributes and methods of its ``file`` object:\n    ``encoding``, ``fileno``, ``flush``, ``isatty``, ``newlines``, ``read``,\n    ``readinto``, ``readline``, ``readlines``, ``seek``, ``tell``,\n    ``truncate``, ``write``, ``writelines``, ``readable()``, ``writable()``,\n    and ``seekable()``.\n\n.. currentmodule:: django.core.files.base\n\nThe ``ContentFile`` class\n=========================\n\n.. class:: ContentFile(File)\n\n    The ``ContentFile`` class inherits from :class:`~django.core.files.File`,\n    but unlike :class:`~django.core.files.File` it operates on string content\n    (bytes also supported), rather than an actual file. For example::\n\n        from django.core.files.base import ContentFile\n\n        f1 = ContentFile(\"esta frase está en español\")\n        f2 = ContentFile(b\"these are bytes\")\n\n.. currentmodule:: django.core.files.images\n\nThe ``ImageFile`` class\n=======================\n\n.. class:: ImageFile(file_object)\n\n    Django provides a built-in class specifically for images.\n    :class:`django.core.files.images.ImageFile` inherits all the attributes\n    and methods of :class:`~django.core.files.File`, and additionally\n    provides the following:\n\n    .. attribute:: width\n\n        Width of the image in pixels.\n\n    .. attribute:: height\n\n        Height of the image in pixels.\n\n.. currentmodule:: django.core.files\n\nAdditional methods on files attached to objects\n===============================================\n\nAny :class:`File` that is associated with an object (as with ``Car.photo``,\nbelow) will also have a couple of extra methods:\n\n.. method:: File.save(name, content, save=True)\n\n    Saves a new file with the file name and contents provided. This will not\n    replace the existing file, but will create a new file and update the object\n    to point to it. If ``save`` is ``True``, the model's ``save()`` method will\n    be called once the file is saved. That is, these two lines::\n\n        >>> car.photo.save('myphoto.jpg', content, save=False)\n        >>> car.save()\n\n    are equivalent to::\n\n        >>> car.photo.save('myphoto.jpg', content, save=True)\n\n    Note that the ``content`` argument must be an instance of either\n    :class:`File` or of a subclass of :class:`File`, such as\n    :class:`~django.core.files.base.ContentFile`.\n\n.. method:: File.delete(save=True)\n\n    Removes the file from the model instance and deletes the underlying file.\n    If ``save`` is ``True``, the model's ``save()`` method will be called once\n    the file is deleted.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":47,"nodeType":"TextFile","repoName":null,"name":"models.txt","path":"docs/faq","text":"=========================\nFAQ: Databases and models\n=========================\n\n.. _faq-see-raw-sql-queries:\n\nHow can I see the raw SQL queries Django is running?\n====================================================\n\nMake sure your Django :setting:`DEBUG` setting is set to ``True``.\nThen do this::\n\n    >>> from django.db import connection\n    >>> connection.queries\n    [{'sql': 'SELECT polls_polls.id, polls_polls.question, polls_polls.pub_date FROM polls_polls',\n    'time': '0.002'}]\n\n``connection.queries`` is only available if :setting:`DEBUG` is ``True``.\nIt's a list of dictionaries in order of query execution. Each dictionary has\nthe following::\n\n    ``sql`` -- The raw SQL statement\n    ``time`` -- How long the statement took to execute, in seconds.\n\n``connection.queries`` includes all SQL statements -- INSERTs, UPDATES,\nSELECTs, etc. Each time your app hits the database, the query will be recorded.\n\nIf you are using :doc:`multiple databases</topics/db/multi-db>`, you can use the\nsame interface on each member of the ``connections`` dictionary::\n\n    >>> from django.db import connections\n    >>> connections['my_db_alias'].queries\n\nIf you need to clear the query list manually at any point in your functions,\ncall ``reset_queries()``, like this::\n\n    from django.db import reset_queries\n    reset_queries()\n\nCan I use Django with a pre-existing database?\n==============================================\n\nYes. See :doc:`Integrating with a legacy database </howto/legacy-databases>`.\n\nIf I make changes to a model, how do I update the database?\n===========================================================\n\nTake a look at Django's support for :mod:`schema migrations\n<django.db.migrations>`.\n\nIf you don't mind clearing data, your project's ``manage.py`` utility has a\n:djadmin:`flush` option to reset the database to the state it was in\nimmediately after :djadmin:`migrate` was executed.\n\nDo Django models support multiple-column primary keys?\n======================================================\n\nNo. Only single-column primary keys are supported.\n\nBut this isn't an issue in practice, because there's nothing stopping you from\nadding other constraints (using the ``unique_together`` model option or\ncreating the constraint directly in your database), and enforcing the\nuniqueness at that level. Single-column primary keys are needed for things such\nas the admin interface to work; e.g., you need a single value to specify\nan object to edit or delete.\n\nDoes Django support NoSQL databases?\n====================================\n\nNoSQL databases are not officially supported by Django itself. There are,\nhowever, a number of side projects and forks which allow NoSQL functionality in\nDjango.\n\nYou can take a look on `the wiki page`_ which discusses some projects.\n\n.. _the wiki page: https://code.djangoproject.com/wiki/NoSqlSupport\n\nHow do I add database-specific options to my CREATE TABLE statements, such as specifying MyISAM as the table type?\n==================================================================================================================\n\nWe try to avoid adding special cases in the Django code to accommodate all the\ndatabase-specific options such as table type, etc. If you'd like to use any of\nthese options, create a migration with a\n:class:`~django.db.migrations.operations.RunSQL` operation that contains\n``ALTER TABLE`` statements that do what you want to do.\n\nFor example, if you're using MySQL and want your tables to use the MyISAM table\ntype, use the following SQL::\n\n    ALTER TABLE myapp_mytable ENGINE=MyISAM;\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":48,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/faq","text":"==========\nDjango FAQ\n==========\n\n.. toctree::\n   :maxdepth: 2\n\n   general\n   install\n   usage\n   help\n   models\n   admin\n   contributing\n   troubleshooting\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":49,"nodeType":"Package","repoName":null,"name":"","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":50,"nodeType":"TextFile","repoName":null,"name":"LICENSE","path":"","text":"Copyright (c) Django Software Foundation and individual contributors.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n    1. Redistributions of source code must retain the above copyright notice,\n       this list of conditions and the following disclaimer.\n\n    2. Redistributions in binary form must reproduce the above copyright\n       notice, this list of conditions and the following disclaimer in the\n       documentation and/or other materials provided with the distribution.\n\n    3. Neither the name of Django nor the names of its contributors may be used\n       to endorse or promote products derived from this software without\n       specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":51,"nodeType":"TextFile","repoName":null,"name":"help.txt","path":"docs/faq","text":"=================\nFAQ: Getting Help\n=================\n\nHow do I do X? Why doesn't Y work? Where can I go to get help?\n==============================================================\n\nFirst, please check if your question is answered on the :doc:`FAQ <faq/index>`.\nAlso, search for answers using your favorite search engine, and in `the\nforum`_.\n\n.. _`the forum`: https://forum.djangoproject.com/\n\nIf you can't find an answer, please take a few minutes to formulate your\nquestion well. Explaining the problems you are facing clearly will help others\nhelp you. See the StackOverflow guide on `asking good questions`_.\n\n.. _`asking good questions`: https://stackoverflow.com/help/how-to-ask\n\nThen, please post it in one of the following channels:\n\n* The Django Forum section `\"Using Django\"`_. This is for web-based\n  discussions.\n* The |django-users| mailing list. This is for email-based discussions.\n* The `#django IRC channel`_ on the Freenode IRC network. This is for\n  chat-based discussions. If you're new to IRC, see the `Freenode\n  documentation`_ for different ways to connect.\n\n.. _`\"Using Django\"`: https://forum.djangoproject.com/c/users\n.. _#django IRC channel: https://webchat.freenode.net/#django\n.. _Freenode documentation: https://freenode.net/kb/answer/chat\n\nIn all these channels please abide by the `Django Code of Conduct`_. In\nsummary, being friendly and patient, considerate, respectful, and careful in\nyour choice of words.\n\n.. _Django Code of Conduct: https://www.djangoproject.com/conduct/\n\n.. _message-does-not-appear-on-django-users:\n\nWhy hasn't my message appeared on *django-users*?\n=================================================\n\n|django-users| has a lot of subscribers. This is good for the community, as\nit means many people are available to contribute answers to questions.\nUnfortunately, it also means that |django-users| is an attractive target for\nspammers.\n\nIn order to combat the spam problem, when you join the |django-users| mailing\nlist, we manually moderate the first message you send to the list. This means\nthat spammers get caught, but it also means that your first question to the\nlist might take a little longer to get answered. We apologize for any\ninconvenience that this policy may cause.\n\nNobody answered my question! What should I do?\n==============================================\n\nTry making your question more specific, or provide a better example of your\nproblem.\n\nAs with most open-source projects, the folks on these channels are volunteers.\nIf nobody has answered your question, it may be because nobody knows the\nanswer, it may be because nobody can understand the question, or it may be that\neverybody that can help is busy.\n\nYou can also try asking on a different channel. But please don't post your\nquestion in all three channels in quick succession.\n\nYou might notice we have a second mailing list, called |django-developers|.\nThis list is for discussion of the development of Django itself. Please don't\nemail support questions to this mailing list. Asking a tech support question\nthere is considered impolite, and you will likely be directed to ask on\n|django-users|.\n\nI think I've found a bug! What should I do?\n===========================================\n\nDetailed instructions on how to handle a potential bug can be found in our\n:ref:`Guide to contributing to Django <reporting-bugs>`.\n\nI think I've found a security problem! What should I do?\n========================================================\n\nIf you think you've found a security problem with Django, please send a message\nto security@djangoproject.com. This is a private list only open to long-time,\nhighly trusted Django developers, and its archives are not publicly readable.\n\nDue to the sensitive nature of security issues, we ask that if you think you\nhave found a security problem, *please* don't post a message on the forum, IRC,\nor one of the public mailing lists. Django has a\n:ref:`policy for handling security issues <reporting-security-issues>`;\nwhile a defect is outstanding, we would like to minimize any damage that\ncould be inflicted through public knowledge of that defect.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":52,"nodeType":"TextFile","repoName":null,"name":"usage.txt","path":"docs/faq","text":"=================\nFAQ: Using Django\n=================\n\nWhy do I get an error about importing :envvar:`DJANGO_SETTINGS_MODULE`?\n=======================================================================\n\nMake sure that:\n\n* The environment variable :envvar:`DJANGO_SETTINGS_MODULE` is set to a\n  fully-qualified Python module (i.e. \"mysite.settings\").\n\n* Said module is on ``sys.path`` (``import mysite.settings`` should work).\n\n* The module doesn't contain syntax errors.\n\nI can't stand your template language. Do I have to use it?\n==========================================================\n\nWe happen to think our template engine is the best thing since chunky bacon,\nbut we recognize that choosing a template language runs close to religion.\nThere's nothing about Django that requires using the template language, so\nif you're attached to Jinja2, Mako, or whatever, feel free to use those.\n\nDo I have to use your model/database layer?\n===========================================\n\nNope. Just like the template system, the model/database layer is decoupled from\nthe rest of the framework.\n\nThe one exception is: If you use a different database library, you won't get to\nuse Django's automatically-generated admin site. That app is coupled to the\nDjango database layer.\n\nHow do I use image and file fields?\n===================================\n\nUsing a :class:`~django.db.models.FileField` or an\n:class:`~django.db.models.ImageField` in a model takes a few steps:\n\n#. In your settings file, you'll need to define :setting:`MEDIA_ROOT` as\n   the full path to a directory where you'd like Django to store uploaded\n   files. (For performance, these files are not stored in the database.)\n   Define :setting:`MEDIA_URL` as the base public URL of that directory.\n   Make sure that this directory is writable by the Web server's user\n   account.\n\n#. Add the :class:`~django.db.models.FileField` or\n   :class:`~django.db.models.ImageField` to your model, defining the\n   :attr:`~django.db.models.FileField.upload_to` option to specify a\n   subdirectory of :setting:`MEDIA_ROOT` to use for uploaded files.\n\n#. All that will be stored in your database is a path to the file\n   (relative to :setting:`MEDIA_ROOT`). You'll most likely want to use the\n   convenience :attr:`~django.db.models.fields.files.FieldFile.url` attribute\n   provided by Django. For example, if your\n   :class:`~django.db.models.ImageField` is called ``mug_shot``, you can get\n   the absolute path to your image in a template with\n   ``{{ object.mug_shot.url }}``.\n\nHow do I make a variable available to all my templates?\n=======================================================\n\nSometimes your templates all need the same thing. A common example would be\ndynamically generated menus. At first glance, it seems logical to add a common\ndictionary to the template context.\n\nThe best way to do this in Django is to use a ``RequestContext``. Details on\nhow to do this are here: :ref:`subclassing-context-requestcontext`.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":53,"nodeType":"Package","repoName":null,"name":"docs","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":54,"nodeType":"TextFile","repoName":null,"name":"glossary.txt","path":"docs","text":"========\nGlossary\n========\n\n.. glossary::\n\n    concrete model\n        A non-abstract (:attr:`abstract=False\n        <django.db.models.Options.abstract>`) model.\n\n    field\n        An attribute on a :term:`model`; a given field usually maps directly to\n        a single database column.\n\n        See :doc:`/topics/db/models`.\n\n    generic view\n        A higher-order :term:`view` function that provides an abstract/generic\n        implementation of a common idiom or pattern found in view development.\n\n        See :doc:`/topics/class-based-views/index`.\n\n    model\n        Models store your application's data.\n\n        See :doc:`/topics/db/models`.\n\n    MTV\n        \"Model-template-view\"; a software pattern, similar in style to MVC, but\n        a better description of the way Django does things.\n\n        See :ref:`the FAQ entry <faq-mtv>`.\n\n    MVC\n        `Model-view-controller`__; a software pattern. Django :ref:`follows MVC\n        to some extent <faq-mtv>`.\n\n        __ https://en.wikipedia.org/wiki/Model-view-controller\n\n    project\n        A Python package -- i.e. a directory of code -- that contains all the\n        settings for an instance of Django. This would include database\n        configuration, Django-specific options and application-specific\n        settings.\n\n    property\n        Also known as \"managed attributes\", and a feature of Python since\n        version 2.2. This is a neat way to implement attributes whose usage\n        resembles attribute access, but whose implementation uses method calls.\n\n        See :class:`property`.\n\n    queryset\n        An object representing some set of rows to be fetched from the database.\n\n        See :doc:`/topics/db/queries`.\n\n    slug\n        A short label for something, containing only letters, numbers,\n        underscores or hyphens. They're generally used in URLs. For\n        example, in a typical blog entry URL:\n\n        .. parsed-literal::\n\n            https://www.djangoproject.com/weblog/2008/apr/12/**spring**/\n\n        the last bit (``spring``) is the slug.\n\n    template\n        A chunk of text that acts as formatting for representing data. A\n        template helps to abstract the presentation of data from the data\n        itself.\n\n        See :doc:`/topics/templates`.\n\n    view\n        A function responsible for rendering a page.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":55,"nodeType":"TextFile","repoName":null,"name":"troubleshooting.txt","path":"docs/faq","text":"===============\nTroubleshooting\n===============\n\nThis page contains some advice about errors and problems commonly encountered\nduring the development of Django applications.\n\n.. _troubleshooting-django-admin:\n\nProblems running ``django-admin``\n=================================\n\n``command not found: django-admin``\n-----------------------------------\n\n:doc:`django-admin </ref/django-admin>` should be on your system path if you\ninstalled Django via ``pip``. If it's not in your path, ensure you have your\nvirtual environment activated and you can try running the equivalent command\n``python -m django``.\n\nmacOS permissions\n-----------------\n\nIf you're using macOS, you may see the message \"permission denied\" when\nyou try to run ``django-admin``. This is because, on Unix-based systems like\nmacOS, a file must be marked as \"executable\" before it can be run as a program.\nTo do this, open Terminal.app and navigate (using the ``cd`` command) to the\ndirectory where :doc:`django-admin </ref/django-admin>` is installed, then\nrun the command ``sudo chmod +x django-admin``.\n\nMiscellaneous\n=============\n\nI'm getting a ``UnicodeDecodeError``. What am I doing wrong?\n------------------------------------------------------------\n\nThis class of errors happen when a bytestring containing non-ASCII sequences is\ntransformed into a Unicode string and the specified encoding is incorrect. The\noutput generally looks like this::\n\n    UnicodeDecodeError: 'ascii' codec can't decode byte 0x?? in position ?:\n    ordinal not in range(128)\n\nThe resolution mostly depends on the context, however here are two common\npitfalls producing this error:\n\n* Your system locale may be a default ASCII locale, like the \"C\" locale on\n  UNIX-like systems (can be checked by the ``locale`` command). If it's the\n  case, please refer to your system documentation to learn how you can change\n  this to a UTF-8 locale.\n\nRelated resources:\n\n* :doc:`Unicode in Django </ref/unicode>`\n* https://wiki.python.org/moin/UnicodeDecodeError\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":56,"nodeType":"TextFile","repoName":null,"name":"LICENSE.python","path":"","text":"Django is licensed under the three-clause BSD license; see the file\nLICENSE for details.\n\nDjango includes code from the Python standard library, which is licensed under\nthe Python license, a permissive open source license. The copyright and license\nis included below for compliance with Python's terms.\n\n----------------------------------------------------------------------\n\nCopyright (c) 2001-present Python Software Foundation; All Rights Reserved\n\nA. HISTORY OF THE SOFTWARE\n==========================\n\nPython was created in the early 1990s by Guido van Rossum at Stichting\nMathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands\nas a successor of a language called ABC.  Guido remains Python's\nprincipal author, although it includes many contributions from others.\n\nIn 1995, Guido continued his work on Python at the Corporation for\nNational Research Initiatives (CNRI, see http://www.cnri.reston.va.us)\nin Reston, Virginia where he released several versions of the\nsoftware.\n\nIn May 2000, Guido and the Python core development team moved to\nBeOpen.com to form the BeOpen PythonLabs team.  In October of the same\nyear, the PythonLabs team moved to Digital Creations, which became\nZope Corporation.  In 2001, the Python Software Foundation (PSF, see\nhttps://www.python.org/psf/) was formed, a non-profit organization\ncreated specifically to own Python-related Intellectual Property.\nZope Corporation was a sponsoring member of the PSF.\n\nAll Python releases are Open Source (see http://www.opensource.org for\nthe Open Source Definition).  Historically, most, but not all, Python\nreleases have also been GPL-compatible; the table below summarizes\nthe various releases.\n\n    Release         Derived     Year        Owner       GPL-\n                    from                                compatible? (1)\n\n    0.9.0 thru 1.2              1991-1995   CWI         yes\n    1.3 thru 1.5.2  1.2         1995-1999   CNRI        yes\n    1.6             1.5.2       2000        CNRI        no\n    2.0             1.6         2000        BeOpen.com  no\n    1.6.1           1.6         2001        CNRI        yes (2)\n    2.1             2.0+1.6.1   2001        PSF         no\n    2.0.1           2.0+1.6.1   2001        PSF         yes\n    2.1.1           2.1+2.0.1   2001        PSF         yes\n    2.1.2           2.1.1       2002        PSF         yes\n    2.1.3           2.1.2       2002        PSF         yes\n    2.2 and above   2.1.1       2001-now    PSF         yes\n\nFootnotes:\n\n(1) GPL-compatible doesn't mean that we're distributing Python under\n    the GPL.  All Python licenses, unlike the GPL, let you distribute\n    a modified version without making your changes open source.  The\n    GPL-compatible licenses make it possible to combine Python with\n    other software that is released under the GPL; the others don't.\n\n(2) According to Richard Stallman, 1.6.1 is not GPL-compatible,\n    because its license has a choice of law clause.  According to\n    CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1\n    is \"not incompatible\" with the GPL.\n\nThanks to the many outside volunteers who have worked under Guido's\ndirection to make these releases possible.\n\n\nB. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON\n===============================================================\n\nPYTHON SOFTWARE FOUNDATION LICENSE VERSION 2\n--------------------------------------------\n\n1. This LICENSE AGREEMENT is between the Python Software Foundation\n(\"PSF\"), and the Individual or Organization (\"Licensee\") accessing and\notherwise using this software (\"Python\") in source or binary form and\nits associated documentation.\n\n2. Subject to the terms and conditions of this License Agreement, PSF hereby\ngrants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,\nanalyze, test, perform and/or display publicly, prepare derivative works,\ndistribute, and otherwise use Python alone or in any derivative version,\nprovided, however, that PSF's License Agreement and PSF's notice of copyright,\ni.e., \"Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,\n2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Python Software Foundation;\nAll Rights Reserved\" are retained in Python alone or in any derivative version\nprepared by Licensee.\n\n3. In the event Licensee prepares a derivative work that is based on\nor incorporates Python or any part thereof, and wants to make\nthe derivative work available to others as provided herein, then\nLicensee hereby agrees to include in any such work a brief summary of\nthe changes made to Python.\n\n4. PSF is making Python available to Licensee on an \"AS IS\"\nbasis.  PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT\nINFRINGE ANY THIRD PARTY RIGHTS.\n\n5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON\nFOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS\nA RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,\nOR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.\n\n6. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n\n7. Nothing in this License Agreement shall be deemed to create any\nrelationship of agency, partnership, or joint venture between PSF and\nLicensee.  This License Agreement does not grant permission to use PSF\ntrademarks or trade name in a trademark sense to endorse or promote\nproducts or services of Licensee, or any third party.\n\n8. By copying, installing or otherwise using Python, Licensee\nagrees to be bound by the terms and conditions of this License\nAgreement.\n\n\nBEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0\n-------------------------------------------\n\nBEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1\n\n1. This LICENSE AGREEMENT is between BeOpen.com (\"BeOpen\"), having an\noffice at 160 Saratoga Avenue, Santa Clara, CA 95051, and the\nIndividual or Organization (\"Licensee\") accessing and otherwise using\nthis software in source or binary form and its associated\ndocumentation (\"the Software\").\n\n2. Subject to the terms and conditions of this BeOpen Python License\nAgreement, BeOpen hereby grants Licensee a non-exclusive,\nroyalty-free, world-wide license to reproduce, analyze, test, perform\nand/or display publicly, prepare derivative works, distribute, and\notherwise use the Software alone or in any derivative version,\nprovided, however, that the BeOpen Python License is retained in the\nSoftware, alone or in any derivative version prepared by Licensee.\n\n3. BeOpen is making the Software available to Licensee on an \"AS IS\"\nbasis.  BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT\nINFRINGE ANY THIRD PARTY RIGHTS.\n\n4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE\nSOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS\nAS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY\nDERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.\n\n5. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n\n6. This License Agreement shall be governed by and interpreted in all\nrespects by the law of the State of California, excluding conflict of\nlaw provisions.  Nothing in this License Agreement shall be deemed to\ncreate any relationship of agency, partnership, or joint venture\nbetween BeOpen and Licensee.  This License Agreement does not grant\npermission to use BeOpen trademarks or trade names in a trademark\nsense to endorse or promote products or services of Licensee, or any\nthird party.  As an exception, the \"BeOpen Python\" logos available at\nhttp://www.pythonlabs.com/logos.html may be used according to the\npermissions granted on that web page.\n\n7. By copying, installing or otherwise using the software, Licensee\nagrees to be bound by the terms and conditions of this License\nAgreement.\n\n\nCNRI LICENSE AGREEMENT FOR PYTHON 1.6.1\n---------------------------------------\n\n1. This LICENSE AGREEMENT is between the Corporation for National\nResearch Initiatives, having an office at 1895 Preston White Drive,\nReston, VA 20191 (\"CNRI\"), and the Individual or Organization\n(\"Licensee\") accessing and otherwise using Python 1.6.1 software in\nsource or binary form and its associated documentation.\n\n2. Subject to the terms and conditions of this License Agreement, CNRI\nhereby grants Licensee a nonexclusive, royalty-free, world-wide\nlicense to reproduce, analyze, test, perform and/or display publicly,\nprepare derivative works, distribute, and otherwise use Python 1.6.1\nalone or in any derivative version, provided, however, that CNRI's\nLicense Agreement and CNRI's notice of copyright, i.e., \"Copyright (c)\n1995-2001 Corporation for National Research Initiatives; All Rights\nReserved\" are retained in Python 1.6.1 alone or in any derivative\nversion prepared by Licensee.  Alternately, in lieu of CNRI's License\nAgreement, Licensee may substitute the following text (omitting the\nquotes): \"Python 1.6.1 is made available subject to the terms and\nconditions in CNRI's License Agreement.  This Agreement together with\nPython 1.6.1 may be located on the Internet using the following\nunique, persistent identifier (known as a handle): 1895.22/1013.  This\nAgreement may also be obtained from a proxy server on the Internet\nusing the following URL: http://hdl.handle.net/1895.22/1013\".\n\n3. In the event Licensee prepares a derivative work that is based on\nor incorporates Python 1.6.1 or any part thereof, and wants to make\nthe derivative work available to others as provided herein, then\nLicensee hereby agrees to include in any such work a brief summary of\nthe changes made to Python 1.6.1.\n\n4. CNRI is making Python 1.6.1 available to Licensee on an \"AS IS\"\nbasis.  CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT\nINFRINGE ANY THIRD PARTY RIGHTS.\n\n5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON\n1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS\nA RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,\nOR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.\n\n6. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n\n7. This License Agreement shall be governed by the federal\nintellectual property law of the United States, including without\nlimitation the federal copyright law, and, to the extent such\nU.S. federal law does not apply, by the law of the Commonwealth of\nVirginia, excluding Virginia's conflict of law provisions.\nNotwithstanding the foregoing, with regard to derivative works based\non Python 1.6.1 that incorporate non-separable material that was\npreviously distributed under the GNU General Public License (GPL), the\nlaw of the Commonwealth of Virginia shall govern this License\nAgreement only as to issues arising under or with respect to\nParagraphs 4, 5, and 7 of this License Agreement.  Nothing in this\nLicense Agreement shall be deemed to create any relationship of\nagency, partnership, or joint venture between CNRI and Licensee.  This\nLicense Agreement does not grant permission to use CNRI trademarks or\ntrade name in a trademark sense to endorse or promote products or\nservices of Licensee, or any third party.\n\n8. By clicking on the \"ACCEPT\" button where indicated, or by copying,\ninstalling or otherwise using Python 1.6.1, Licensee agrees to be\nbound by the terms and conditions of this License Agreement.\n\n        ACCEPT\n\n\nCWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2\n--------------------------------------------------\n\nCopyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,\nThe Netherlands.  All rights reserved.\n\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee is hereby granted,\nprovided that the above copyright notice appear in all copies and that\nboth that copyright notice and this permission notice appear in\nsupporting documentation, and that the name of Stichting Mathematisch\nCentrum or CWI not be used in advertising or publicity pertaining to\ndistribution of the software without specific, written prior\npermission.\n\nSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO\nTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\nFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE\nFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT\nOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":57,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs","text":"====================\nDjango documentation\n====================\n\n.. rubric:: Everything you need to know about Django.\n\n.. _index-first-steps:\n\nFirst steps\n===========\n\nAre you new to Django or to programming? This is the place to start!\n\n* **From scratch:**\n  :doc:`Overview <intro/overview>` |\n  :doc:`Installation <intro/install>`\n\n* **Tutorial:**\n  :doc:`Part 1: Requests and responses <intro/tutorial01>` |\n  :doc:`Part 2: Models and the admin site <intro/tutorial02>` |\n  :doc:`Part 3: Views and templates <intro/tutorial03>` |\n  :doc:`Part 4: Forms and generic views <intro/tutorial04>` |\n  :doc:`Part 5: Testing <intro/tutorial05>` |\n  :doc:`Part 6: Static files <intro/tutorial06>` |\n  :doc:`Part 7: Customizing the admin site <intro/tutorial07>`\n\n* **Advanced Tutorials:**\n  :doc:`How to write reusable apps <intro/reusable-apps>` |\n  :doc:`Writing your first patch for Django <intro/contributing>`\n\nGetting help\n============\n\nHaving trouble? We'd like to help!\n\n* Try the :doc:`FAQ <faq/index>` -- it's got answers to many common questions.\n\n* Looking for specific information? Try the :ref:`genindex`, :ref:`modindex` or\n  the :doc:`detailed table of contents <contents>`.\n\n* Not found anything? See :doc:`faq/help` for information on getting support\n  and asking questions to the community.\n\n* Report bugs with Django in our `ticket tracker`_.\n\n.. _ticket tracker: https://code.djangoproject.com/\n\nHow the documentation is organized\n==================================\n\nDjango has a lot of documentation. A high-level overview of how it's organized\nwill help you know where to look for certain things:\n\n* :doc:`Tutorials </intro/index>` take you by the hand through a series of\n  steps to create a Web application. Start here if you're new to Django or Web\n  application development. Also look at the \":ref:`index-first-steps`\".\n\n* :doc:`Topic guides </topics/index>` discuss key topics and concepts at a\n  fairly high level and provide useful background information and explanation.\n\n* :doc:`Reference guides </ref/index>` contain technical reference for APIs and\n  other aspects of Django's machinery. They describe how it works and how to\n  use it but assume that you have a basic understanding of key concepts.\n\n* :doc:`How-to guides </howto/index>` are recipes. They guide you through the\n  steps involved in addressing key problems and use-cases. They are more\n  advanced than tutorials and assume some knowledge of how Django works.\n\nThe model layer\n===============\n\nDjango provides an abstraction layer (the \"models\") for structuring and\nmanipulating the data of your Web application. Learn more about it below:\n\n* **Models:**\n  :doc:`Introduction to models <topics/db/models>` |\n  :doc:`Field types <ref/models/fields>` |\n  :doc:`Indexes <ref/models/indexes>` |\n  :doc:`Meta options <ref/models/options>` |\n  :doc:`Model class <ref/models/class>`\n\n* **QuerySets:**\n  :doc:`Making queries <topics/db/queries>` |\n  :doc:`QuerySet method reference <ref/models/querysets>` |\n  :doc:`Lookup expressions <ref/models/lookups>`\n\n* **Model instances:**\n  :doc:`Instance methods <ref/models/instances>` |\n  :doc:`Accessing related objects <ref/models/relations>`\n\n* **Migrations:**\n  :doc:`Introduction to Migrations<topics/migrations>` |\n  :doc:`Operations reference <ref/migration-operations>` |\n  :doc:`SchemaEditor <ref/schema-editor>` |\n  :doc:`Writing migrations <howto/writing-migrations>`\n\n* **Advanced:**\n  :doc:`Managers <topics/db/managers>` |\n  :doc:`Raw SQL <topics/db/sql>` |\n  :doc:`Transactions <topics/db/transactions>` |\n  :doc:`Aggregation <topics/db/aggregation>` |\n  :doc:`Search <topics/db/search>` |\n  :doc:`Custom fields <howto/custom-model-fields>` |\n  :doc:`Multiple databases <topics/db/multi-db>` |\n  :doc:`Custom lookups <howto/custom-lookups>` |\n  :doc:`Query Expressions <ref/models/expressions>` |\n  :doc:`Conditional Expressions <ref/models/conditional-expressions>` |\n  :doc:`Database Functions <ref/models/database-functions>`\n\n* **Other:**\n  :doc:`Supported databases <ref/databases>` |\n  :doc:`Legacy databases <howto/legacy-databases>` |\n  :doc:`Providing initial data <howto/initial-data>` |\n  :doc:`Optimize database access <topics/db/optimization>` |\n  :doc:`PostgreSQL specific features <ref/contrib/postgres/index>`\n\nThe view layer\n==============\n\nDjango has the concept of \"views\" to encapsulate the logic responsible for\nprocessing a user's request and for returning the response. Find all you need\nto know about views via the links below:\n\n* **The basics:**\n  :doc:`URLconfs <topics/http/urls>` |\n  :doc:`View functions <topics/http/views>` |\n  :doc:`Shortcuts <topics/http/shortcuts>` |\n  :doc:`Decorators <topics/http/decorators>` |\n  :doc:`Asynchronous Support <topics/async>`\n\n* **Reference:**\n  :doc:`Built-in Views <ref/views>` |\n  :doc:`Request/response objects <ref/request-response>` |\n  :doc:`TemplateResponse objects <ref/template-response>`\n\n* **File uploads:**\n  :doc:`Overview <topics/http/file-uploads>` |\n  :doc:`File objects <ref/files/file>` |\n  :doc:`Storage API <ref/files/storage>` |\n  :doc:`Managing files <topics/files>` |\n  :doc:`Custom storage <howto/custom-file-storage>`\n\n* **Class-based views:**\n  :doc:`Overview <topics/class-based-views/index>` |\n  :doc:`Built-in display views <topics/class-based-views/generic-display>` |\n  :doc:`Built-in editing views <topics/class-based-views/generic-editing>` |\n  :doc:`Using mixins <topics/class-based-views/mixins>` |\n  :doc:`API reference <ref/class-based-views/index>` |\n  :doc:`Flattened index<ref/class-based-views/flattened-index>`\n\n* **Advanced:**\n  :doc:`Generating CSV <howto/outputting-csv>` |\n  :doc:`Generating PDF <howto/outputting-pdf>`\n\n* **Middleware:**\n  :doc:`Overview <topics/http/middleware>` |\n  :doc:`Built-in middleware classes <ref/middleware>`\n\nThe template layer\n==================\n\nThe template layer provides a designer-friendly syntax for rendering the\ninformation to be presented to the user. Learn how this syntax can be used by\ndesigners and how it can be extended by programmers:\n\n* **The basics:**\n  :doc:`Overview <topics/templates>`\n\n* **For designers:**\n  :doc:`Language overview <ref/templates/language>` |\n  :doc:`Built-in tags and filters <ref/templates/builtins>` |\n  :doc:`Humanization <ref/contrib/humanize>`\n\n* **For programmers:**\n  :doc:`Template API <ref/templates/api>` |\n  :doc:`Custom tags and filters <howto/custom-template-tags>` |\n  :doc:`Custom template backend <howto/custom-template-backend>`\n\nForms\n=====\n\nDjango provides a rich framework to facilitate the creation of forms and the\nmanipulation of form data.\n\n* **The basics:**\n  :doc:`Overview <topics/forms/index>` |\n  :doc:`Form API <ref/forms/api>` |\n  :doc:`Built-in fields <ref/forms/fields>` |\n  :doc:`Built-in widgets <ref/forms/widgets>`\n\n* **Advanced:**\n  :doc:`Forms for models <topics/forms/modelforms>` |\n  :doc:`Integrating media <topics/forms/media>` |\n  :doc:`Formsets <topics/forms/formsets>` |\n  :doc:`Customizing validation <ref/forms/validation>`\n\nThe development process\n=======================\n\nLearn about the various components and tools to help you in the development and\ntesting of Django applications:\n\n* **Settings:**\n  :doc:`Overview <topics/settings>` |\n  :doc:`Full list of settings <ref/settings>`\n\n* **Applications:**\n  :doc:`Overview <ref/applications>`\n\n* **Exceptions:**\n  :doc:`Overview <ref/exceptions>`\n\n* **django-admin and manage.py:**\n  :doc:`Overview <ref/django-admin>` |\n  :doc:`Adding custom commands <howto/custom-management-commands>`\n\n* **Testing:**\n  :doc:`Introduction <topics/testing/index>` |\n  :doc:`Writing and running tests <topics/testing/overview>` |\n  :doc:`Included testing tools <topics/testing/tools>` |\n  :doc:`Advanced topics <topics/testing/advanced>`\n\n* **Deployment:**\n  :doc:`Overview <howto/deployment/index>` |\n  :doc:`WSGI servers <howto/deployment/wsgi/index>` |\n  :doc:`ASGI servers <howto/deployment/asgi/index>` |\n  :doc:`Deploying static files <howto/static-files/deployment>` |\n  :doc:`Tracking code errors by email <howto/error-reporting>` |\n  :doc:`Deployment checklist <howto/deployment/checklist>`\n\nThe admin\n=========\n\nFind all you need to know about the automated admin interface, one of Django's\nmost popular features:\n\n* :doc:`Admin site <ref/contrib/admin/index>`\n* :doc:`Admin actions <ref/contrib/admin/actions>`\n* :doc:`Admin documentation generator<ref/contrib/admin/admindocs>`\n\nSecurity\n========\n\nSecurity is a topic of paramount importance in the development of Web\napplications and Django provides multiple protection tools and mechanisms:\n\n* :doc:`Security overview <topics/security>`\n* :doc:`Disclosed security issues in Django <releases/security>`\n* :doc:`Clickjacking protection <ref/clickjacking>`\n* :doc:`Cross Site Request Forgery protection <ref/csrf>`\n* :doc:`Cryptographic signing <topics/signing>`\n* :ref:`Security Middleware <security-middleware>`\n\nInternationalization and localization\n=====================================\n\nDjango offers a robust internationalization and localization framework to\nassist you in the development of applications for multiple languages and world\nregions:\n\n* :doc:`Overview <topics/i18n/index>` |\n  :doc:`Internationalization <topics/i18n/translation>` |\n  :ref:`Localization <how-to-create-language-files>` |\n  :doc:`Localized Web UI formatting and form input <topics/i18n/formatting>`\n* :doc:`Time zones </topics/i18n/timezones>`\n\nPerformance and optimization\n============================\n\nThere are a variety of techniques and tools that can help get your code running\nmore efficiently - faster, and using fewer system resources.\n\n* :doc:`Performance and optimization overview <topics/performance>`\n\nGeographic framework\n====================\n\n:doc:`GeoDjango <ref/contrib/gis/index>` intends to be a world-class geographic\nWeb framework. Its goal is to make it as easy as possible to build GIS Web\napplications and harness the power of spatially enabled data.\n\nCommon Web application tools\n============================\n\nDjango offers multiple tools commonly needed in the development of Web\napplications:\n\n* **Authentication:**\n  :doc:`Overview <topics/auth/index>` |\n  :doc:`Using the authentication system <topics/auth/default>` |\n  :doc:`Password management <topics/auth/passwords>` |\n  :doc:`Customizing authentication <topics/auth/customizing>` |\n  :doc:`API Reference <ref/contrib/auth>`\n* :doc:`Caching <topics/cache>`\n* :doc:`Logging <topics/logging>`\n* :doc:`Sending emails <topics/email>`\n* :doc:`Syndication feeds (RSS/Atom) <ref/contrib/syndication>`\n* :doc:`Pagination <topics/pagination>`\n* :doc:`Messages framework <ref/contrib/messages>`\n* :doc:`Serialization <topics/serialization>`\n* :doc:`Sessions <topics/http/sessions>`\n* :doc:`Sitemaps <ref/contrib/sitemaps>`\n* :doc:`Static files management <ref/contrib/staticfiles>`\n* :doc:`Data validation <ref/validators>`\n\nOther core functionalities\n==========================\n\nLearn about some other core functionalities of the Django framework:\n\n* :doc:`Conditional content processing <topics/conditional-view-processing>`\n* :doc:`Content types and generic relations <ref/contrib/contenttypes>`\n* :doc:`Flatpages <ref/contrib/flatpages>`\n* :doc:`Redirects <ref/contrib/redirects>`\n* :doc:`Signals <topics/signals>`\n* :doc:`System check framework <topics/checks>`\n* :doc:`The sites framework <ref/contrib/sites>`\n* :doc:`Unicode in Django <ref/unicode>`\n\nThe Django open-source project\n==============================\n\nLearn about the development process for the Django project itself and about how\nyou can contribute:\n\n* **Community:**\n  :doc:`How to get involved <internals/contributing/index>` |\n  :doc:`The release process <internals/release-process>` |\n  :doc:`Team organization <internals/organization>` |\n  :doc:`The Django source code repository <internals/git>` |\n  :doc:`Security policies <internals/security>` |\n  :doc:`Mailing lists <internals/mailing-lists>`\n\n* **Design philosophies:**\n  :doc:`Overview <misc/design-philosophies>`\n\n* **Documentation:**\n  :doc:`About this documentation <internals/contributing/writing-documentation>`\n\n* **Third-party distributions:**\n  :doc:`Overview <misc/distributions>`\n\n* **Django over time:**\n  :doc:`API stability <misc/api-stability>` |\n  :doc:`Release notes and upgrading instructions <releases/index>` |\n  :doc:`Deprecation Timeline <internals/deprecation>`\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":58,"nodeType":"TextFile","repoName":null,"name":"MANIFEST.in","path":"","text":"include AUTHORS\ninclude Gruntfile.js\ninclude INSTALL\ninclude LICENSE\ninclude LICENSE.python\ninclude MANIFEST.in\ninclude package.json\ninclude *.rst\ngraft django\ngraft docs\ngraft extras\ngraft js_tests\ngraft scripts\ngraft tests\nglobal-exclude __pycache__\nglobal-exclude *.py[co]\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":59,"nodeType":"TextFile","repoName":null,"name":"spelling_wordlist","path":"docs","text":"à\naccessor\naccessors\nAceh\nadmin\nadmindocs\nadmins\naffine\naffordances\naggregator\nAi\nAlchin\nalphanumerics\namet\namongst\nanalytics\napnumber\napp\nappname\napps\narccosine\narchitected\narcsine\narctangent\narg\nargs\nassistive\nasync\natomicity\nattr\nauth\nautoclobber\nautocommit\nautocomplete\nautocompletion\nautodetect\nautodetectable\nautodetection\nautodetector\nautodiscovery\nautoescape\nautoescaping\nautoextend\nautogenerated\nautoincrement\nautoreload\nautovacuum\nawaitable\nAzerbaijani\nbackend\nbackends\nbackport\nbackported\nbackports\nbacktraces\nbalancer\nbasename\nBcc\nBCC'ed\nbcrypt\nbeatles\nBeaven\nbenchmarking\nBenoit\nBerners\nBiggs\nbitwise\nBjørn\nblazingly\nblog\nblogs\nboilerplatish\nBokmål\nbolded\nBonham\nbookmarklet\nbookmarklets\nboolean\nbooleans\nbpython\nBronn\nbugfix\nbugfixes\nbuiltin\nbuiltins\nbulleted\nByteorder\nbytestring\nbytestrings\ncacheable\ncallables\ncamelCase\ncardinality\ncentric\ncentroid\nchangelist\nchangeset\ncharset\ncheckbox\ncheckboxes\ncheckin\nchecksum\nchecksums\nclearable\nclickable\nclickjacking\ncms\ncodebase\ncodec\ncodename\ncodenamed\ncoercible\ncommenters\ncommitter\ncommitters\nconcat\nconf\nconfig\ncontenttypes\ncontextvars\ncontrib\ncoroutine\ncoroutines\ncovariance\ncriticals\ncron\ncrontab\ncryptographic\ncryptographically\ncsrf\ncsrfmiddlewaretoken\ncss\ncsv\nctime\nCtrl\ncustomizability\ncustomizable\ncustomizations\nDahl\nDaly\nDanga\nDaphne\nDarussalam\ndatabrowse\ndatafile\ndataset\ndatasets\ndatatype\ndatetimes\nDebian\ndeclaratively\ndeconstruct\ndeconstructing\ndecrement\ndecrementing\ndeduplicates\ndeepcopy\ndeferrable\ndeprecations\ndeserialization\ndeserialize\ndeserialized\ndeserializer\ndeserializing\ndeterministically\nDeutsch\ndev\ndict\ndictConfig\ndicts\ndiff\nDimensionally\ndimensioned\ndirmod\ndiscoverable\nDisqus\ndistro\nDjango\ndjangoproject\nDjango's\ndm\ndocstring\ndocstrings\ndoctests\ndoctype\ndocumentational\nDoS\ndownloadable\nDreamweaver\ndrilldown\ndropdown\ndropdowns\ndrupal\nDunck\neditability\nelidable\nencodings\nEndian\nEnero\nenum\nenviron\nesque\nEss\nETag\nETags\nexe\nextensibility\nFacebook\nfallback\nfallbacks\nfaq\nFastCGI\nfavicon\nfieldset\nfieldsets\nfilename\nfilenames\nfilesystem\nfk\nflatpage\nflatpages\nFlatpages\nfollowup\nfooapp\nformatters\nformfield\nformset\nformsets\nformtools\nfreenode\nFrysian\nfunctionalities\ngdal\ngeo\nGeoff\ngeoip\ngeolibs\ngeolocalized\ngeolocated\ngeolocation\ngeoquerysets\ngeoreference\ngeoreferenced\ngeoreferencing\ngeospatial\nGettext\nGiB\ngid\ngis\nGitHub\nglobalization\ngoogle\nGoogol\nGreenhill\ngrey\ngte\ngunicorn\ngz\nGZip\ngzipped\nhackish\nhandheld\nhardcode\nhardcoded\nhardcoding\nhashable\nhasher\nhashers\nheaderlist\nhoc\nHoerner\nHolovaty\nHolscher\nHomebrew\nhostname\nhostnames\nhstore\nhtml\nhttp\nhttps\nhyperlinks\nie\nies\niframe\ninbox\nincrementing\nindexable\nindices\ning\nini\ninit\ninline\ninlines\nInstagram\ninstantiation\ninterdependencies\ninternet\ninteroperability\nintranet\niOS\nip\nipsum\nIPv\nIPython\nirc\nise\niso\niterable\niterables\niteratively\niTunes\nize\nJavaScript\nJinja\njQuery\nJupyter\njython\nKaplan\nKessler\nkeyservers\nKiB\nkilometre\nKoziarski\nkwarg\nkwargs\nKyngesburye\nlatin\nlawrence\nlexer\nlifecycle\nlifecycles\nlinearize\nlinestring\nlinework\nlinter\nLivni\nlocalflavor\nlocalhost\nlocalizable\nlocalizers\nlocaltime\nlogin\nlogout\nlookaround\nlookup\nlookups\nloopback\nlorem\nlossy\nlowercased\nlowercasing\nlt\nlte\nLuhn\nmacOS\nMagee\nMako\nmanouche\nMarino\nMBR\nmemcache\nmemcached\nmentorship\nmetaclass\nmetaclasses\nmetadata\nmetre\nMiB\nmicrometre\nmiddleware\nmigrationname\nmillimetre\nMinification\nminified\nminify\nmis\nmisconfiguration\nmitre\nmixin\nmixins\nmodelforms\nmodelformset\nmodwsgi\nmonkeypatched\nmulti\nMulti\nmulticolumn\nmultijoins\nmultiline\nmultilinestring\nmultipart\nmultipolygon\nmultitenancy\nmultithreaded\nmultithreading\nmultivalued\nMumbai\nmyapp\nmyproject\nmysite\nmysql\nmysqlclient\nnaïve\nnamespace\nnamespaced\nnamespaces\nnamespacing\nNanggroe\nnatively\nnd\nneedsinfo\nněmecky\nnewforms\nnginx\nnoding\nnonnegative\nnonspatial\nnullable\nOAuth\noffline\nOGC\nOGR\noldforms\nonline\nons\nonwards\noptimizations\norderable\norg\nOrléans\norm\noutbox\nOutdim\noutfile\npaginator\nparallelization\nparallelized\nparameterization\nparameterized\nparams\nparens\nparsers\npdf\nPEM\nperl\npermalink\npessimization\nPeucker\npgAdmin\nPgBouncer\nPGRaster\nphishing\nphp\npicklable\npicosecond\nPIL\npingback\npingbacks\nPinney\nPinterest\nplaintext\npluggable\nplugin\nplugins\npluralizations\npo\npodcast\npooler\npooling\npopup\npostfix\npostgis\npostgres\npostgresql\npq\npre\nprecisions\nprecomputation\npreconfigured\nprefetch\nprefetched\nprefetches\nprefetching\npreload\nprepend\nprepended\nprepending\nprepends\nprepopulate\nprepopulated\nprepopulates\npreprocess\npreprocessed\npreprocesses\npreprocessing\nprogrammatically\nproxied\nproxying\npseudocode\npsycopg\nPunycode\nPuthraya\npy\npyformat\npysqlite\npythonic\npytz\nqs\nqueryset\nquerysets\nquerystring\nqueueing\nQuickstart\nQUnit\nquo\nquoteless\nRadziej\nraster\nrasters\nrc\nreadded\nreallow\nreallowed\nreallows\nrebase\nrebased\nrebasing\nrecomputation\nrecursed\nredeclare\nredirections\nredisplay\nredisplayed\nredisplaying\nredisplays\nrefactor\nrefactored\nrefactoring\nrefactorings\nrefactors\nreferer\nreferers\nreflow\nregex\nregistrable\nreimplement\nreindent\nreindex\nreinstall\nreleaser\nreleasers\nreloader\nrenderer\nrenderers\nrepo\nreportable\nreprojection\nreraising\nresampling\nreST\nreStructuredText\nreusability\nrevalidate\nreverter\nroadmap\nRoald\nrss\nruntime\nSandvik\nsavepoint\nsavepoints\nscalable\nSchaub\nschemas\nscreencast\nscreencasts\nscreenshot\nscreenshots\nsemimajor\nsemiminor\nserializability\nserializable\nserializer\nserializers\nsessionid\nsetuptools\nsha\nshapefile\nshapefiles\nsharding\nsid\nsimultaneously\nsitemap\nsitemaps\nsitewide\nslashdot\nsliceable\nslippy\nSMTP\nsolaris\nSolr\nsortable\nspam\nspammers\nspatialite\nSpringmeyer\nSQL\nssi\nSSL\nstacktrace\nstartup\nstateful\nstaticfile\nstaticfiles\nstderr\nstdlib\nstdout\nstorages\nstylesheet\nstylesheets\nsubclass\nsubclassed\nsubclasses\nsubclassing\nsubcommand\nsubcommands\nsubdir\nsubdirectories\nsubdirectory\nsubdomain\nsubdomains\nsubfields\nsublanguage\nsublist\nsubmodule\nsubmodules\nsubpath\nsubprocesses\nsubqueries\nsubquery\nsubselect\nsubstring\nsubtemplate\nsubtemplates\nsubtransactions\nsubtree\nsubtype\nsubviews\nsubwidget\nsubwidgets\nsuperclass\nsuperclasses\nsuperset\nswappable\nsymlink\nsymlinking\nsymlinks\nsyntaxes\nsysadmin\nsystemwide\ntablespace\ntablespaces\ntagline\ntarball\ntarballs\nteardown\ntemplating\ntestcase\ntextarea\nth\nthat'll\nThejaswi\nThis'll\nthreadlocals\nthreadpool\ntimeframe\ntimeline\ntimelines\ntimesaving\ntimestamp\ntimestamped\ntimestamps\ntimezones\ntitlecase\ntmp\ntokenized\ntoolbar\ntoolkits\ntoolset\nTox\ntrac\ntracebacks\ntransactional\nTransifex\nTredinnick\ntriager\ntriagers\ntriaging\ntrigram\ntrigrams\ntuple\ntuples\ntv\ntxt\ntz\nubuntu\nul\numask\nUnaccent\nunannotated\nunapplied\nunapply\nunapplying\nuncategorized\nuncheck\nunclaim\nuncopyable\nunencoded\nunencrypted\nunescape\nunescaped\nunevaluated\nunglamorous\nungrouped\nunhandled\nunharmful\nunhashable\nuninstall\nuninstalling\nunioning\nuniterated\nunlocalize\nunlocalized\nunmaintained\nunmanaged\nunordered\nunparseable\nunparsed\nunpickle\nunpickled\nunpickling\nunpopulated\nunpythonic\nunrendered\nunreproducible\nUnreviewed\nunsanitized\nunselected\nunsets\nunsquashed\nuntar\nuntrusted\nunvalidated\nuppercased\nurl\nurljoins\nurlpatterns\nurls\nusername\nusernames\nutc\nUTF\nutil\nutils\nUvicorn\nuwsgi\nuWSGI\nvalidator\nvalidators\nvalidsite\nVARCHAR\nvariadic\nvendored\nvendorname\nversa\nversioned\nversioning\nvertices\nviewable\nvirtualenv\nvirtualenvs\nvirtualized\nWeblog\nwhitelist\nwhitelisted\nwhitespace\nwhitespaces\nwhizbang\nwiki\nwikipedia\nwildcard\nwildcards\nWillison\nwontfix\nworkflow\nworksforme\nwrappable\nwsgi\nwww\nxe\nxgettext\nXSS\nxxxxx\nZope\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":60,"nodeType":"TextFile","repoName":null,"name":"INSTALL","path":"","text":"Thanks for downloading Django.\n\nTo install it, make sure you have Python 3.6 or greater installed. Then run\nthis command from the command prompt:\n\n    python -m pip install .\n\nFor more detailed instructions, see docs/intro/install.txt.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":61,"nodeType":"TextFile","repoName":null,"name":"Gruntfile.js","path":"","text":"var globalThreshold = 50;  // Global code coverage threshold (as a percentage)\n\nmodule.exports = function(grunt) {\n    grunt.initConfig({\n        qunit: {\n            all: ['js_tests/tests.html']\n        }\n    });\n\n    grunt.loadNpmTasks('grunt-contrib-qunit');\n    grunt.registerTask('test', ['qunit']);\n    grunt.registerTask('default', ['test']);\n};\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":62,"nodeType":"Package","repoName":null,"name":"docs/ref/forms","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":63,"nodeType":"TextFile","repoName":null,"name":"widgets.txt","path":"docs/ref/forms","text":"=======\nWidgets\n=======\n\n.. module:: django.forms.widgets\n   :synopsis: Django's built-in form widgets.\n\n.. currentmodule:: django.forms\n\nA widget is Django's representation of an HTML input element. The widget\nhandles the rendering of the HTML, and the extraction of data from a GET/POST\ndictionary that corresponds to the widget.\n\nThe HTML generated by the built-in widgets uses HTML5 syntax, targeting\n``<!DOCTYPE html>``. For example, it uses boolean attributes such as ``checked``\nrather than the XHTML style of ``checked='checked'``.\n\n.. tip::\n\n    Widgets should not be confused with the :doc:`form fields </ref/forms/fields>`.\n    Form fields deal with the logic of input validation and are used directly\n    in templates. Widgets deal with rendering of HTML form input elements on\n    the web page and extraction of raw submitted data. However, widgets do\n    need to be :ref:`assigned <widget-to-field>` to form fields.\n\n.. _widget-to-field:\n\nSpecifying widgets\n==================\n\nWhenever you specify a field on a form, Django will use a default widget\nthat is appropriate to the type of data that is to be displayed. To find\nwhich widget is used on which field, see the documentation about\n:ref:`built-in-fields`.\n\nHowever, if you want to use a different widget for a field, you can\nuse the :attr:`~Field.widget` argument on the field definition. For example::\n\n    from django import forms\n\n    class CommentForm(forms.Form):\n        name = forms.CharField()\n        url = forms.URLField()\n        comment = forms.CharField(widget=forms.Textarea)\n\nThis would specify a form with a comment that uses a larger :class:`Textarea`\nwidget, rather than the default :class:`TextInput` widget.\n\nSetting arguments for widgets\n=============================\n\nMany widgets have optional extra arguments; they can be set when defining the\nwidget on the field. In the following example, the\n:attr:`~django.forms.SelectDateWidget.years` attribute is set for a\n:class:`~django.forms.SelectDateWidget`::\n\n    from django import forms\n\n    BIRTH_YEAR_CHOICES = ['1980', '1981', '1982']\n    FAVORITE_COLORS_CHOICES = [\n        ('blue', 'Blue'),\n        ('green', 'Green'),\n        ('black', 'Black'),\n    ]\n\n    class SimpleForm(forms.Form):\n        birth_year = forms.DateField(widget=forms.SelectDateWidget(years=BIRTH_YEAR_CHOICES))\n        favorite_colors = forms.MultipleChoiceField(\n            required=False,\n            widget=forms.CheckboxSelectMultiple,\n            choices=FAVORITE_COLORS_CHOICES,\n        )\n\nSee the :ref:`built-in widgets` for more information about which widgets\nare available and which arguments they accept.\n\nWidgets inheriting from the ``Select`` widget\n=============================================\n\nWidgets inheriting from the :class:`Select` widget deal with choices. They\npresent the user with a list of options to choose from. The different widgets\npresent this choice differently; the :class:`Select` widget itself uses a\n``<select>`` HTML list representation, while :class:`RadioSelect` uses radio\nbuttons.\n\n:class:`Select` widgets are used by default on :class:`ChoiceField` fields. The\nchoices displayed on the widget are inherited from the :class:`ChoiceField` and\nchanging :attr:`ChoiceField.choices` will update :attr:`Select.choices`. For\nexample::\n\n    >>> from django import forms\n    >>> CHOICES = [('1', 'First'), ('2', 'Second')]\n    >>> choice_field = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)\n    >>> choice_field.choices\n    [('1', 'First'), ('2', 'Second')]\n    >>> choice_field.widget.choices\n    [('1', 'First'), ('2', 'Second')]\n    >>> choice_field.widget.choices = []\n    >>> choice_field.choices = [('1', 'First and only')]\n    >>> choice_field.widget.choices\n    [('1', 'First and only')]\n\nWidgets which offer a :attr:`~Select.choices` attribute can however be used\nwith fields which are not based on choice -- such as a :class:`CharField` --\nbut it is recommended to use a :class:`ChoiceField`-based field when the\nchoices are inherent to the model and not just the representational widget.\n\nCustomizing widget instances\n============================\n\nWhen Django renders a widget as HTML, it only renders very minimal markup -\nDjango doesn't add class names, or any other widget-specific attributes. This\nmeans, for example, that all :class:`TextInput` widgets will appear the same\non your Web pages.\n\nThere are two ways to customize widgets: :ref:`per widget instance\n<styling-widget-instances>` and :ref:`per widget class <styling-widget-classes>`.\n\n.. _styling-widget-instances:\n\nStyling widget instances\n------------------------\n\nIf you want to make one widget instance look different from another, you will\nneed to specify additional attributes at the time when the widget object is\ninstantiated and assigned to a form field (and perhaps add some rules to your\nCSS files).\n\nFor example, take the following form::\n\n    from django import forms\n\n    class CommentForm(forms.Form):\n        name = forms.CharField()\n        url = forms.URLField()\n        comment = forms.CharField()\n\nThis form will include three default :class:`TextInput` widgets, with default\nrendering -- no CSS class, no extra attributes. This means that the input boxes\nprovided for each widget will be rendered exactly the same::\n\n    >>> f = CommentForm(auto_id=False)\n    >>> f.as_table()\n    <tr><th>Name:</th><td><input type=\"text\" name=\"name\" required></td></tr>\n    <tr><th>Url:</th><td><input type=\"url\" name=\"url\" required></td></tr>\n    <tr><th>Comment:</th><td><input type=\"text\" name=\"comment\" required></td></tr>\n\nOn a real Web page, you probably don't want every widget to look the same. You\nmight want a larger input element for the comment, and you might want the\n'name' widget to have some special CSS class. It is also possible to specify\nthe 'type' attribute to take advantage of the new HTML5 input types.  To do\nthis, you use the :attr:`Widget.attrs` argument when creating the widget::\n\n    class CommentForm(forms.Form):\n        name = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'}))\n        url = forms.URLField()\n        comment = forms.CharField(widget=forms.TextInput(attrs={'size': '40'}))\n\nYou can also modify a widget in the form definition::\n\n    class CommentForm(forms.Form):\n        name = forms.CharField()\n        url = forms.URLField()\n        comment = forms.CharField()\n\n        name.widget.attrs.update({'class': 'special'})\n        comment.widget.attrs.update(size='40')\n\nOr if the field isn't declared directly on the form (such as model form fields),\nyou can use the :attr:`Form.fields` attribute::\n\n    class CommentForm(forms.ModelForm):\n        def __init__(self, *args, **kwargs):\n            super().__init__(*args, **kwargs)\n            self.fields['name'].widget.attrs.update({'class': 'special'})\n            self.fields['comment'].widget.attrs.update(size='40')\n\nDjango will then include the extra attributes in the rendered output:\n\n    >>> f = CommentForm(auto_id=False)\n    >>> f.as_table()\n    <tr><th>Name:</th><td><input type=\"text\" name=\"name\" class=\"special\" required></td></tr>\n    <tr><th>Url:</th><td><input type=\"url\" name=\"url\" required></td></tr>\n    <tr><th>Comment:</th><td><input type=\"text\" name=\"comment\" size=\"40\" required></td></tr>\n\nYou can also set the HTML ``id`` using :attr:`~Widget.attrs`. See\n:attr:`BoundField.id_for_label` for an example.\n\n.. _styling-widget-classes:\n\nStyling widget classes\n----------------------\n\nWith widgets, it is possible to add assets (``css`` and ``javascript``)\nand more deeply customize their appearance and behavior.\n\nIn a nutshell, you will need to subclass the widget and either\n:ref:`define a \"Media\" inner class  <assets-as-a-static-definition>` or\n:ref:`create a \"media\" property <dynamic-property>`.\n\nThese methods involve somewhat advanced Python programming and are described in\ndetail in the :doc:`Form Assets </topics/forms/media>` topic guide.\n\n.. _base-widget-classes:\n\nBase widget classes\n===================\n\nBase widget classes :class:`Widget` and :class:`MultiWidget` are subclassed by\nall the :ref:`built-in widgets <built-in widgets>` and may serve as a\nfoundation for custom widgets.\n\n``Widget``\n----------\n\n.. class:: Widget(attrs=None)\n\n    This abstract class cannot be rendered, but provides the basic attribute\n    :attr:`~Widget.attrs`.  You may also implement or override the\n    :meth:`~Widget.render()` method on custom widgets.\n\n    .. attribute:: Widget.attrs\n\n        A dictionary containing HTML attributes to be set on the rendered\n        widget.\n\n        .. code-block:: pycon\n\n            >>> from django import forms\n            >>> name = forms.TextInput(attrs={'size': 10, 'title': 'Your name'})\n            >>> name.render('name', 'A name')\n            '<input title=\"Your name\" type=\"text\" name=\"name\" value=\"A name\" size=\"10\">'\n\n        If you assign a value of ``True`` or ``False`` to an attribute,\n        it will be rendered as an HTML5 boolean attribute::\n\n            >>> name = forms.TextInput(attrs={'required': True})\n            >>> name.render('name', 'A name')\n            '<input name=\"name\" type=\"text\" value=\"A name\" required>'\n            >>>\n            >>> name = forms.TextInput(attrs={'required': False})\n            >>> name.render('name', 'A name')\n            '<input name=\"name\" type=\"text\" value=\"A name\">'\n\n    .. attribute:: Widget.supports_microseconds\n\n       An attribute that defaults to ``True``. If set to ``False``, the\n       microseconds part of :class:`~datetime.datetime` and\n       :class:`~datetime.time` values will be set to ``0``.\n\n    .. method:: format_value(value)\n\n        Cleans and returns a value for use in the widget template. ``value``\n        isn't guaranteed to be valid input, therefore subclass implementations\n        should program defensively.\n\n    .. method:: get_context(name, value, attrs)\n\n        Returns a dictionary of values to use when rendering the widget\n        template. By default, the dictionary contains a single key,\n        ``'widget'``, which is a dictionary representation of the widget\n        containing the following keys:\n\n        * ``'name'``: The name of the field from the ``name`` argument.\n        * ``'is_hidden'``: A boolean indicating whether or not this widget is\n          hidden.\n        * ``'required'``: A boolean indicating whether or not the field for\n          this widget is required.\n        * ``'value'``: The value as returned by :meth:`format_value`.\n        * ``'attrs'``: HTML attributes to be set on the rendered widget. The\n          combination of the :attr:`attrs` attribute and the ``attrs`` argument.\n        * ``'template_name'``: The value of ``self.template_name``.\n\n        ``Widget`` subclasses can provide custom context values by overriding\n        this method.\n\n    .. method:: id_for_label(id_)\n\n        Returns the HTML ID attribute of this widget for use by a ``<label>``,\n        given the ID of the field. Returns ``None`` if an ID isn't available.\n\n        This hook is necessary because some widgets have multiple HTML\n        elements and, thus, multiple IDs. In that case, this method should\n        return an ID value that corresponds to the first ID in the widget's\n        tags.\n\n    .. method:: render(name, value, attrs=None, renderer=None)\n\n        Renders a widget to HTML using the given renderer. If ``renderer`` is\n        ``None``, the renderer from the :setting:`FORM_RENDERER` setting is\n        used.\n\n    .. method:: value_from_datadict(data, files, name)\n\n        Given a dictionary of data and this widget's name, returns the value\n        of this widget. ``files`` may contain data coming from\n        :attr:`request.FILES <django.http.HttpRequest.FILES>`. Returns ``None``\n        if a value wasn't provided. Note also that ``value_from_datadict`` may\n        be called more than once during handling of form data, so if you\n        customize it and add expensive processing, you should implement some\n        caching mechanism yourself.\n\n    .. method:: value_omitted_from_data(data, files, name)\n\n        Given ``data`` and ``files`` dictionaries and this widget's name,\n        returns whether or not there's data or files for the widget.\n\n        The method's result affects whether or not a field in a model form\n        :ref:`falls back to its default <topics-modelform-save>`.\n\n        Special cases are :class:`~django.forms.CheckboxInput`,\n        :class:`~django.forms.CheckboxSelectMultiple`, and\n        :class:`~django.forms.SelectMultiple`, which always return\n        ``False`` because an unchecked checkbox and unselected\n        ``<select multiple>`` don't appear in the data of an HTML form\n        submission, so it's unknown whether or not the user submitted a value.\n\n    .. method:: use_required_attribute(initial)\n\n        Given a form field's ``initial`` value, returns whether or not the\n        widget can be rendered with the ``required`` HTML attribute. Forms use\n        this method along with :attr:`Field.required\n        <django.forms.Field.required>` and :attr:`Form.use_required_attribute\n        <django.forms.Form.use_required_attribute>` to determine whether or not\n        to display the ``required`` attribute for each field.\n\n        By default, returns ``False`` for hidden widgets and ``True``\n        otherwise. Special cases are :class:`~django.forms.FileInput` and\n        :class:`~django.forms.ClearableFileInput`, which return ``False`` when\n        ``initial`` is set, and :class:`~django.forms.CheckboxSelectMultiple`,\n        which always returns ``False`` because browser validation would require\n        all checkboxes to be checked instead of at least one.\n\n        Override this method in custom widgets that aren't compatible with\n        browser validation. For example, a WSYSIWG text editor widget backed by\n        a hidden ``textarea`` element may want to always return ``False`` to\n        avoid browser validation on the hidden field.\n\n        .. versionchanged:: 3.1\n\n            In older versions, ``True`` was returned for\n            :class:`~django.forms.FileInput` when ``initial`` was set.\n\n``MultiWidget``\n---------------\n\n.. class:: MultiWidget(widgets, attrs=None)\n\n    A widget that is composed of multiple widgets.\n    :class:`~django.forms.MultiWidget` works hand in hand with the\n    :class:`~django.forms.MultiValueField`.\n\n    :class:`MultiWidget` has one required argument:\n\n    .. attribute:: MultiWidget.widgets\n\n        An iterable containing the widgets needed. For example::\n\n            >>> from django.forms import MultiWidget, TextInput\n            >>> widget = MultiWidget(widgets=[TextInput, TextInput])\n            >>> widget.render('name', ['john', 'paul'])\n            '<input type=\"text\" name=\"name_0\" value=\"john\"><input type=\"text\" name=\"name_1\" value=\"paul\">'\n\n        You may provide a dictionary in order to specify custom suffixes for\n        the ``name`` attribute on each subwidget. In this case, for each\n        ``(key, widget)`` pair, the key will be appended to the ``name`` of the\n        widget in order to generate the attribute value. You may provide the\n        empty string (``''``) for a single key, in order to suppress the suffix\n        for one widget. For example::\n\n            >>> widget = MultiWidget(widgets={'': TextInput, 'last': TextInput})\n            >>> widget.render('name', ['john', 'lennon'])\n            '<input type=\"text\" name=\"name\" value=\"john\"><input type=\"text\" name=\"name_last\" value=\"paul\">'\n\n        .. versionchanged::3.1\n\n            Support for using a dictionary was added.\n\n    And one required method:\n\n    .. method:: decompress(value)\n\n        This method takes a single \"compressed\" value from the field and\n        returns a list of \"decompressed\" values. The input value can be\n        assumed valid, but not necessarily non-empty.\n\n        This method **must be implemented** by the subclass, and since the\n        value may be empty, the implementation must be defensive.\n\n        The rationale behind \"decompression\" is that it is necessary to \"split\"\n        the combined value of the form field into the values for each widget.\n\n        An example of this is how :class:`SplitDateTimeWidget` turns a\n        :class:`~datetime.datetime` value into a list with date and time split\n        into two separate values::\n\n            from django.forms import MultiWidget\n\n            class SplitDateTimeWidget(MultiWidget):\n\n                # ...\n\n                def decompress(self, value):\n                    if value:\n                        return [value.date(), value.time()]\n                    return [None, None]\n\n        .. tip::\n\n            Note that :class:`~django.forms.MultiValueField` has a\n            complementary method :meth:`~django.forms.MultiValueField.compress`\n            with the opposite responsibility - to combine cleaned values of\n            all member fields into one.\n\n    It provides some custom context:\n\n    .. method:: get_context(name, value, attrs)\n\n        In addition to the ``'widget'`` key described in\n        :meth:`Widget.get_context`, ``MultiValueWidget`` adds a\n        ``widget['subwidgets']`` key.\n\n        These can be looped over in the widget template:\n\n        .. code-block:: html+django\n\n            {% for subwidget in widget.subwidgets %}\n                {% include subwidget.template_name with widget=subwidget %}\n            {% endfor %}\n\n    Here's an example widget which subclasses :class:`MultiWidget` to display\n    a date with the day, month, and year in different select boxes. This widget\n    is intended to be used with a :class:`~django.forms.DateField` rather than\n    a :class:`~django.forms.MultiValueField`, thus we have implemented\n    :meth:`~Widget.value_from_datadict`::\n\n        from datetime import date\n        from django import forms\n\n        class DateSelectorWidget(forms.MultiWidget):\n            def __init__(self, attrs=None):\n                days = [(day, day) for day in range(1, 32)]\n                months = [(month, month) for month in range(1, 13)]\n                years = [(year, year) for year in [2018, 2019, 2020]]\n                widgets = [\n                    forms.Select(attrs=attrs, choices=days),\n                    forms.Select(attrs=attrs, choices=months),\n                    forms.Select(attrs=attrs, choices=years),\n                ]\n                super().__init__(widgets, attrs)\n\n            def decompress(self, value):\n                if isinstance(value, date):\n                    return [value.day, value.month, value.year]\n                elif isinstance(value, str):\n                    year, month, day = value.split('-')\n                    return [day, month, year]\n                return [None, None, None]\n\n            def value_from_datadict(self, data, files, name):\n                day, month, year = super().value_from_datadict(data, files, name)\n                # DateField expects a single string that it can parse into a date.\n                return '{}-{}-{}'.format(year, month, day)\n\n    The constructor creates several :class:`Select` widgets in a list. The\n    ``super()`` method uses this list to setup the widget.\n\n    The required method :meth:`~MultiWidget.decompress` breaks up a\n    ``datetime.date`` value into the day, month, and year values corresponding\n    to each widget. If an invalid date was selected, such as the non-existent\n    30th February, the :class:`~django.forms.DateField` passes this method a\n    string instead, so that needs parsing. The final ``return`` handles when\n    ``value`` is ``None``, meaning we don't have any defaults for our\n    subwidgets.\n\n    The default implementation of :meth:`~Widget.value_from_datadict` returns a\n    list of values corresponding to each ``Widget``. This is appropriate when\n    using a ``MultiWidget`` with a :class:`~django.forms.MultiValueField`. But\n    since we want to use this widget with a :class:`~django.forms.DateField`,\n    which takes a single value, we have overridden this method. The\n    implementation here combines the data from the subwidgets into a string in\n    the format that :class:`~django.forms.DateField` expects.\n\n.. _built-in widgets:\n\nBuilt-in widgets\n================\n\nDjango provides a representation of all the basic HTML widgets, plus some\ncommonly used groups of widgets in the ``django.forms.widgets`` module,\nincluding :ref:`the input of text <text-widgets>`, :ref:`various checkboxes\nand selectors <selector-widgets>`, :ref:`uploading files <file-upload-widgets>`,\nand :ref:`handling of multi-valued input <composite-widgets>`.\n\n.. _text-widgets:\n\nWidgets handling input of text\n------------------------------\n\nThese widgets make use of the HTML elements ``input`` and ``textarea``.\n\n``TextInput``\n~~~~~~~~~~~~~\n\n.. class:: TextInput\n\n    * ``input_type``: ``'text'``\n    * ``template_name``: ``'django/forms/widgets/text.html'``\n    * Renders as: ``<input type=\"text\" ...>``\n\n``NumberInput``\n~~~~~~~~~~~~~~~\n\n.. class:: NumberInput\n\n    * ``input_type``: ``'number'``\n    * ``template_name``: ``'django/forms/widgets/number.html'``\n    * Renders as: ``<input type=\"number\" ...>``\n\n    Beware that not all browsers support entering localized numbers in\n    ``number`` input types. Django itself avoids using them for fields having\n    their :attr:`~django.forms.Field.localize` property set to ``True``.\n\n``EmailInput``\n~~~~~~~~~~~~~~\n\n.. class:: EmailInput\n\n    * ``input_type``: ``'email'``\n    * ``template_name``: ``'django/forms/widgets/email.html'``\n    * Renders as: ``<input type=\"email\" ...>``\n\n``URLInput``\n~~~~~~~~~~~~\n\n.. class:: URLInput\n\n    * ``input_type``: ``'url'``\n    * ``template_name``: ``'django/forms/widgets/url.html'``\n    * Renders as: ``<input type=\"url\" ...>``\n\n``PasswordInput``\n~~~~~~~~~~~~~~~~~\n\n.. class:: PasswordInput\n\n    * ``input_type``: ``'password'``\n    * ``template_name``: ``'django/forms/widgets/password.html'``\n    * Renders as: ``<input type=\"password\" ...>``\n\n    Takes one optional argument:\n\n    .. attribute:: PasswordInput.render_value\n\n        Determines whether the widget will have a value filled in when the\n        form is re-displayed after a validation error (default is ``False``).\n\n``HiddenInput``\n~~~~~~~~~~~~~~~\n\n.. class:: HiddenInput\n\n    * ``input_type``: ``'hidden'``\n    * ``template_name``: ``'django/forms/widgets/hidden.html'``\n    * Renders as: ``<input type=\"hidden\" ...>``\n\n    Note that there also is a :class:`MultipleHiddenInput` widget that\n    encapsulates a set of hidden input elements.\n\n``DateInput``\n~~~~~~~~~~~~~\n\n.. class:: DateInput\n\n    * ``input_type``: ``'text'``\n    * ``template_name``: ``'django/forms/widgets/date.html'``\n    * Renders as: ``<input type=\"text\" ...>``\n\n    Takes same arguments as :class:`TextInput`, with one more optional argument:\n\n    .. attribute:: DateInput.format\n\n        The format in which this field's initial value will be displayed.\n\n    If no ``format`` argument is provided, the default format is the first\n    format found in :setting:`DATE_INPUT_FORMATS` and respects\n    :doc:`/topics/i18n/formatting`.\n\n``DateTimeInput``\n~~~~~~~~~~~~~~~~~\n\n.. class:: DateTimeInput\n\n    * ``input_type``: ``'text'``\n    * ``template_name``: ``'django/forms/widgets/datetime.html'``\n    * Renders as: ``<input type=\"text\" ...>``\n\n    Takes same arguments as :class:`TextInput`, with one more optional argument:\n\n    .. attribute:: DateTimeInput.format\n\n        The format in which this field's initial value will be displayed.\n\n    If no ``format`` argument is provided, the default format is the first\n    format found in :setting:`DATETIME_INPUT_FORMATS` and respects\n    :doc:`/topics/i18n/formatting`.\n\n    By default, the microseconds part of the time value is always set to ``0``.\n    If microseconds are required, use a subclass with the\n    :attr:`~Widget.supports_microseconds` attribute set to ``True``.\n\n``TimeInput``\n~~~~~~~~~~~~~\n\n.. class:: TimeInput\n\n    * ``input_type``: ``'text'``\n    * ``template_name``: ``'django/forms/widgets/time.html'``\n    * Renders as: ``<input type=\"text\" ...>``\n\n    Takes same arguments as :class:`TextInput`, with one more optional argument:\n\n    .. attribute:: TimeInput.format\n\n        The format in which this field's initial value will be displayed.\n\n    If no ``format`` argument is provided, the default format is the first\n    format found in :setting:`TIME_INPUT_FORMATS` and respects\n    :doc:`/topics/i18n/formatting`.\n\n    For the treatment of microseconds, see :class:`DateTimeInput`.\n\n``Textarea``\n~~~~~~~~~~~~\n\n.. class:: Textarea\n\n    * ``template_name``: ``'django/forms/widgets/textarea.html'``\n    * Renders as: ``<textarea>...</textarea>``\n\n.. _selector-widgets:\n\nSelector and checkbox widgets\n-----------------------------\n\nThese widgets make use of the HTML elements ``<select>``,\n``<input type=\"checkbox\">``, and ``<input type=\"radio\">``.\n\nWidgets that render multiple choices have an ``option_template_name`` attribute\nthat specifies the template used to render each choice. For example, for the\n:class:`Select` widget, ``select_option.html`` renders the ``<option>`` for a\n``<select>``.\n\n``CheckboxInput``\n~~~~~~~~~~~~~~~~~\n\n.. class:: CheckboxInput\n\n    * ``input_type``: ``'checkbox'``\n    * ``template_name``: ``'django/forms/widgets/checkbox.html'``\n    * Renders as: ``<input type=\"checkbox\" ...>``\n\n    Takes one optional argument:\n\n    .. attribute:: CheckboxInput.check_test\n\n        A callable that takes the value of the ``CheckboxInput`` and returns\n        ``True`` if the checkbox should be checked for that value.\n\n``Select``\n~~~~~~~~~~\n\n.. class:: Select\n\n    * ``template_name``: ``'django/forms/widgets/select.html'``\n    * ``option_template_name``: ``'django/forms/widgets/select_option.html'``\n    * Renders as: ``<select><option ...>...</select>``\n\n    .. attribute:: Select.choices\n\n        This attribute is optional when the form field does not have a\n        ``choices`` attribute. If it does, it will override anything you set\n        here when the attribute is updated on the :class:`Field`.\n\n``NullBooleanSelect``\n~~~~~~~~~~~~~~~~~~~~~\n\n.. class:: NullBooleanSelect\n\n    * ``template_name``: ``'django/forms/widgets/select.html'``\n    * ``option_template_name``: ``'django/forms/widgets/select_option.html'``\n\n    Select widget with options 'Unknown', 'Yes' and 'No'\n\n``SelectMultiple``\n~~~~~~~~~~~~~~~~~~\n\n.. class:: SelectMultiple\n\n    * ``template_name``: ``'django/forms/widgets/select.html'``\n    * ``option_template_name``: ``'django/forms/widgets/select_option.html'``\n\n    Similar to :class:`Select`, but allows multiple selection:\n    ``<select multiple>...</select>``\n\n``RadioSelect``\n~~~~~~~~~~~~~~~\n\n.. class:: RadioSelect\n\n    * ``template_name``: ``'django/forms/widgets/radio.html'``\n    * ``option_template_name``: ``'django/forms/widgets/radio_option.html'``\n\n    Similar to :class:`Select`, but rendered as a list of radio buttons within\n    ``<li>`` tags:\n\n    .. code-block:: html\n\n        <ul>\n          <li><input type=\"radio\" name=\"...\"></li>\n          ...\n        </ul>\n\n    For more granular control over the generated markup, you can loop over the\n    radio buttons in the template. Assuming a form ``myform`` with a field\n    ``beatles`` that uses a ``RadioSelect`` as its widget:\n\n    .. code-block:: html+django\n\n        {% for radio in myform.beatles %}\n        <div class=\"myradio\">\n            {{ radio }}\n        </div>\n        {% endfor %}\n\n    This would generate the following HTML:\n\n    .. code-block:: html\n\n        <div class=\"myradio\">\n            <label for=\"id_beatles_0\"><input id=\"id_beatles_0\" name=\"beatles\" type=\"radio\" value=\"john\" required> John</label>\n        </div>\n        <div class=\"myradio\">\n            <label for=\"id_beatles_1\"><input id=\"id_beatles_1\" name=\"beatles\" type=\"radio\" value=\"paul\" required> Paul</label>\n        </div>\n        <div class=\"myradio\">\n            <label for=\"id_beatles_2\"><input id=\"id_beatles_2\" name=\"beatles\" type=\"radio\" value=\"george\" required> George</label>\n        </div>\n        <div class=\"myradio\">\n            <label for=\"id_beatles_3\"><input id=\"id_beatles_3\" name=\"beatles\" type=\"radio\" value=\"ringo\" required> Ringo</label>\n        </div>\n\n    That included the ``<label>`` tags. To get more granular, you can use each\n    radio button's ``tag``, ``choice_label`` and ``id_for_label`` attributes.\n    For example, this template...\n\n    .. code-block:: html+django\n\n        {% for radio in myform.beatles %}\n            <label for=\"{{ radio.id_for_label }}\">\n                {{ radio.choice_label }}\n                <span class=\"radio\">{{ radio.tag }}</span>\n            </label>\n        {% endfor %}\n\n    ...will result in the following HTML:\n\n    .. code-block:: html\n\n        <label for=\"id_beatles_0\">\n            John\n            <span class=\"radio\"><input id=\"id_beatles_0\" name=\"beatles\" type=\"radio\" value=\"john\" required></span>\n        </label>\n\n        <label for=\"id_beatles_1\">\n            Paul\n            <span class=\"radio\"><input id=\"id_beatles_1\" name=\"beatles\" type=\"radio\" value=\"paul\" required></span>\n        </label>\n\n        <label for=\"id_beatles_2\">\n            George\n            <span class=\"radio\"><input id=\"id_beatles_2\" name=\"beatles\" type=\"radio\" value=\"george\" required></span>\n        </label>\n\n        <label for=\"id_beatles_3\">\n            Ringo\n            <span class=\"radio\"><input id=\"id_beatles_3\" name=\"beatles\" type=\"radio\" value=\"ringo\" required></span>\n        </label>\n\n    If you decide not to loop over the radio buttons -- e.g., if your template\n    includes ``{{ myform.beatles }}`` -- they'll be output in a ``<ul>`` with\n    ``<li>`` tags, as above.\n\n    The outer ``<ul>`` container receives the ``id`` attribute of the widget,\n    if defined, or :attr:`BoundField.auto_id` otherwise.\n\n    When looping over the radio buttons, the ``label`` and ``input`` tags include\n    ``for`` and ``id`` attributes, respectively. Each radio button has an\n    ``id_for_label`` attribute to output the element's ID.\n\n``CheckboxSelectMultiple``\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. class:: CheckboxSelectMultiple\n\n    * ``template_name``: ``'django/forms/widgets/checkbox_select.html'``\n    * ``option_template_name``: ``'django/forms/widgets/checkbox_option.html'``\n\n    Similar to :class:`SelectMultiple`, but rendered as a list of checkboxes:\n\n    .. code-block:: html\n\n        <ul>\n          <li><input type=\"checkbox\" name=\"...\" ></li>\n          ...\n        </ul>\n\n    The outer ``<ul>`` container receives the ``id`` attribute of the widget,\n    if defined, or :attr:`BoundField.auto_id` otherwise.\n\nLike :class:`RadioSelect`, you can loop over the individual checkboxes for the\nwidget's choices. Unlike :class:`RadioSelect`, the checkboxes won't include the\n``required`` HTML attribute if the field is required because browser validation\nwould require all checkboxes to be checked instead of at least one.\n\nWhen looping over the checkboxes, the ``label`` and ``input`` tags include\n``for`` and ``id`` attributes, respectively. Each checkbox has an\n``id_for_label`` attribute to output the element's ID.\n\n.. _file-upload-widgets:\n\nFile upload widgets\n-------------------\n\n``FileInput``\n~~~~~~~~~~~~~\n\n.. class:: FileInput\n\n    * ``template_name``: ``'django/forms/widgets/file.html'``\n    * Renders as: ``<input type=\"file\" ...>``\n\n``ClearableFileInput``\n~~~~~~~~~~~~~~~~~~~~~~\n\n.. class:: ClearableFileInput\n\n    * ``template_name``: ``'django/forms/widgets/clearable_file_input.html'``\n    * Renders as: ``<input type=\"file\" ...>`` with an additional checkbox\n      input to clear the field's value, if the field is not required and has\n      initial data.\n\n.. _composite-widgets:\n\nComposite widgets\n-----------------\n\n``MultipleHiddenInput``\n~~~~~~~~~~~~~~~~~~~~~~~\n\n.. class:: MultipleHiddenInput\n\n    * ``template_name``: ``'django/forms/widgets/multiple_hidden.html'``\n    * Renders as: multiple ``<input type=\"hidden\" ...>`` tags\n\n    A widget that handles multiple hidden widgets for fields that have a list\n    of values.\n\n``SplitDateTimeWidget``\n~~~~~~~~~~~~~~~~~~~~~~~\n\n.. class:: SplitDateTimeWidget\n\n    * ``template_name``: ``'django/forms/widgets/splitdatetime.html'``\n\n    Wrapper (using :class:`MultiWidget`) around two widgets: :class:`DateInput`\n    for the date, and :class:`TimeInput` for the time. Must be used with\n    :class:`SplitDateTimeField` rather than :class:`DateTimeField`.\n\n    ``SplitDateTimeWidget`` has several optional arguments:\n\n    .. attribute:: SplitDateTimeWidget.date_format\n\n        Similar to :attr:`DateInput.format`\n\n    .. attribute:: SplitDateTimeWidget.time_format\n\n        Similar to :attr:`TimeInput.format`\n\n    .. attribute:: SplitDateTimeWidget.date_attrs\n    .. attribute:: SplitDateTimeWidget.time_attrs\n\n        Similar to :attr:`Widget.attrs`. A dictionary containing HTML\n        attributes to be set on the rendered :class:`DateInput` and\n        :class:`TimeInput` widgets, respectively. If these attributes aren't\n        set, :attr:`Widget.attrs` is used instead.\n\n``SplitHiddenDateTimeWidget``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. class:: SplitHiddenDateTimeWidget\n\n    * ``template_name``: ``'django/forms/widgets/splithiddendatetime.html'``\n\n    Similar to :class:`SplitDateTimeWidget`, but uses :class:`HiddenInput` for\n    both date and time.\n\n``SelectDateWidget``\n~~~~~~~~~~~~~~~~~~~~\n\n.. class:: SelectDateWidget\n\n    * ``template_name``: ``'django/forms/widgets/select_date.html'``\n\n    Wrapper around three :class:`~django.forms.Select` widgets: one each for\n    month, day, and year.\n\n    Takes several optional arguments:\n\n    .. attribute:: SelectDateWidget.years\n\n        An optional list/tuple of years to use in the \"year\" select box.\n        The default is a list containing the current year and the next 9 years.\n\n    .. attribute:: SelectDateWidget.months\n\n        An optional dict of months to use in the \"months\" select box.\n\n        The keys of the dict correspond to the month number (1-indexed) and\n        the values are the displayed months::\n\n            MONTHS = {\n                1:_('jan'), 2:_('feb'), 3:_('mar'), 4:_('apr'),\n                5:_('may'), 6:_('jun'), 7:_('jul'), 8:_('aug'),\n                9:_('sep'), 10:_('oct'), 11:_('nov'), 12:_('dec')\n            }\n\n    .. attribute:: SelectDateWidget.empty_label\n\n        If the :class:`~django.forms.DateField` is not required,\n        :class:`SelectDateWidget` will have an empty choice at the top of the\n        list (which is ``---`` by default). You can change the text of this\n        label with the ``empty_label`` attribute. ``empty_label`` can be a\n        ``string``, ``list``, or ``tuple``. When a string is used, all select\n        boxes will each have an empty choice with this label. If ``empty_label``\n        is a ``list`` or ``tuple`` of 3 string elements, the select boxes will\n        have their own custom label. The labels should be in this order\n        ``('year_label', 'month_label', 'day_label')``.\n\n        .. code-block:: python\n\n            # A custom empty label with string\n            field1 = forms.DateField(widget=SelectDateWidget(empty_label=\"Nothing\"))\n\n            # A custom empty label with tuple\n            field1 = forms.DateField(\n                widget=SelectDateWidget(\n                    empty_label=(\"Choose Year\", \"Choose Month\", \"Choose Day\"),\n                ),\n            )\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":64,"nodeType":"TextFile","repoName":null,"name":"formsets.txt","path":"docs/ref/forms","text":"=================\nFormset Functions\n=================\n\nFormset API reference. For introductory material about formsets, see the\n:doc:`/topics/forms/formsets` topic guide.\n\n.. module:: django.forms.formsets\n   :synopsis: Django's functions for building formsets.\n\n``formset_factory``\n===================\n\n.. function:: formset_factory(form, formset=BaseFormSet, extra=1, can_order=False, can_delete=False, max_num=None, validate_max=False, min_num=None, validate_min=False)\n\n    Returns a ``FormSet`` class for the given ``form`` class.\n\n    See :doc:`formsets </topics/forms/formsets>` for example usage.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":65,"nodeType":"TextFile","repoName":null,"name":"api.txt","path":"docs/ref/forms","text":"=============\nThe Forms API\n=============\n\n.. module:: django.forms\n\n.. admonition:: About this document\n\n    This document covers the gritty details of Django's forms API. You should\n    read the :doc:`introduction to working with forms </topics/forms/index>`\n    first.\n\n.. _ref-forms-api-bound-unbound:\n\nBound and unbound forms\n=======================\n\nA :class:`Form` instance is either **bound** to a set of data, or **unbound**.\n\n* If it's **bound** to a set of data, it's capable of validating that data\n  and rendering the form as HTML with the data displayed in the HTML.\n\n* If it's **unbound**, it cannot do validation (because there's no data to\n  validate!), but it can still render the blank form as HTML.\n\n.. class:: Form\n\nTo create an unbound :class:`Form` instance, instantiate the class::\n\n    >>> f = ContactForm()\n\nTo bind data to a form, pass the data as a dictionary as the first parameter to\nyour :class:`Form` class constructor::\n\n    >>> data = {'subject': 'hello',\n    ...         'message': 'Hi there',\n    ...         'sender': 'foo@example.com',\n    ...         'cc_myself': True}\n    >>> f = ContactForm(data)\n\nIn this dictionary, the keys are the field names, which correspond to the\nattributes in your :class:`Form` class. The values are the data you're trying to\nvalidate. These will usually be strings, but there's no requirement that they be\nstrings; the type of data you pass depends on the :class:`Field`, as we'll see\nin a moment.\n\n.. attribute:: Form.is_bound\n\nIf you need to distinguish between bound and unbound form instances at runtime,\ncheck the value of the form's :attr:`~Form.is_bound` attribute::\n\n    >>> f = ContactForm()\n    >>> f.is_bound\n    False\n    >>> f = ContactForm({'subject': 'hello'})\n    >>> f.is_bound\n    True\n\nNote that passing an empty dictionary creates a *bound* form with empty data::\n\n    >>> f = ContactForm({})\n    >>> f.is_bound\n    True\n\nIf you have a bound :class:`Form` instance and want to change the data somehow,\nor if you want to bind an unbound :class:`Form` instance to some data, create\nanother :class:`Form` instance. There is no way to change data in a\n:class:`Form` instance. Once a :class:`Form` instance has been created, you\nshould consider its data immutable, whether it has data or not.\n\nUsing forms to validate data\n============================\n\n.. method:: Form.clean()\n\nImplement a ``clean()`` method on your ``Form`` when you must add custom\nvalidation for fields that are interdependent. See\n:ref:`validating-fields-with-clean` for example usage.\n\n.. method:: Form.is_valid()\n\nThe primary task of a :class:`Form` object is to validate data. With a bound\n:class:`Form` instance, call the :meth:`~Form.is_valid` method to run validation\nand return a boolean designating whether the data was valid::\n\n    >>> data = {'subject': 'hello',\n    ...         'message': 'Hi there',\n    ...         'sender': 'foo@example.com',\n    ...         'cc_myself': True}\n    >>> f = ContactForm(data)\n    >>> f.is_valid()\n    True\n\nLet's try with some invalid data. In this case, ``subject`` is blank (an error,\nbecause all fields are required by default) and ``sender`` is not a valid\nemail address::\n\n    >>> data = {'subject': '',\n    ...         'message': 'Hi there',\n    ...         'sender': 'invalid email address',\n    ...         'cc_myself': True}\n    >>> f = ContactForm(data)\n    >>> f.is_valid()\n    False\n\n.. attribute:: Form.errors\n\nAccess the :attr:`~Form.errors` attribute to get a dictionary of error\nmessages::\n\n    >>> f.errors\n    {'sender': ['Enter a valid email address.'], 'subject': ['This field is required.']}\n\nIn this dictionary, the keys are the field names, and the values are lists of\nstrings representing the error messages. The error messages are stored\nin lists because a field can have multiple error messages.\n\nYou can access :attr:`~Form.errors` without having to call\n:meth:`~Form.is_valid` first. The form's data will be validated the first time\neither you call :meth:`~Form.is_valid` or access :attr:`~Form.errors`.\n\nThe validation routines will only get called once, regardless of how many times\nyou access :attr:`~Form.errors` or call :meth:`~Form.is_valid`. This means that\nif validation has side effects, those side effects will only be triggered once.\n\n.. method:: Form.errors.as_data()\n\nReturns a ``dict`` that maps fields to their original ``ValidationError``\ninstances.\n\n    >>> f.errors.as_data()\n    {'sender': [ValidationError(['Enter a valid email address.'])],\n    'subject': [ValidationError(['This field is required.'])]}\n\nUse this method anytime you need to identify an error by its ``code``. This\nenables things like rewriting the error's message or writing custom logic in a\nview when a given error is present. It can also be used to serialize the errors\nin a custom format (e.g. XML); for instance, :meth:`~Form.errors.as_json()`\nrelies on ``as_data()``.\n\nThe need for the ``as_data()`` method is due to backwards compatibility.\nPreviously ``ValidationError`` instances were lost as soon as their\n**rendered** error messages were added to the ``Form.errors`` dictionary.\nIdeally ``Form.errors`` would have stored ``ValidationError`` instances\nand methods with an ``as_`` prefix could render them, but it had to be done\nthe other way around in order not to break code that expects rendered error\nmessages in ``Form.errors``.\n\n.. method:: Form.errors.as_json(escape_html=False)\n\nReturns the errors serialized as JSON.\n\n    >>> f.errors.as_json()\n    {\"sender\": [{\"message\": \"Enter a valid email address.\", \"code\": \"invalid\"}],\n    \"subject\": [{\"message\": \"This field is required.\", \"code\": \"required\"}]}\n\nBy default, ``as_json()`` does not escape its output. If you are using it for\nsomething like AJAX requests to a form view where the client interprets the\nresponse and inserts errors into the page, you'll want to be sure to escape the\nresults on the client-side to avoid the possibility of a cross-site scripting\nattack. You can do this in JavaScript with ``element.textContent = errorText``\nor with jQuery's ``$(el).text(errorText)`` (rather than its ``.html()``\nfunction).\n\nIf for some reason you don't want to use client-side escaping, you can also\nset ``escape_html=True`` and error messages will be escaped so you can use them\ndirectly in HTML.\n\n.. method:: Form.errors.get_json_data(escape_html=False)\n\nReturns the errors as a dictionary suitable for serializing to JSON.\n:meth:`Form.errors.as_json()` returns serialized JSON, while this returns the\nerror data before it's serialized.\n\nThe ``escape_html`` parameter behaves as described in\n:meth:`Form.errors.as_json()`.\n\n.. method:: Form.add_error(field, error)\n\nThis method allows adding errors to specific fields from within the\n``Form.clean()`` method, or from outside the form altogether; for instance\nfrom a view.\n\nThe ``field`` argument is the name of the field to which the errors\nshould be added. If its value is ``None`` the error will be treated as\na non-field error as returned by :meth:`Form.non_field_errors()\n<django.forms.Form.non_field_errors>`.\n\nThe ``error`` argument can be a string, or preferably an instance of\n``ValidationError``. See :ref:`raising-validation-error` for best practices\nwhen defining form errors.\n\nNote that ``Form.add_error()`` automatically removes the relevant field from\n``cleaned_data``.\n\n.. method:: Form.has_error(field, code=None)\n\nThis method returns a boolean designating whether a field has an error with\na specific error ``code``. If ``code`` is ``None``, it will return ``True``\nif the field contains any errors at all.\n\nTo check for non-field errors use\n:data:`~django.core.exceptions.NON_FIELD_ERRORS` as the ``field`` parameter.\n\n.. method:: Form.non_field_errors()\n\nThis method returns the list of errors from :attr:`Form.errors\n<django.forms.Form.errors>`  that aren't associated with a particular field.\nThis includes ``ValidationError``\\s that are raised in :meth:`Form.clean()\n<django.forms.Form.clean>` and errors added using :meth:`Form.add_error(None,\n\"...\") <django.forms.Form.add_error>`.\n\nBehavior of unbound forms\n-------------------------\n\nIt's meaningless to validate a form with no data, but, for the record, here's\nwhat happens with unbound forms::\n\n    >>> f = ContactForm()\n    >>> f.is_valid()\n    False\n    >>> f.errors\n    {}\n\nDynamic initial values\n======================\n\n.. attribute:: Form.initial\n\nUse :attr:`~Form.initial` to declare the initial value of form fields at\nruntime. For example, you might want to fill in a ``username`` field with the\nusername of the current session.\n\nTo accomplish this, use the :attr:`~Form.initial` argument to a :class:`Form`.\nThis argument, if given, should be a dictionary mapping field names to initial\nvalues. Only include the fields for which you're specifying an initial value;\nit's not necessary to include every field in your form. For example::\n\n    >>> f = ContactForm(initial={'subject': 'Hi there!'})\n\nThese values are only displayed for unbound forms, and they're not used as\nfallback values if a particular value isn't provided.\n\nIf a :class:`~django.forms.Field` defines :attr:`~Field.initial` *and* you\ninclude :attr:`~Form.initial` when instantiating the ``Form``, then the latter\n``initial`` will have precedence. In this example, ``initial`` is provided both\nat the field level and at the form instance level, and the latter gets\nprecedence::\n\n    >>> from django import forms\n    >>> class CommentForm(forms.Form):\n    ...     name = forms.CharField(initial='class')\n    ...     url = forms.URLField()\n    ...     comment = forms.CharField()\n    >>> f = CommentForm(initial={'name': 'instance'}, auto_id=False)\n    >>> print(f)\n    <tr><th>Name:</th><td><input type=\"text\" name=\"name\" value=\"instance\" required></td></tr>\n    <tr><th>Url:</th><td><input type=\"url\" name=\"url\" required></td></tr>\n    <tr><th>Comment:</th><td><input type=\"text\" name=\"comment\" required></td></tr>\n\n.. method:: Form.get_initial_for_field(field, field_name)\n\nUse :meth:`~Form.get_initial_for_field()` to retrieve initial data for a form\nfield. It retrieves data from :attr:`Form.initial` and :attr:`Field.initial`,\nin that order, and evaluates any callable initial values.\n\nChecking which form data has changed\n====================================\n\n.. method:: Form.has_changed()\n\nUse the ``has_changed()`` method on your ``Form`` when you need to check if the\nform data has been changed from the initial data.\n\n    >>> data = {'subject': 'hello',\n    ...         'message': 'Hi there',\n    ...         'sender': 'foo@example.com',\n    ...         'cc_myself': True}\n    >>> f = ContactForm(data, initial=data)\n    >>> f.has_changed()\n    False\n\nWhen the form is submitted, we reconstruct it and provide the original data\nso that the comparison can be done:\n\n    >>> f = ContactForm(request.POST, initial=data)\n    >>> f.has_changed()\n\n``has_changed()`` will be ``True`` if the data from ``request.POST`` differs\nfrom what was provided in :attr:`~Form.initial` or ``False`` otherwise. The\nresult is computed by calling :meth:`Field.has_changed` for each field in the\nform.\n\n.. attribute:: Form.changed_data\n\nThe ``changed_data`` attribute returns a list of the names of the fields whose\nvalues in the form's bound data (usually ``request.POST``) differ from what was\nprovided in :attr:`~Form.initial`. It returns an empty list if no data differs.\n\n    >>> f = ContactForm(request.POST, initial=data)\n    >>> if f.has_changed():\n    ...     print(\"The following fields changed: %s\" % \", \".join(f.changed_data))\n    >>> f.changed_data\n    ['subject', 'message']\n\nAccessing the fields from the form\n==================================\n\n.. attribute:: Form.fields\n\nYou can access the fields of :class:`Form` instance from its ``fields``\nattribute::\n\n    >>> for row in f.fields.values(): print(row)\n    ...\n    <django.forms.fields.CharField object at 0x7ffaac632510>\n    <django.forms.fields.URLField object at 0x7ffaac632f90>\n    <django.forms.fields.CharField object at 0x7ffaac3aa050>\n    >>> f.fields['name']\n    <django.forms.fields.CharField object at 0x7ffaac6324d0>\n\nYou can alter the field of :class:`Form` instance to change the way it is\npresented in the form::\n\n    >>> f.as_table().split('\\n')[0]\n    '<tr><th>Name:</th><td><input name=\"name\" type=\"text\" value=\"instance\" required></td></tr>'\n    >>> f.fields['name'].label = \"Username\"\n    >>> f.as_table().split('\\n')[0]\n    '<tr><th>Username:</th><td><input name=\"name\" type=\"text\" value=\"instance\" required></td></tr>'\n\nBeware not to alter the ``base_fields`` attribute because this modification\nwill influence all subsequent ``ContactForm`` instances within the same Python\nprocess::\n\n    >>> f.base_fields['name'].label = \"Username\"\n    >>> another_f = CommentForm(auto_id=False)\n    >>> another_f.as_table().split('\\n')[0]\n    '<tr><th>Username:</th><td><input name=\"name\" type=\"text\" value=\"class\" required></td></tr>'\n\nAccessing \"clean\" data\n======================\n\n.. attribute:: Form.cleaned_data\n\nEach field in a :class:`Form` class is responsible not only for validating\ndata, but also for \"cleaning\" it -- normalizing it to a consistent format. This\nis a nice feature, because it allows data for a particular field to be input in\na variety of ways, always resulting in consistent output.\n\nFor example, :class:`~django.forms.DateField` normalizes input into a\nPython ``datetime.date`` object. Regardless of whether you pass it a string in\nthe format ``'1994-07-15'``, a ``datetime.date`` object, or a number of other\nformats, ``DateField`` will always normalize it to a ``datetime.date`` object\nas long as it's valid.\n\nOnce you've created a :class:`~Form` instance with a set of data and validated\nit, you can access the clean data via its ``cleaned_data`` attribute::\n\n    >>> data = {'subject': 'hello',\n    ...         'message': 'Hi there',\n    ...         'sender': 'foo@example.com',\n    ...         'cc_myself': True}\n    >>> f = ContactForm(data)\n    >>> f.is_valid()\n    True\n    >>> f.cleaned_data\n    {'cc_myself': True, 'message': 'Hi there', 'sender': 'foo@example.com', 'subject': 'hello'}\n\nNote that any text-based field -- such as ``CharField`` or ``EmailField`` --\nalways cleans the input into a string. We'll cover the encoding implications\nlater in this document.\n\nIf your data does *not* validate, the ``cleaned_data`` dictionary contains\nonly the valid fields::\n\n    >>> data = {'subject': '',\n    ...         'message': 'Hi there',\n    ...         'sender': 'invalid email address',\n    ...         'cc_myself': True}\n    >>> f = ContactForm(data)\n    >>> f.is_valid()\n    False\n    >>> f.cleaned_data\n    {'cc_myself': True, 'message': 'Hi there'}\n\n``cleaned_data`` will always *only* contain a key for fields defined in the\n``Form``, even if you pass extra data when you define the ``Form``. In this\nexample, we pass a bunch of extra fields to the ``ContactForm`` constructor,\nbut ``cleaned_data`` contains only the form's fields::\n\n    >>> data = {'subject': 'hello',\n    ...         'message': 'Hi there',\n    ...         'sender': 'foo@example.com',\n    ...         'cc_myself': True,\n    ...         'extra_field_1': 'foo',\n    ...         'extra_field_2': 'bar',\n    ...         'extra_field_3': 'baz'}\n    >>> f = ContactForm(data)\n    >>> f.is_valid()\n    True\n    >>> f.cleaned_data # Doesn't contain extra_field_1, etc.\n    {'cc_myself': True, 'message': 'Hi there', 'sender': 'foo@example.com', 'subject': 'hello'}\n\nWhen the ``Form`` is valid, ``cleaned_data`` will include a key and value for\n*all* its fields, even if the data didn't include a value for some optional\nfields. In this example, the data dictionary doesn't include a value for the\n``nick_name`` field, but ``cleaned_data`` includes it, with an empty value::\n\n    >>> from django import forms\n    >>> class OptionalPersonForm(forms.Form):\n    ...     first_name = forms.CharField()\n    ...     last_name = forms.CharField()\n    ...     nick_name = forms.CharField(required=False)\n    >>> data = {'first_name': 'John', 'last_name': 'Lennon'}\n    >>> f = OptionalPersonForm(data)\n    >>> f.is_valid()\n    True\n    >>> f.cleaned_data\n    {'nick_name': '', 'first_name': 'John', 'last_name': 'Lennon'}\n\nIn this above example, the ``cleaned_data`` value for ``nick_name`` is set to an\nempty string, because ``nick_name`` is ``CharField``, and ``CharField``\\s treat\nempty values as an empty string. Each field type knows what its \"blank\" value\nis -- e.g., for ``DateField``, it's ``None`` instead of the empty string. For\nfull details on each field's behavior in this case, see the \"Empty value\" note\nfor each field in the \"Built-in ``Field`` classes\" section below.\n\nYou can write code to perform validation for particular form fields (based on\ntheir name) or for the form as a whole (considering combinations of various\nfields). More information about this is in :doc:`/ref/forms/validation`.\n\n.. _ref-forms-api-outputting-html:\n\nOutputting forms as HTML\n========================\n\nThe second task of a ``Form`` object is to render itself as HTML. To do so,\n``print`` it::\n\n    >>> f = ContactForm()\n    >>> print(f)\n    <tr><th><label for=\"id_subject\">Subject:</label></th><td><input id=\"id_subject\" type=\"text\" name=\"subject\" maxlength=\"100\" required></td></tr>\n    <tr><th><label for=\"id_message\">Message:</label></th><td><input type=\"text\" name=\"message\" id=\"id_message\" required></td></tr>\n    <tr><th><label for=\"id_sender\">Sender:</label></th><td><input type=\"email\" name=\"sender\" id=\"id_sender\" required></td></tr>\n    <tr><th><label for=\"id_cc_myself\">Cc myself:</label></th><td><input type=\"checkbox\" name=\"cc_myself\" id=\"id_cc_myself\"></td></tr>\n\nIf the form is bound to data, the HTML output will include that data\nappropriately. For example, if a field is represented by an\n``<input type=\"text\">``, the data will be in the ``value`` attribute. If a\nfield is represented by an ``<input type=\"checkbox\">``, then that HTML will\ninclude ``checked`` if appropriate::\n\n    >>> data = {'subject': 'hello',\n    ...         'message': 'Hi there',\n    ...         'sender': 'foo@example.com',\n    ...         'cc_myself': True}\n    >>> f = ContactForm(data)\n    >>> print(f)\n    <tr><th><label for=\"id_subject\">Subject:</label></th><td><input id=\"id_subject\" type=\"text\" name=\"subject\" maxlength=\"100\" value=\"hello\" required></td></tr>\n    <tr><th><label for=\"id_message\">Message:</label></th><td><input type=\"text\" name=\"message\" id=\"id_message\" value=\"Hi there\" required></td></tr>\n    <tr><th><label for=\"id_sender\">Sender:</label></th><td><input type=\"email\" name=\"sender\" id=\"id_sender\" value=\"foo@example.com\" required></td></tr>\n    <tr><th><label for=\"id_cc_myself\">Cc myself:</label></th><td><input type=\"checkbox\" name=\"cc_myself\" id=\"id_cc_myself\" checked></td></tr>\n\nThis default output is a two-column HTML table, with a ``<tr>`` for each field.\nNotice the following:\n\n* For flexibility, the output does *not* include the ``<table>`` and\n  ``</table>`` tags, nor does it include the ``<form>`` and ``</form>``\n  tags or an ``<input type=\"submit\">`` tag. It's your job to do that.\n\n* Each field type has a default HTML representation. ``CharField`` is\n  represented by an ``<input type=\"text\">`` and ``EmailField`` by an\n  ``<input type=\"email\">``. ``BooleanField(null=False)`` is represented by an\n  ``<input type=\"checkbox\">``. Note these are merely sensible defaults; you can\n  specify which HTML to use for a given field by using widgets, which we'll\n  explain shortly.\n\n* The HTML ``name`` for each tag is taken directly from its attribute name\n  in the ``ContactForm`` class.\n\n* The text label for each field -- e.g. ``'Subject:'``, ``'Message:'`` and\n  ``'Cc myself:'`` is generated from the field name by converting all\n  underscores to spaces and upper-casing the first letter. Again, note\n  these are merely sensible defaults; you can also specify labels manually.\n\n* Each text label is surrounded in an HTML ``<label>`` tag, which points\n  to the appropriate form field via its ``id``. Its ``id``, in turn, is\n  generated by prepending ``'id_'`` to the field name. The ``id``\n  attributes and ``<label>`` tags are included in the output by default, to\n  follow best practices, but you can change that behavior.\n\n* The output uses HTML5 syntax, targeting ``<!DOCTYPE html>``. For example,\n  it uses boolean attributes such as ``checked`` rather than the XHTML style\n  of ``checked='checked'``.\n\nAlthough ``<table>`` output is the default output style when you ``print`` a\nform, other output styles are available. Each style is available as a method on\na form object, and each rendering method returns a string.\n\n``as_p()``\n----------\n\n.. method:: Form.as_p()\n\n``as_p()`` renders the form as a series of ``<p>`` tags, with each ``<p>``\ncontaining one field::\n\n    >>> f = ContactForm()\n    >>> f.as_p()\n    '<p><label for=\"id_subject\">Subject:</label> <input id=\"id_subject\" type=\"text\" name=\"subject\" maxlength=\"100\" required></p>\\n<p><label for=\"id_message\">Message:</label> <input type=\"text\" name=\"message\" id=\"id_message\" required></p>\\n<p><label for=\"id_sender\">Sender:</label> <input type=\"text\" name=\"sender\" id=\"id_sender\" required></p>\\n<p><label for=\"id_cc_myself\">Cc myself:</label> <input type=\"checkbox\" name=\"cc_myself\" id=\"id_cc_myself\"></p>'\n    >>> print(f.as_p())\n    <p><label for=\"id_subject\">Subject:</label> <input id=\"id_subject\" type=\"text\" name=\"subject\" maxlength=\"100\" required></p>\n    <p><label for=\"id_message\">Message:</label> <input type=\"text\" name=\"message\" id=\"id_message\" required></p>\n    <p><label for=\"id_sender\">Sender:</label> <input type=\"email\" name=\"sender\" id=\"id_sender\" required></p>\n    <p><label for=\"id_cc_myself\">Cc myself:</label> <input type=\"checkbox\" name=\"cc_myself\" id=\"id_cc_myself\"></p>\n\n``as_ul()``\n-----------\n\n.. method:: Form.as_ul()\n\n``as_ul()`` renders the form as a series of ``<li>`` tags, with each\n``<li>`` containing one field. It does *not* include the ``<ul>`` or\n``</ul>``, so that you can specify any HTML attributes on the ``<ul>`` for\nflexibility::\n\n    >>> f = ContactForm()\n    >>> f.as_ul()\n    '<li><label for=\"id_subject\">Subject:</label> <input id=\"id_subject\" type=\"text\" name=\"subject\" maxlength=\"100\" required></li>\\n<li><label for=\"id_message\">Message:</label> <input type=\"text\" name=\"message\" id=\"id_message\" required></li>\\n<li><label for=\"id_sender\">Sender:</label> <input type=\"email\" name=\"sender\" id=\"id_sender\" required></li>\\n<li><label for=\"id_cc_myself\">Cc myself:</label> <input type=\"checkbox\" name=\"cc_myself\" id=\"id_cc_myself\"></li>'\n    >>> print(f.as_ul())\n    <li><label for=\"id_subject\">Subject:</label> <input id=\"id_subject\" type=\"text\" name=\"subject\" maxlength=\"100\" required></li>\n    <li><label for=\"id_message\">Message:</label> <input type=\"text\" name=\"message\" id=\"id_message\" required></li>\n    <li><label for=\"id_sender\">Sender:</label> <input type=\"email\" name=\"sender\" id=\"id_sender\" required></li>\n    <li><label for=\"id_cc_myself\">Cc myself:</label> <input type=\"checkbox\" name=\"cc_myself\" id=\"id_cc_myself\"></li>\n\n``as_table()``\n--------------\n\n.. method:: Form.as_table()\n\nFinally, ``as_table()`` outputs the form as an HTML ``<table>``. This is\nexactly the same as ``print``. In fact, when you ``print`` a form object,\nit calls its ``as_table()`` method behind the scenes::\n\n    >>> f = ContactForm()\n    >>> f.as_table()\n    '<tr><th><label for=\"id_subject\">Subject:</label></th><td><input id=\"id_subject\" type=\"text\" name=\"subject\" maxlength=\"100\" required></td></tr>\\n<tr><th><label for=\"id_message\">Message:</label></th><td><input type=\"text\" name=\"message\" id=\"id_message\" required></td></tr>\\n<tr><th><label for=\"id_sender\">Sender:</label></th><td><input type=\"email\" name=\"sender\" id=\"id_sender\" required></td></tr>\\n<tr><th><label for=\"id_cc_myself\">Cc myself:</label></th><td><input type=\"checkbox\" name=\"cc_myself\" id=\"id_cc_myself\"></td></tr>'\n    >>> print(f)\n    <tr><th><label for=\"id_subject\">Subject:</label></th><td><input id=\"id_subject\" type=\"text\" name=\"subject\" maxlength=\"100\" required></td></tr>\n    <tr><th><label for=\"id_message\">Message:</label></th><td><input type=\"text\" name=\"message\" id=\"id_message\" required></td></tr>\n    <tr><th><label for=\"id_sender\">Sender:</label></th><td><input type=\"email\" name=\"sender\" id=\"id_sender\" required></td></tr>\n    <tr><th><label for=\"id_cc_myself\">Cc myself:</label></th><td><input type=\"checkbox\" name=\"cc_myself\" id=\"id_cc_myself\"></td></tr>\n\n.. _ref-forms-api-styling-form-rows:\n\nStyling required or erroneous form rows\n---------------------------------------\n\n.. attribute:: Form.error_css_class\n.. attribute:: Form.required_css_class\n\nIt's pretty common to style form rows and fields that are required or have\nerrors. For example, you might want to present required form rows in bold and\nhighlight errors in red.\n\nThe :class:`Form` class has a couple of hooks you can use to add ``class``\nattributes to required rows or to rows with errors: set the\n:attr:`Form.error_css_class` and/or :attr:`Form.required_css_class`\nattributes::\n\n    from django import forms\n\n    class ContactForm(forms.Form):\n        error_css_class = 'error'\n        required_css_class = 'required'\n\n        # ... and the rest of your fields here\n\nOnce you've done that, rows will be given ``\"error\"`` and/or ``\"required\"``\nclasses, as needed. The HTML will look something like::\n\n    >>> f = ContactForm(data)\n    >>> print(f.as_table())\n    <tr class=\"required\"><th><label class=\"required\" for=\"id_subject\">Subject:</label>    ...\n    <tr class=\"required\"><th><label class=\"required\" for=\"id_message\">Message:</label>    ...\n    <tr class=\"required error\"><th><label class=\"required\" for=\"id_sender\">Sender:</label>      ...\n    <tr><th><label for=\"id_cc_myself\">Cc myself:<label> ...\n    >>> f['subject'].label_tag()\n    <label class=\"required\" for=\"id_subject\">Subject:</label>\n    >>> f['subject'].label_tag(attrs={'class': 'foo'})\n    <label for=\"id_subject\" class=\"foo required\">Subject:</label>\n\n.. _ref-forms-api-configuring-label:\n\nConfiguring form elements' HTML ``id`` attributes and ``<label>`` tags\n----------------------------------------------------------------------\n\n.. attribute:: Form.auto_id\n\nBy default, the form rendering methods include:\n\n* HTML ``id`` attributes on the form elements.\n\n* The corresponding ``<label>`` tags around the labels. An HTML ``<label>`` tag\n  designates which label text is associated with which form element. This small\n  enhancement makes forms more usable and more accessible to assistive devices.\n  It's always a good idea to use ``<label>`` tags.\n\nThe ``id`` attribute values are generated by prepending ``id_`` to the form\nfield names.  This behavior is configurable, though, if you want to change the\n``id`` convention or remove HTML ``id`` attributes and ``<label>`` tags\nentirely.\n\nUse the ``auto_id`` argument to the ``Form`` constructor to control the ``id``\nand label behavior. This argument must be ``True``, ``False`` or a string.\n\nIf ``auto_id`` is ``False``, then the form output will not include ``<label>``\ntags nor ``id`` attributes::\n\n    >>> f = ContactForm(auto_id=False)\n    >>> print(f.as_table())\n    <tr><th>Subject:</th><td><input type=\"text\" name=\"subject\" maxlength=\"100\" required></td></tr>\n    <tr><th>Message:</th><td><input type=\"text\" name=\"message\" required></td></tr>\n    <tr><th>Sender:</th><td><input type=\"email\" name=\"sender\" required></td></tr>\n    <tr><th>Cc myself:</th><td><input type=\"checkbox\" name=\"cc_myself\"></td></tr>\n    >>> print(f.as_ul())\n    <li>Subject: <input type=\"text\" name=\"subject\" maxlength=\"100\" required></li>\n    <li>Message: <input type=\"text\" name=\"message\" required></li>\n    <li>Sender: <input type=\"email\" name=\"sender\" required></li>\n    <li>Cc myself: <input type=\"checkbox\" name=\"cc_myself\"></li>\n    >>> print(f.as_p())\n    <p>Subject: <input type=\"text\" name=\"subject\" maxlength=\"100\" required></p>\n    <p>Message: <input type=\"text\" name=\"message\" required></p>\n    <p>Sender: <input type=\"email\" name=\"sender\" required></p>\n    <p>Cc myself: <input type=\"checkbox\" name=\"cc_myself\"></p>\n\nIf ``auto_id`` is set to ``True``, then the form output *will* include\n``<label>`` tags and will use the field name as its ``id`` for each form\nfield::\n\n    >>> f = ContactForm(auto_id=True)\n    >>> print(f.as_table())\n    <tr><th><label for=\"subject\">Subject:</label></th><td><input id=\"subject\" type=\"text\" name=\"subject\" maxlength=\"100\" required></td></tr>\n    <tr><th><label for=\"message\">Message:</label></th><td><input type=\"text\" name=\"message\" id=\"message\" required></td></tr>\n    <tr><th><label for=\"sender\">Sender:</label></th><td><input type=\"email\" name=\"sender\" id=\"sender\" required></td></tr>\n    <tr><th><label for=\"cc_myself\">Cc myself:</label></th><td><input type=\"checkbox\" name=\"cc_myself\" id=\"cc_myself\"></td></tr>\n    >>> print(f.as_ul())\n    <li><label for=\"subject\">Subject:</label> <input id=\"subject\" type=\"text\" name=\"subject\" maxlength=\"100\" required></li>\n    <li><label for=\"message\">Message:</label> <input type=\"text\" name=\"message\" id=\"message\" required></li>\n    <li><label for=\"sender\">Sender:</label> <input type=\"email\" name=\"sender\" id=\"sender\" required></li>\n    <li><label for=\"cc_myself\">Cc myself:</label> <input type=\"checkbox\" name=\"cc_myself\" id=\"cc_myself\"></li>\n    >>> print(f.as_p())\n    <p><label for=\"subject\">Subject:</label> <input id=\"subject\" type=\"text\" name=\"subject\" maxlength=\"100\" required></p>\n    <p><label for=\"message\">Message:</label> <input type=\"text\" name=\"message\" id=\"message\" required></p>\n    <p><label for=\"sender\">Sender:</label> <input type=\"email\" name=\"sender\" id=\"sender\" required></p>\n    <p><label for=\"cc_myself\">Cc myself:</label> <input type=\"checkbox\" name=\"cc_myself\" id=\"cc_myself\"></p>\n\nIf ``auto_id`` is set to a string containing the format character ``'%s'``,\nthen the form output will include ``<label>`` tags, and will generate ``id``\nattributes based on the format string. For example, for a format string\n``'field_%s'``, a field named ``subject`` will get the ``id`` value\n``'field_subject'``. Continuing our example::\n\n    >>> f = ContactForm(auto_id='id_for_%s')\n    >>> print(f.as_table())\n    <tr><th><label for=\"id_for_subject\">Subject:</label></th><td><input id=\"id_for_subject\" type=\"text\" name=\"subject\" maxlength=\"100\" required></td></tr>\n    <tr><th><label for=\"id_for_message\">Message:</label></th><td><input type=\"text\" name=\"message\" id=\"id_for_message\" required></td></tr>\n    <tr><th><label for=\"id_for_sender\">Sender:</label></th><td><input type=\"email\" name=\"sender\" id=\"id_for_sender\" required></td></tr>\n    <tr><th><label for=\"id_for_cc_myself\">Cc myself:</label></th><td><input type=\"checkbox\" name=\"cc_myself\" id=\"id_for_cc_myself\"></td></tr>\n    >>> print(f.as_ul())\n    <li><label for=\"id_for_subject\">Subject:</label> <input id=\"id_for_subject\" type=\"text\" name=\"subject\" maxlength=\"100\" required></li>\n    <li><label for=\"id_for_message\">Message:</label> <input type=\"text\" name=\"message\" id=\"id_for_message\" required></li>\n    <li><label for=\"id_for_sender\">Sender:</label> <input type=\"email\" name=\"sender\" id=\"id_for_sender\" required></li>\n    <li><label for=\"id_for_cc_myself\">Cc myself:</label> <input type=\"checkbox\" name=\"cc_myself\" id=\"id_for_cc_myself\"></li>\n    >>> print(f.as_p())\n    <p><label for=\"id_for_subject\">Subject:</label> <input id=\"id_for_subject\" type=\"text\" name=\"subject\" maxlength=\"100\" required></p>\n    <p><label for=\"id_for_message\">Message:</label> <input type=\"text\" name=\"message\" id=\"id_for_message\" required></p>\n    <p><label for=\"id_for_sender\">Sender:</label> <input type=\"email\" name=\"sender\" id=\"id_for_sender\" required></p>\n    <p><label for=\"id_for_cc_myself\">Cc myself:</label> <input type=\"checkbox\" name=\"cc_myself\" id=\"id_for_cc_myself\"></p>\n\nIf ``auto_id`` is set to any other true value -- such as a string that doesn't\ninclude ``%s`` -- then the library will act as if ``auto_id`` is ``True``.\n\nBy default, ``auto_id`` is set to the string ``'id_%s'``.\n\n.. attribute:: Form.label_suffix\n\nA translatable string (defaults to a colon (``:``) in English) that will be\nappended after any label name when a form is rendered.\n\nIt's possible to customize that character, or omit it entirely, using the\n``label_suffix`` parameter::\n\n    >>> f = ContactForm(auto_id='id_for_%s', label_suffix='')\n    >>> print(f.as_ul())\n    <li><label for=\"id_for_subject\">Subject</label> <input id=\"id_for_subject\" type=\"text\" name=\"subject\" maxlength=\"100\" required></li>\n    <li><label for=\"id_for_message\">Message</label> <input type=\"text\" name=\"message\" id=\"id_for_message\" required></li>\n    <li><label for=\"id_for_sender\">Sender</label> <input type=\"email\" name=\"sender\" id=\"id_for_sender\" required></li>\n    <li><label for=\"id_for_cc_myself\">Cc myself</label> <input type=\"checkbox\" name=\"cc_myself\" id=\"id_for_cc_myself\"></li>\n    >>> f = ContactForm(auto_id='id_for_%s', label_suffix=' ->')\n    >>> print(f.as_ul())\n    <li><label for=\"id_for_subject\">Subject -></label> <input id=\"id_for_subject\" type=\"text\" name=\"subject\" maxlength=\"100\" required></li>\n    <li><label for=\"id_for_message\">Message -></label> <input type=\"text\" name=\"message\" id=\"id_for_message\" required></li>\n    <li><label for=\"id_for_sender\">Sender -></label> <input type=\"email\" name=\"sender\" id=\"id_for_sender\" required></li>\n    <li><label for=\"id_for_cc_myself\">Cc myself -></label> <input type=\"checkbox\" name=\"cc_myself\" id=\"id_for_cc_myself\"></li>\n\nNote that the label suffix is added only if the last character of the\nlabel isn't a punctuation character (in English, those are ``.``, ``!``, ``?``\nor ``:``).\n\nFields can also define their own :attr:`~django.forms.Field.label_suffix`.\nThis will take precedence over :attr:`Form.label_suffix\n<django.forms.Form.label_suffix>`. The suffix can also be overridden at runtime\nusing the ``label_suffix`` parameter to\n:meth:`~django.forms.BoundField.label_tag`.\n\n.. attribute:: Form.use_required_attribute\n\nWhen set to ``True`` (the default), required form fields will have the\n``required`` HTML attribute.\n\n:doc:`Formsets </topics/forms/formsets>` instantiate forms with\n``use_required_attribute=False`` to avoid incorrect browser validation when\nadding and deleting forms from a formset.\n\nConfiguring the rendering of a form's widgets\n---------------------------------------------\n\n.. attribute:: Form.default_renderer\n\nSpecifies the :doc:`renderer <renderers>` to use for the form. Defaults to\n``None`` which means to use the default renderer specified by the\n:setting:`FORM_RENDERER` setting.\n\nYou can set this as a class attribute when declaring your form or use the\n``renderer`` argument to ``Form.__init__()``. For example::\n\n    from django import forms\n\n    class MyForm(forms.Form):\n        default_renderer = MyRenderer()\n\nor::\n\n    form = MyForm(renderer=MyRenderer())\n\nNotes on field ordering\n-----------------------\n\nIn the ``as_p()``, ``as_ul()`` and ``as_table()`` shortcuts, the fields are\ndisplayed in the order in which you define them in your form class. For\nexample, in the ``ContactForm`` example, the fields are defined in the order\n``subject``, ``message``, ``sender``, ``cc_myself``. To reorder the HTML\noutput, change the order in which those fields are listed in the class.\n\nThere are several other ways to customize the order:\n\n.. attribute:: Form.field_order\n\nBy default ``Form.field_order=None``, which retains the order in which you\ndefine the fields in your form class. If ``field_order`` is a list of field\nnames, the fields are ordered as specified by the list and remaining fields are\nappended according to the default order. Unknown field names in the list are\nignored. This makes it possible to disable a field in a subclass by setting it\nto ``None`` without having to redefine ordering.\n\nYou can also use the ``Form.field_order`` argument to a :class:`Form` to\noverride the field order. If a :class:`~django.forms.Form` defines\n:attr:`~Form.field_order` *and* you include ``field_order`` when instantiating\nthe ``Form``, then the latter ``field_order`` will have precedence.\n\n.. method:: Form.order_fields(field_order)\n\nYou may rearrange the fields any time using ``order_fields()`` with a list of\nfield names as in :attr:`~django.forms.Form.field_order`.\n\nHow errors are displayed\n------------------------\n\nIf you render a bound ``Form`` object, the act of rendering will automatically\nrun the form's validation if it hasn't already happened, and the HTML output\nwill include the validation errors as a ``<ul class=\"errorlist\">`` near the\nfield. The particular positioning of the error messages depends on the output\nmethod you're using::\n\n    >>> data = {'subject': '',\n    ...         'message': 'Hi there',\n    ...         'sender': 'invalid email address',\n    ...         'cc_myself': True}\n    >>> f = ContactForm(data, auto_id=False)\n    >>> print(f.as_table())\n    <tr><th>Subject:</th><td><ul class=\"errorlist\"><li>This field is required.</li></ul><input type=\"text\" name=\"subject\" maxlength=\"100\" required></td></tr>\n    <tr><th>Message:</th><td><input type=\"text\" name=\"message\" value=\"Hi there\" required></td></tr>\n    <tr><th>Sender:</th><td><ul class=\"errorlist\"><li>Enter a valid email address.</li></ul><input type=\"email\" name=\"sender\" value=\"invalid email address\" required></td></tr>\n    <tr><th>Cc myself:</th><td><input checked type=\"checkbox\" name=\"cc_myself\"></td></tr>\n    >>> print(f.as_ul())\n    <li><ul class=\"errorlist\"><li>This field is required.</li></ul>Subject: <input type=\"text\" name=\"subject\" maxlength=\"100\" required></li>\n    <li>Message: <input type=\"text\" name=\"message\" value=\"Hi there\" required></li>\n    <li><ul class=\"errorlist\"><li>Enter a valid email address.</li></ul>Sender: <input type=\"email\" name=\"sender\" value=\"invalid email address\" required></li>\n    <li>Cc myself: <input checked type=\"checkbox\" name=\"cc_myself\"></li>\n    >>> print(f.as_p())\n    <p><ul class=\"errorlist\"><li>This field is required.</li></ul></p>\n    <p>Subject: <input type=\"text\" name=\"subject\" maxlength=\"100\" required></p>\n    <p>Message: <input type=\"text\" name=\"message\" value=\"Hi there\" required></p>\n    <p><ul class=\"errorlist\"><li>Enter a valid email address.</li></ul></p>\n    <p>Sender: <input type=\"email\" name=\"sender\" value=\"invalid email address\" required></p>\n    <p>Cc myself: <input checked type=\"checkbox\" name=\"cc_myself\"></p>\n\n.. _ref-forms-error-list-format:\n\nCustomizing the error list format\n---------------------------------\n\nBy default, forms use ``django.forms.utils.ErrorList`` to format validation\nerrors. If you'd like to use an alternate class for displaying errors, you can\npass that in at construction time::\n\n    >>> from django.forms.utils import ErrorList\n    >>> class DivErrorList(ErrorList):\n    ...     def __str__(self):\n    ...         return self.as_divs()\n    ...     def as_divs(self):\n    ...         if not self: return ''\n    ...         return '<div class=\"errorlist\">%s</div>' % ''.join(['<div class=\"error\">%s</div>' % e for e in self])\n    >>> f = ContactForm(data, auto_id=False, error_class=DivErrorList)\n    >>> f.as_p()\n    <div class=\"errorlist\"><div class=\"error\">This field is required.</div></div>\n    <p>Subject: <input type=\"text\" name=\"subject\" maxlength=\"100\" required></p>\n    <p>Message: <input type=\"text\" name=\"message\" value=\"Hi there\" required></p>\n    <div class=\"errorlist\"><div class=\"error\">Enter a valid email address.</div></div>\n    <p>Sender: <input type=\"email\" name=\"sender\" value=\"invalid email address\" required></p>\n    <p>Cc myself: <input checked type=\"checkbox\" name=\"cc_myself\"></p>\n\nMore granular output\n====================\n\nThe ``as_p()``, ``as_ul()``, and ``as_table()`` methods are shortcuts --\nthey're not the only way a form object can be displayed.\n\n.. class:: BoundField\n\n   Used to display HTML or access attributes for a single field of a\n   :class:`Form` instance.\n\n   The ``__str__()`` method of this object displays the HTML for this field.\n\nTo retrieve a single ``BoundField``, use dictionary lookup syntax on your form\nusing the field's name as the key::\n\n    >>> form = ContactForm()\n    >>> print(form['subject'])\n    <input id=\"id_subject\" type=\"text\" name=\"subject\" maxlength=\"100\" required>\n\nTo retrieve all ``BoundField`` objects, iterate the form::\n\n    >>> form = ContactForm()\n    >>> for boundfield in form: print(boundfield)\n    <input id=\"id_subject\" type=\"text\" name=\"subject\" maxlength=\"100\" required>\n    <input type=\"text\" name=\"message\" id=\"id_message\" required>\n    <input type=\"email\" name=\"sender\" id=\"id_sender\" required>\n    <input type=\"checkbox\" name=\"cc_myself\" id=\"id_cc_myself\">\n\nThe field-specific output honors the form object's ``auto_id`` setting::\n\n    >>> f = ContactForm(auto_id=False)\n    >>> print(f['message'])\n    <input type=\"text\" name=\"message\" required>\n    >>> f = ContactForm(auto_id='id_%s')\n    >>> print(f['message'])\n    <input type=\"text\" name=\"message\" id=\"id_message\" required>\n\nAttributes of ``BoundField``\n----------------------------\n\n.. attribute:: BoundField.auto_id\n\n    The HTML ID attribute for this ``BoundField``. Returns an empty string\n    if :attr:`Form.auto_id` is ``False``.\n\n.. attribute:: BoundField.data\n\n    This property returns the data for this :class:`~django.forms.BoundField`\n    extracted by the widget's :meth:`~django.forms.Widget.value_from_datadict`\n    method, or ``None`` if it wasn't given::\n\n        >>> unbound_form = ContactForm()\n        >>> print(unbound_form['subject'].data)\n        None\n        >>> bound_form = ContactForm(data={'subject': 'My Subject'})\n        >>> print(bound_form['subject'].data)\n        My Subject\n\n.. attribute:: BoundField.errors\n\n    A :ref:`list-like object <ref-forms-error-list-format>` that is displayed\n    as an HTML ``<ul class=\"errorlist\">`` when printed::\n\n        >>> data = {'subject': 'hi', 'message': '', 'sender': '', 'cc_myself': ''}\n        >>> f = ContactForm(data, auto_id=False)\n        >>> print(f['message'])\n        <input type=\"text\" name=\"message\" required>\n        >>> f['message'].errors\n        ['This field is required.']\n        >>> print(f['message'].errors)\n        <ul class=\"errorlist\"><li>This field is required.</li></ul>\n        >>> f['subject'].errors\n        []\n        >>> print(f['subject'].errors)\n\n        >>> str(f['subject'].errors)\n        ''\n\n.. attribute:: BoundField.field\n\n    The form :class:`~django.forms.Field` instance from the form class that\n    this :class:`~django.forms.BoundField` wraps.\n\n.. attribute:: BoundField.form\n\n    The :class:`~django.forms.Form` instance this :class:`~django.forms.BoundField`\n    is bound to.\n\n.. attribute:: BoundField.help_text\n\n    The :attr:`~django.forms.Field.help_text` of the field.\n\n.. attribute:: BoundField.html_name\n\n    The name that will be used in the widget's HTML ``name`` attribute. It takes\n    the form :attr:`~django.forms.Form.prefix` into account.\n\n.. attribute:: BoundField.id_for_label\n\n    Use this property to render the ID of this field. For example, if you are\n    manually constructing a ``<label>`` in your template (despite the fact that\n    :meth:`~BoundField.label_tag` will do this for you):\n\n    .. code-block:: html+django\n\n        <label for=\"{{ form.my_field.id_for_label }}\">...</label>{{ my_field }}\n\n    By default, this will be the field's name prefixed by ``id_``\n    (\"``id_my_field``\" for the example above). You may modify the ID by setting\n    :attr:`~django.forms.Widget.attrs` on the field's widget. For example,\n    declaring a field like this::\n\n        my_field = forms.CharField(widget=forms.TextInput(attrs={'id': 'myFIELD'}))\n\n    and using the template above, would render something like:\n\n    .. code-block:: html\n\n        <label for=\"myFIELD\">...</label><input id=\"myFIELD\" type=\"text\" name=\"my_field\" required>\n\n.. attribute:: BoundField.is_hidden\n\n    Returns ``True`` if this :class:`~django.forms.BoundField`'s widget is\n    hidden.\n\n.. attribute:: BoundField.label\n\n    The :attr:`~django.forms.Field.label` of the field. This is used in\n    :meth:`~BoundField.label_tag`.\n\n.. attribute:: BoundField.name\n\n    The name of this field in the form::\n\n        >>> f = ContactForm()\n        >>> print(f['subject'].name)\n        subject\n        >>> print(f['message'].name)\n        message\n\n.. attribute:: BoundField.widget_type\n\n    .. versionadded:: 3.1\n\n    Returns the lowercased class name of the wrapped field's widget, with any\n    trailing ``input`` or ``widget`` removed. This may be used when building\n    forms where the layout is dependent upon the widget type. For example::\n\n        {% for field in form %}\n            {% if field.widget_type == 'checkbox' %}\n                # render one way\n            {% else %}\n                # render another way\n            {% endif %}\n        {% endfor %}\n\n\nMethods of ``BoundField``\n-------------------------\n\n.. method:: BoundField.as_hidden(attrs=None, **kwargs)\n\n    Returns a string of HTML for representing this as an ``<input type=\"hidden\">``.\n\n    ``**kwargs`` are passed to :meth:`~django.forms.BoundField.as_widget`.\n\n    This method is primarily used internally. You should use a widget instead.\n\n.. method:: BoundField.as_widget(widget=None, attrs=None, only_initial=False)\n\n    Renders the field by rendering the passed widget, adding any HTML\n    attributes passed as ``attrs``.  If no widget is specified, then the\n    field's default widget will be used.\n\n    ``only_initial`` is used by Django internals and should not be set\n    explicitly.\n\n.. method:: BoundField.css_classes(extra_classes=None)\n\n    When you use Django's rendering shortcuts, CSS classes are used to\n    indicate required form fields or fields that contain errors. If you're\n    manually rendering a form, you can access these CSS classes using the\n    ``css_classes`` method::\n\n        >>> f = ContactForm(data={'message': ''})\n        >>> f['message'].css_classes()\n        'required'\n\n    If you want to provide some additional classes in addition to the\n    error and required classes that may be required, you can provide\n    those classes as an argument::\n\n        >>> f = ContactForm(data={'message': ''})\n        >>> f['message'].css_classes('foo bar')\n        'foo bar required'\n\n.. method:: BoundField.label_tag(contents=None, attrs=None, label_suffix=None)\n\n    To separately render the label tag of a form field, you can call its\n    ``label_tag()`` method::\n\n        >>> f = ContactForm(data={'message': ''})\n        >>> print(f['message'].label_tag())\n        <label for=\"id_message\">Message:</label>\n\n    You can provide the ``contents`` parameter which will replace the\n    auto-generated label tag. An ``attrs`` dictionary may contain additional\n    attributes for the ``<label>`` tag.\n\n    The HTML that's generated includes the form's\n    :attr:`~django.forms.Form.label_suffix` (a colon, by default) or, if set, the\n    current field's :attr:`~django.forms.Field.label_suffix`. The optional\n    ``label_suffix`` parameter allows you to override any previously set\n    suffix. For example, you can use an empty string to hide the label on selected\n    fields. If you need to do this in a template, you could write a custom\n    filter to allow passing parameters to ``label_tag``.\n\n.. method:: BoundField.value()\n\n    Use this method to render the raw value of this field as it would be rendered\n    by a ``Widget``::\n\n        >>> initial = {'subject': 'welcome'}\n        >>> unbound_form = ContactForm(initial=initial)\n        >>> bound_form = ContactForm(data={'subject': 'hi'}, initial=initial)\n        >>> print(unbound_form['subject'].value())\n        welcome\n        >>> print(bound_form['subject'].value())\n        hi\n\nCustomizing ``BoundField``\n==========================\n\nIf you need to access some additional information about a form field in a\ntemplate and using a subclass of :class:`~django.forms.Field` isn't\nsufficient, consider also customizing :class:`~django.forms.BoundField`.\n\nA custom form field can override ``get_bound_field()``:\n\n.. method:: Field.get_bound_field(form, field_name)\n\n    Takes an instance of :class:`~django.forms.Form` and the name of the field.\n    The return value will be used when accessing the field in a template. Most\n    likely it will be an instance of a subclass of\n    :class:`~django.forms.BoundField`.\n\nIf you have a ``GPSCoordinatesField``, for example, and want to be able to\naccess additional information about the coordinates in a template, this could\nbe implemented as follows::\n\n    class GPSCoordinatesBoundField(BoundField):\n        @property\n        def country(self):\n            \"\"\"\n            Return the country the coordinates lie in or None if it can't be\n            determined.\n            \"\"\"\n            value = self.value()\n            if value:\n                return get_country_from_coordinates(value)\n            else:\n                return None\n\n    class GPSCoordinatesField(Field):\n        def get_bound_field(self, form, field_name):\n            return GPSCoordinatesBoundField(form, self, field_name)\n\nNow you can access the country in a template with\n``{{ form.coordinates.country }}``.\n\n.. _binding-uploaded-files:\n\nBinding uploaded files to a form\n================================\n\nDealing with forms that have ``FileField`` and ``ImageField`` fields\nis a little more complicated than a normal form.\n\nFirstly, in order to upload files, you'll need to make sure that your\n``<form>`` element correctly defines the ``enctype`` as\n``\"multipart/form-data\"``::\n\n  <form enctype=\"multipart/form-data\" method=\"post\" action=\"/foo/\">\n\nSecondly, when you use the form, you need to bind the file data. File\ndata is handled separately to normal form data, so when your form\ncontains a ``FileField`` and ``ImageField``, you will need to specify\na second argument when you bind your form. So if we extend our\nContactForm to include an ``ImageField`` called ``mugshot``, we\nneed to bind the file data containing the mugshot image::\n\n    # Bound form with an image field\n    >>> from django.core.files.uploadedfile import SimpleUploadedFile\n    >>> data = {'subject': 'hello',\n    ...         'message': 'Hi there',\n    ...         'sender': 'foo@example.com',\n    ...         'cc_myself': True}\n    >>> file_data = {'mugshot': SimpleUploadedFile('face.jpg', <file data>)}\n    >>> f = ContactFormWithMugshot(data, file_data)\n\nIn practice, you will usually specify ``request.FILES`` as the source\nof file data (just like you use ``request.POST`` as the source of\nform data)::\n\n    # Bound form with an image field, data from the request\n    >>> f = ContactFormWithMugshot(request.POST, request.FILES)\n\nConstructing an unbound form is the same as always -- omit both form data *and*\nfile data::\n\n    # Unbound form with an image field\n    >>> f = ContactFormWithMugshot()\n\nTesting for multipart forms\n---------------------------\n\n.. method:: Form.is_multipart()\n\nIf you're writing reusable views or templates, you may not know ahead of time\nwhether your form is a multipart form or not. The ``is_multipart()`` method\ntells you whether the form requires multipart encoding for submission::\n\n    >>> f = ContactFormWithMugshot()\n    >>> f.is_multipart()\n    True\n\nHere's an example of how you might use this in a template::\n\n    {% if form.is_multipart %}\n        <form enctype=\"multipart/form-data\" method=\"post\" action=\"/foo/\">\n    {% else %}\n        <form method=\"post\" action=\"/foo/\">\n    {% endif %}\n    {{ form }}\n    </form>\n\nSubclassing forms\n=================\n\nIf you have multiple ``Form`` classes that share fields, you can use\nsubclassing to remove redundancy.\n\nWhen you subclass a custom ``Form`` class, the resulting subclass will\ninclude all fields of the parent class(es), followed by the fields you define\nin the subclass.\n\nIn this example, ``ContactFormWithPriority`` contains all the fields from\n``ContactForm``, plus an additional field, ``priority``. The ``ContactForm``\nfields are ordered first::\n\n    >>> class ContactFormWithPriority(ContactForm):\n    ...     priority = forms.CharField()\n    >>> f = ContactFormWithPriority(auto_id=False)\n    >>> print(f.as_ul())\n    <li>Subject: <input type=\"text\" name=\"subject\" maxlength=\"100\" required></li>\n    <li>Message: <input type=\"text\" name=\"message\" required></li>\n    <li>Sender: <input type=\"email\" name=\"sender\" required></li>\n    <li>Cc myself: <input type=\"checkbox\" name=\"cc_myself\"></li>\n    <li>Priority: <input type=\"text\" name=\"priority\" required></li>\n\nIt's possible to subclass multiple forms, treating forms as mixins. In this\nexample, ``BeatleForm`` subclasses both ``PersonForm`` and ``InstrumentForm``\n(in that order), and its field list includes the fields from the parent\nclasses::\n\n    >>> from django import forms\n    >>> class PersonForm(forms.Form):\n    ...     first_name = forms.CharField()\n    ...     last_name = forms.CharField()\n    >>> class InstrumentForm(forms.Form):\n    ...     instrument = forms.CharField()\n    >>> class BeatleForm(InstrumentForm, PersonForm):\n    ...     haircut_type = forms.CharField()\n    >>> b = BeatleForm(auto_id=False)\n    >>> print(b.as_ul())\n    <li>First name: <input type=\"text\" name=\"first_name\" required></li>\n    <li>Last name: <input type=\"text\" name=\"last_name\" required></li>\n    <li>Instrument: <input type=\"text\" name=\"instrument\" required></li>\n    <li>Haircut type: <input type=\"text\" name=\"haircut_type\" required></li>\n\nIt's possible to declaratively remove a ``Field`` inherited from a parent class\nby setting the name of the field to ``None`` on the subclass. For example::\n\n    >>> from django import forms\n\n    >>> class ParentForm(forms.Form):\n    ...     name = forms.CharField()\n    ...     age = forms.IntegerField()\n\n    >>> class ChildForm(ParentForm):\n    ...     name = None\n\n    >>> list(ChildForm().fields)\n    ['age']\n\n.. _form-prefix:\n\nPrefixes for forms\n==================\n\n.. attribute:: Form.prefix\n\nYou can put several Django forms inside one ``<form>`` tag. To give each\n``Form`` its own namespace, use the ``prefix`` keyword argument::\n\n    >>> mother = PersonForm(prefix=\"mother\")\n    >>> father = PersonForm(prefix=\"father\")\n    >>> print(mother.as_ul())\n    <li><label for=\"id_mother-first_name\">First name:</label> <input type=\"text\" name=\"mother-first_name\" id=\"id_mother-first_name\" required></li>\n    <li><label for=\"id_mother-last_name\">Last name:</label> <input type=\"text\" name=\"mother-last_name\" id=\"id_mother-last_name\" required></li>\n    >>> print(father.as_ul())\n    <li><label for=\"id_father-first_name\">First name:</label> <input type=\"text\" name=\"father-first_name\" id=\"id_father-first_name\" required></li>\n    <li><label for=\"id_father-last_name\">Last name:</label> <input type=\"text\" name=\"father-last_name\" id=\"id_father-last_name\" required></li>\n\nThe prefix can also be specified on the form class::\n\n    >>> class PersonForm(forms.Form):\n    ...     ...\n    ...     prefix = 'person'\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":66,"nodeType":"TextFile","repoName":null,"name":"tox.ini","path":"","text":"# Tox (https://tox.readthedocs.io/) is a tool for running tests in multiple\n# virtualenvs. This configuration file helps to run the test suite on all\n# supported Python versions. To use it, \"python -m pip install tox\" and\n# then run \"tox\" from this directory.\n\n[tox]\nskipsdist = true\nenvlist =\n    py3\n    flake8\n    docs\n    isort\n\n# Add environment to use the default python3 installation\n[testenv:py3]\nbasepython = python3\n\n[testenv]\nusedevelop = true\n# OBJC_DISABLE_INITIALIZE_FORK_SAFETY fixes hung tests for MacOS users. (#30806)\npassenv = DJANGO_SETTINGS_MODULE PYTHONPATH HOME DISPLAY OBJC_DISABLE_INITIALIZE_FORK_SAFETY\nsetenv =\n    PYTHONDONTWRITEBYTECODE=1\ndeps =\n    py{3,36,37,38}: -rtests/requirements/py3.txt\n    postgres: -rtests/requirements/postgres.txt\n    mysql: -rtests/requirements/mysql.txt\n    oracle: -rtests/requirements/oracle.txt\nchangedir = tests\ncommands =\n    {envpython} runtests.py {posargs}\n\n[testenv:flake8]\nbasepython = python3\nusedevelop = false\ndeps = flake8\nchangedir = {toxinidir}\ncommands = flake8 .\n\n[testenv:docs]\nbasepython = python3\nusedevelop = false\nwhitelist_externals =\n    make\ndeps =\n    Sphinx\n    pyenchant\n    sphinxcontrib-spelling\nchangedir = docs\ncommands =\n    make spelling\n\n[testenv:isort]\nbasepython = python3\nusedevelop = false\ndeps = isort\nchangedir = {toxinidir}\ncommands = isort --recursive --check-only --diff django tests scripts\n\n[testenv:javascript]\nusedevelop = false\ndeps =\nchangedir = {toxinidir}\nwhitelist_externals = npm\ncommands =\n    npm install\n    npm test\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":67,"nodeType":"TextFile","repoName":null,"name":"AUTHORS","path":"","text":"Django was originally created in late 2003 at World Online, the Web division\nof the Lawrence Journal-World newspaper in Lawrence, Kansas.\n\nHere is an inevitably incomplete list of MUCH-APPRECIATED CONTRIBUTORS --\npeople who have submitted patches, reported bugs, added translations, helped\nanswer newbie questions, and generally made Django that much better:\n\n    Aaron Cannon <cannona@fireantproductions.com>\n    Aaron Swartz <http://www.aaronsw.com/>\n    Aaron T. Myers <atmyers@gmail.com>\n    Abeer Upadhyay <ab.esquarer@gmail.com>\n    Abhijeet Viswa <abhijeetviswa@gmail.com>\n    Abhinav Patil <https://github.com/ubadub/>\n    Abhishek Gautam <abhishekg1128@yahoo.com>\n    Adam Allred <adam.w.allred@gmail.com>\n    Adam Bogdał <adam@bogdal.pl>\n    Adam Donaghy\n    Adam Johnson <https://github.com/adamchainz>\n    Adam Malinowski <https://adammalinowski.co.uk/>\n    Adam Vandenberg\n    Adiyat Mubarak <adiyatmubarak@gmail.com>\n    Adnan Umer <u.adnan@outlook.com>\n    Adrian Holovaty <adrian@holovaty.com>\n    Adrien Lemaire <lemaire.adrien@gmail.com>\n    Afonso Fernández Nogueira <fonzzo.django@gmail.com>\n    AgarFu <heaven@croasanaso.sytes.net>\n    Ahmad Alhashemi <trans@ahmadh.com>\n    Ahmad Al-Ibrahim\n    Ahmed Eltawela <https://github.com/ahmedabt>\n    ajs <adi@sieker.info>\n    Akash Agrawal <akashrocksha@gmail.com>\n    Akis Kesoglou <akiskesoglou@gmail.com>\n    Aksel Ethem <aksel.ethem@gmail.com>\n    Akshesh Doshi <aksheshdoshi+django@gmail.com>\n    alang@bright-green.com\n    Alasdair Nicol <https://al.sdair.co.uk/>\n    Albert Wang <https://github.com/albertyw/>\n    Alcides Fonseca\n    Aldian Fazrihady <mobile@aldian.net>\n    Aleksandra Sendecka <asendecka@hauru.eu>\n    Aleksi Häkli <aleksi.hakli@iki.fi>\n    Alexander Dutton <dev@alexdutton.co.uk>\n    Alexander Myodov <alex@myodov.com>\n    Alexandr Tatarinov <tatarinov1997@gmail.com>\n    Alex Aktsipetrov <alex.akts@gmail.com>\n    Alex Becker <https://alexcbecker.net/>\n    Alex Couper <http://alexcouper.com/>\n    Alex Dedul\n    Alex Gaynor <alex.gaynor@gmail.com>\n    Alex Hill <alex@hill.net.au>\n    Alex Ogier <alex.ogier@gmail.com>\n    Alex Robbins <alexander.j.robbins@gmail.com>\n    Alexey Boriskin <alex@boriskin.me>\n    Alexey Tsivunin <most-208@yandex.ru>\n    Aljosa Mohorovic <aljosa.mohorovic@gmail.com>\n    Amit Chakradeo <https://amit.chakradeo.net/>\n    Amit Ramon <amit.ramon@gmail.com>\n    Amit Upadhyay <http://www.amitu.com/blog/>\n    A. Murat Eren <meren@pardus.org.tr>\n    Ana Belen Sarabia <belensarabia@gmail.com>\n    Ana Krivokapic <https://github.com/infraredgirl>\n    Andi Albrecht <albrecht.andi@gmail.com>\n    André Ericson <de.ericson@gmail.com>\n    Andrei Kulakov <andrei.avk@gmail.com>\n    Andreas\n    Andreas Mock <andreas.mock@web.de>\n    Andreas Pelme <andreas@pelme.se>\n    Andrés Torres Marroquín <andres.torres.marroquin@gmail.com>\n    Andrew Brehaut <https://brehaut.net/blog>\n    Andrew Clark <amclark7@gmail.com>\n    Andrew Durdin <adurdin@gmail.com>\n    Andrew Godwin <andrew@aeracode.org>\n    Andrew Pinkham <http://AndrewsForge.com>\n    Andrews Medina <andrewsmedina@gmail.com>\n    Andriy Sokolovskiy <me@asokolovskiy.com>\n    Andy Dustman <farcepest@gmail.com>\n    Andy Gayton <andy-django@thecablelounge.com>\n    andy@jadedplanet.net\n    Anssi Kääriäinen <akaariai@gmail.com>\n    ant9000@netwise.it\n    Anthony Briggs <anthony.briggs@gmail.com>\n    Anton Samarchyan <desecho@gmail.com>\n    Antoni Aloy\n    Antonio Cavedoni <http://cavedoni.com/>\n    Antonis Christofides <anthony@itia.ntua.gr>\n    Antti Haapala <antti@industrialwebandmagic.com>\n    Antti Kaihola <http://djangopeople.net/akaihola/>\n    Anubhav Joshi <anubhav9042@gmail.com>\n    Aram Dulyan\n    arien <regexbot@gmail.com>\n    Armin Ronacher\n    Aron Podrigal <aronp@guaranteedplus.com>\n    Artem Gnilov <boobsd@gmail.com>\n    Arthur <avandorp@gmail.com>\n    Arthur Koziel <http://arthurkoziel.com>\n    Arthur Rio <arthur.rio44@gmail.com>\n    Arvis Bickovskis <viestards.lists@gmail.com>\n    Aryeh Leib Taurog <http://www.aryehleib.com/>\n    A S Alam <aalam@users.sf.net>\n    Asif Saif Uddin <auvipy@gmail.com>\n    atlithorn <atlithorn@gmail.com>\n    Audrey Roy <http://audreymroy.com/>\n    av0000@mail.ru\n    Axel Haustant <noirbizarre@gmail.com>\n    Aymeric Augustin <aymeric.augustin@m4x.org>\n    Bahadır Kandemir <bahadir@pardus.org.tr>\n    Baishampayan Ghose\n    Baptiste Mispelon <bmispelon@gmail.com>\n    Barry Pederson <bp@barryp.org>\n    Bartolome Sanchez Salado <i42sasab@uco.es>\n    Bartosz Grabski <bartosz.grabski@gmail.com>\n    Bashar Al-Abdulhadi\n    Bastian Kleineidam <calvin@debian.org>\n    Batiste Bieler <batiste.bieler@gmail.com>\n    Batman\n    Batuhan Taskaya <batuhanosmantaskaya@gmail.com>\n    Baurzhan Ismagulov <ibr@radix50.net>\n    Ben Dean Kawamura <ben.dean.kawamura@gmail.com>\n    Ben Firshman <ben@firshman.co.uk>\n    Ben Godfrey <http://aftnn.org>\n    Benjamin Wohlwend <piquadrat@gmail.com>\n    Ben Khoo <khoobks@westnet.com.au>\n    Ben Slavin <benjamin.slavin@gmail.com>\n    Ben Sturmfels <ben@sturm.com.au>\n    Berker Peksag <berker.peksag@gmail.com>\n    Bernd Schlapsi\n    Bernhard Essl <me@bernhardessl.com>\n    berto\n    Bill Fenner <fenner@gmail.com>\n    Bjørn Stabell <bjorn@exoweb.net>\n    Bo Marchman <bo.marchman@gmail.com>\n    Bogdan Mateescu\n    Bojan Mihelac <bmihelac@mihelac.org>\n    Bouke Haarsma <bouke@haarsma.eu>\n    Božidar Benko <bbenko@gmail.com>\n    Brad Melin <melinbrad@gmail.com>\n    Brandon Chinn <https://brandonchinn178.github.io/>\n    Brant Harris\n    Brendan Hayward <brendanhayward85@gmail.com>\n    Brendan Quinn <brendan@cluefulmedia.com>\n    Brenton Simpson <http://theillustratedlife.com>\n    Brett Cannon <brett@python.org>\n    Brett Hoerner <bretthoerner@bretthoerner.com>\n    Brian Beck <http://blog.brianbeck.com/>\n    Brian Fabian Crain <http://www.bfc.do/>\n    Brian Harring <ferringb@gmail.com>\n    Brian Ray <http://brianray.chipy.org/>\n    Brian Rosner <brosner@gmail.com>\n    Bruce Kroeze <https://coderseye.com/>\n    Bruno Alla <alla.brunoo@gmail.com>\n    Bruno Renié <buburno@gmail.com>\n    brut.alll@gmail.com\n    Bryan Chow <bryan at verdjn dot com>\n    Bryan Veloso <bryan@revyver.com>\n    bthomas\n    btoll@bestweb.net\n    C8E\n    Caio Ariede <caio.ariede@gmail.com>\n    Calvin Spealman <ironfroggy@gmail.com>\n    Cameron Curry\n    Cameron Knight (ckknight)\n    Can Burak Çilingir <canburak@cs.bilgi.edu.tr>\n    Can Sarıgöl <ertugrulsarigol@gmail.com>\n    Carl Meyer <carl@oddbird.net>\n    Carles Pina i Estany <carles@pina.cat>\n    Carlos Eduardo de Paula <carlosedp@gmail.com>\n    Carlos Matías de la Torre <cmdelatorre@gmail.com>\n    Carlton Gibson <carlton.gibson@noumenal.es>\n    cedric@terramater.net\n    Chad Whitman <chad.whitman@icloud.com>\n    ChaosKCW\n    Charlie Leifer <coleifer@gmail.com>\n    charly.wilhelm@gmail.com\n    Chason Chaffin <chason@gmail.com>\n    Cheng Zhang\n    Chris Adams\n    Chris Beaven <smileychris@gmail.com>\n    Chris Bennett <chrisrbennett@yahoo.com>\n    Chris Cahoon <chris.cahoon@gmail.com>\n    Chris Chamberlin <dja@cdc.msbx.net>\n    Chris Jerdonek\n    Chris Jones <chris@brack3t.com>\n    Chris Lamb <chris@chris-lamb.co.uk>\n    Chris Streeter <chris@chrisstreeter.com>\n    Christian Barcenas <christian@cbarcenas.com>\n    Christian Metts\n    Christian Oudard <christian.oudard@gmail.com>\n    Christian Tanzer <tanzer@swing.co.at>\n    Christoffer Sjöbergsson\n    Christophe Pettus <xof@thebuild.com>\n    Christopher Adams <http://christopheradams.info>\n    Christopher Babiak <chrisbabiak@gmail.com>\n    Christopher Lenz <https://www.cmlenz.net/>\n    Christoph Mędrela <chris.medrela@gmail.com>\n    Chris Wagner <cw264701@ohio.edu>\n    Chris Wesseling <Chris.Wesseling@cwi.nl>\n    Chris Wilson <chris+github@qwirx.com>\n    Claude Paroz <claude@2xlibre.net>\n    Clint Ecker\n    colin@owlfish.com\n    Colin Wood <cwood06@gmail.com>\n    Collin Anderson <cmawebsite@gmail.com>\n    Collin Grady <collin@collingrady.com>\n    Colton Hicks <coltonbhicks@gmail.com>\n    Craig Blaszczyk <masterjakul@gmail.com>\n    crankycoder@gmail.com\n    Curtis Maloney (FunkyBob) <curtis@tinbrain.net>\n    dackze+django@gmail.com\n    Dagur Páll Ammendrup <dagurp@gmail.com>\n    Dane Springmeyer\n    Dan Fairs <dan@fezconsulting.com>\n    Daniel Alves Barbosa de Oliveira Vaz <danielvaz@gmail.com>\n    Daniel Duan <DaNmarner@gmail.com>\n    Daniele Procida <daniele@vurt.org>\n    Daniel Greenfeld\n    dAniel hAhler\n    Daniel Jilg <daniel@breakthesystem.org>\n    Daniel Lindsley <daniel@toastdriven.com>\n    Daniel Poelzleithner <https://poelzi.org/>\n    Daniel Pyrathon <pirosb3@gmail.com>\n    Daniel Roseman <http://roseman.org.uk/>\n    Daniel Tao <https://philosopherdeveloper.com/>\n    Daniel Wiesmann <daniel.wiesmann@gmail.com>\n    Danilo Bargen\n    Dan Johnson <danj.py@gmail.com>\n    Dan Palmer <dan@danpalmer.me>\n    Dan Poirier <poirier@pobox.com>\n    Dan Stephenson <http://dan.io/>\n    Dan Watson <http://danwatson.net/>\n    dave@thebarproject.com\n    David Ascher <https://ascher.ca/>\n    David Avsajanishvili <avsd05@gmail.com>\n    David Blewett <david@dawninglight.net>\n    David Brenneman <http://davidbrenneman.com>\n    David Cramer <dcramer@gmail.com>\n    David Danier <david.danier@team23.de>\n    David Eklund\n    David Foster <david@dafoster.net>\n    David Gouldin <dgouldin@gmail.com>\n    david@kazserve.org\n    David Krauth\n    David Larlet <https://larlet.fr/david/>\n    David Reynolds <david@reynoldsfamily.org.uk>\n    David Sanders <dsanders11@ucsbalum.com>\n    David Schein\n    David Tulig <david.tulig@gmail.com>\n    David Wobrock <david.wobrock@gmail.com>\n    Davide Ceretti <dav.ceretti@gmail.com>\n    Deep L. Sukhwani <deepsukhwani@gmail.com>\n    Deepak Thukral <deep.thukral@gmail.com>\n    Denis Kuzmichyov <kuzmichyov@gmail.com>\n    Dennis Schwertel <dennisschwertel@gmail.com>\n    Derek Willis <http://blog.thescoop.org/>\n    Deric Crago <deric.crago@gmail.com>\n    deric@monowerks.com\n    Deryck Hodge <http://www.devurandom.org/>\n    Dimitris Glezos <dimitris@glezos.com>\n    Dirk Datzert <dummy@habmalnefrage.de>\n    Dirk Eschler <dirk.eschler@gmx.net>\n    Dmitri Fedortchenko <zeraien@gmail.com>\n    Dmitry Jemerov <intelliyole@gmail.com>\n    dne@mayonnaise.net\n    Dolan Antenucci <antenucci.d@gmail.com>\n    Donald Harvey <donald@donaldharvey.co.uk>\n    Donald Stufft <donald@stufft.io>\n    Don Spaulding <donspauldingii@gmail.com>\n    Doug Beck <doug@douglasbeck.com>\n    Doug Napoleone <doug@dougma.com>\n    dready <wil@mojipage.com>\n    dusk@woofle.net\n    Dustyn Gibson <miigotu@gmail.com>\n    Ed Morley <https://github.com/edmorley>\n    eibaan@gmail.com\n    elky <http://elky.me/>\n    Emmanuelle Delescolle <https://github.com/nanuxbe>\n    Emil Stenström <em@kth.se>\n    enlight\n    Enrico <rico.bl@gmail.com>\n    Eric Boersma <eric.boersma@gmail.com>\n    Eric Brandwein <brandweineric@gmail.com>\n    Eric Floehr <eric@intellovations.com>\n    Eric Florenzano <floguy@gmail.com>\n    Eric Holscher <http://ericholscher.com>\n    Eric Moritz <http://eric.themoritzfamily.com/>\n    Eric Palakovich Carr <carreric@gmail.com>\n    Erik Karulf <erik@karulf.com>\n    Erik Romijn <django@solidlinks.nl>\n    eriks@win.tue.nl\n    Erwin Junge <erwin@junge.nl>\n    Esdras Beleza <linux@esdrasbeleza.com>\n    Espen Grindhaug <http://grindhaug.org/>\n    Eugene Lazutkin <http://lazutkin.com/blog/>\n    Evan Grim <https://github.com/egrim>\n    Fabrice Aneche <akh@nobugware.com>\n    Farhaan Bukhsh <farhaan.bukhsh@gmail.com>\n    favo@exoweb.net\n    fdr <drfarina@gmail.com>\n    Federico Capoano <nemesis@ninux.org>\n    Felipe Lee <felipe.lee.garcia@gmail.com>\n    Filip Noetzel <http://filip.noetzel.co.uk/>\n    Filip Wasilewski <filip.wasilewski@gmail.com>\n    Finn Gruwier Larsen <finn@gruwier.dk>\n    Flávio Juvenal da Silva Junior <flavio@vinta.com.br>\n    flavio.curella@gmail.com\n    Florian Apolloner <florian@apolloner.eu>\n    Florian Moussous <florian.moussous@gmail.com>\n    Fran Hrženjak <fran.hrzenjak@gmail.com>\n    Francisco Albarran Cristobal <pahko.xd@gmail.com>\n    Francisco Couzo <franciscouzo@gmail.com>\n    François Freitag <mail@franek.fr>\n    Frank Tegtmeyer <fte@fte.to>\n    Frank Wierzbicki\n    Frank Wiles <frank@revsys.com>\n    František Malina <fmalina@gmail.com>\n    Fraser Nevett <mail@nevett.org>\n    Gabriel Grant <g@briel.ca>\n    Gabriel Hurley <gabriel@strikeawe.com>\n    gandalf@owca.info\n    Garry Lawrence\n    Garry Polley <garrympolley@gmail.com>\n    Garth Kidd <http://www.deadlybloodyserious.com/>\n    Gary Wilson <gary.wilson@gmail.com>\n    Gasper Koren\n    Gasper Zejn <zejn@kiberpipa.org>\n    Gavin Wahl <gavinwahl@gmail.com>\n    Ge Hanbin <xiaomiba0904@gmail.com>\n    geber@datacollect.com\n    Geert Vanderkelen\n    George Karpenkov <george@metaworld.ru>\n    George Song <george@damacy.net>\n    George Vilches <gav@thataddress.com>\n    Georg \"Hugo\" Bauer <gb@hugo.westfalen.de>\n    Georgi Stanojevski <glisha@gmail.com>\n    Gerardo Orozco <gerardo.orozco.mosqueda@gmail.com>\n    Gil Gonçalves <lursty@gmail.com>\n    Girish Kumar <girishkumarkh@gmail.com>\n    Gisle Aas <gisle@aas.no>\n    Glenn Maynard <glenn@zewt.org>\n    glin@seznam.cz\n    GomoX <gomo@datafull.com>\n    Gonzalo Saavedra <gonzalosaavedra@gmail.com>\n    Gopal Narayanan <gopastro@gmail.com>\n    Graham Carlyle <graham.carlyle@maplecroft.net>\n    Grant Jenks <contact@grantjenks.com>\n    Greg Chapple <gregchapple1@gmail.com>\n    Gregor Allensworth <greg.allensworth@gmail.com>\n    Gregor Müllegger <gregor@muellegger.de>\n    Grigory Fateyev <greg@dial.com.ru>\n    Grzegorz Ślusarek <grzegorz.slusarek@gmail.com>\n    Guilherme Mesquita Gondim <semente@taurinus.org>\n    Guillaume Pannatier <guillaume.pannatier@gmail.com>\n    Gustavo Picon\n    hambaloney\n    Hang Park <hangpark@kaist.ac.kr>\n    Hannes Ljungberg <hannes.ljungberg@gmail.com>\n    Hannes Struß <x@hannesstruss.de>\n    Hasan Ramezani <hasan.r67@gmail.com>\n    Hawkeye\n    Helen Sherwood-Taylor <helen@rrdlabs.co.uk>\n    Henrique Romano <onaiort@gmail.com>\n    Henry Dang <henrydangprg@gmail.com>\n    Hidde Bultsma\n    Himanshu Chauhan <hchauhan1404@outlook.com>\n    hipertracker@gmail.com\n    Hiroki Kiyohara <hirokiky@gmail.com>\n    Honza Král <honza.kral@gmail.com>\n    Horst Gutmann <zerok@zerokspot.com>\n    Hugo Osvaldo Barrera <hugo@barrera.io>\n    HyukJin Jang <wkdgurwls00@naver.com>\n    Hyun Mi Ae\n    Iacopo Spalletti <i.spalletti@nephila.it>\n    Ian A Wilson <http://ianawilson.com>\n    Ian Clelland <clelland@gmail.com>\n    Ian G. Kelly <ian.g.kelly@gmail.com>\n    Ian Holsman <http://feh.holsman.net/>\n    Ian Lee <IanLee1521@gmail.com>\n    Ibon <ibonso@gmail.com>\n    Idan Gazit <idan@gazit.me>\n    Idan Melamed\n    Ifedapo Olarewaju <ifedapoolarewaju@gmail.com>\n    Igor Kolar <ike@email.si>\n    Illia Volochii <illia.volochii@gmail.com>\n    Ilya Semenov <semenov@inetss.com>\n    Ingo Klöcker <djangoproject@ingo-kloecker.de>\n    I.S. van Oostveen <v.oostveen@idca.nl>\n    ivan.chelubeev@gmail.com\n    Ivan Sagalaev (Maniac) <http://www.softwaremaniacs.org/>\n    Jaap Roes <jaap.roes@gmail.com>\n    Jack Moffitt <https://metajack.im/>\n    Jacob Burch <jacobburch@gmail.com>\n    Jacob Green\n    Jacob Kaplan-Moss <jacob@jacobian.org>\n    Jakub Paczkowski <jakub@paczkowski.eu>\n    Jakub Wilk <jwilk@jwilk.net>\n    Jakub Wiśniowski <restless.being@gmail.com>\n    james_027@yahoo.com\n    James Aylett\n    James Bennett <james@b-list.org>\n    James Murty\n    James Tauber <jtauber@jtauber.com>\n    James Timmins <jameshtimmins@gmail.com>\n    James Turk <dev@jamesturk.net>\n    James Wheare <django@sparemint.com>\n    Jannis Leidel <jannis@leidel.info>\n    Janos Guljas\n    Jan Pazdziora\n    Jan Rademaker\n    Jarek Głowacki <jarekwg@gmail.com>\n    Jarek Zgoda <jarek.zgoda@gmail.com>\n    Jason Davies (Esaj) <https://www.jasondavies.com/>\n    Jason Huggins <http://www.jrandolph.com/blog/>\n    Jason McBrayer <http://www.carcosa.net/jason/>\n    jason.sidabras@gmail.com\n    Jason Yan <tailofthesun@gmail.com>\n    Javier Mansilla <javimansilla@gmail.com>\n    Jay Parlar <parlar@gmail.com>\n    Jay Welborn <jesse.welborn@gmail.com>\n    Jay Wineinger <jay.wineinger@gmail.com>\n    J. Clifford Dyer <jcd@sdf.lonestar.org>\n    jcrasta@gmail.com\n    jdetaeye\n    Jeff Anderson <jefferya@programmerq.net>\n    Jeff Balogh <jbalogh@mozilla.com>\n    Jeff Hui <jeffkhui@gmail.com>\n    Jeffrey Gelens <jeffrey@gelens.org>\n    Jeff Triplett <jeff.triplett@gmail.com>\n    Jeffrey Yancey <jeffrey.yancey@gmail.com>\n    Jens Diemer <django@htfx.de>\n    Jens Page\n    Jensen Cochran <jensen.cochran@gmail.com>\n    Jeong-Min Lee <falsetru@gmail.com>\n    Jérémie Blaser <blaserje@gmail.com>\n    Jeremy Bowman <https://github.com/jmbowman>\n    Jeremy Carbaugh <jcarbaugh@gmail.com>\n    Jeremy Dunck <jdunck@gmail.com>\n    Jeremy Lainé <jeremy.laine@m4x.org>\n    Jesse Young <adunar@gmail.com>\n    Jezeniel Zapanta <jezeniel.zapanta@gmail.com>\n    jhenry <jhenry@theonion.com>\n    Jim Dalton <jim.dalton@gmail.com>\n    Jimmy Song <jaejoon@gmail.com>\n    Jiri Barton\n    Joachim Jablon <ewjoachim@gmail.com>\n    Joao Oliveira <joaoxsouls@gmail.com>\n    Joao Pedro Silva <j.pedro004@gmail.com>\n    Joe Heck <http://www.rhonabwy.com/wp/>\n    Joel Bohman <mail@jbohman.com>\n    Joel Heenan <joelh-django@planetjoel.com>\n    Joel Watts <joel@joelwatts.com>\n    Joe Topjian <http://joe.terrarum.net/geek/code/python/django/>\n    Johan C. Stöver <johan@nilling.nl>\n    Johann Queuniet <johann.queuniet@adh.naellia.eu>\n    john@calixto.net\n    John D'Agostino <john.dagostino@gmail.com>\n    John D'Ambrosio <dambrosioj@gmail.com>\n    John Huddleston <huddlej@wwu.edu>\n    John Moses <moses.john.r@gmail.com>\n    John Paulett <john@paulett.org>\n    John Shaffer <jshaffer2112@gmail.com>\n    Jökull Sólberg Auðunsson <jokullsolberg@gmail.com>\n    Jon Dufresne <jon.dufresne@gmail.com>\n    Jonas Haag <jonas@lophus.org>\n    Jonatas C. D. <jonatas.cd@gmail.com>\n    Jonathan Buchanan <jonathan.buchanan@gmail.com>\n    Jonathan Daugherty (cygnus) <http://www.cprogrammer.org/>\n    Jonathan Feignberg <jdf@pobox.com>\n    Jonathan Slenders\n    Jordan Dimov <s3x3y1@gmail.com>\n    Jordi J. Tablada <jordi.joan@gmail.com>\n    Jorge Bastida <me@jorgebastida.com>\n    Jorge Gajon <gajon@gajon.org>\n    José Tomás Tocino García <josetomas.tocino@gmail.com>\n    Josef Rousek <josef.rousek@gmail.com>\n    Joseph Kocherhans <joseph@jkocherhans.com>\n    Josh Smeaton <josh.smeaton@gmail.com>\n    Joshua Cannon <joshdcannon@gmail.com>\n    Joshua Ginsberg <jag@flowtheory.net>\n    Jozko Skrablin <jozko.skrablin@gmail.com>\n    J. Pablo Fernandez <pupeno@pupeno.com>\n    jpellerin@gmail.com\n    Juan Catalano <catalanojuan@gmail.com>\n    Juan Manuel Caicedo <juan.manuel.caicedo@gmail.com>\n    Juan Pedro Fisanotti <fisadev@gmail.com>\n    Julia Elman\n    Julia Matsieva <julia.matsieva@gmail.com>\n    Julian Bez\n    Julien Phalip <jphalip@gmail.com>\n    Junyoung Choi <cupjoo@gmail.com>\n    junzhang.jn@gmail.com\n    Jure Cuhalev <gandalf@owca.info>\n    Justin Bronn <jbronn@gmail.com>\n    Justine Tunney <jtunney@gmail.com>\n    Justin Lilly <justinlilly@gmail.com>\n    Justin Michalicek <jmichalicek@gmail.com>\n    Justin Myles Holmes <justin@slashrootcafe.com>\n    Jyrki Pulliainen <jyrki.pulliainen@gmail.com>\n    Kadesarin Sanjek\n    Karderio <karderio@gmail.com>\n    Karen Tracey <kmtracey@gmail.com>\n    Karol Sikora <elektrrrus@gmail.com>\n    Katherine “Kati” Michel <kthrnmichel@gmail.com>\n    Kathryn Killebrew <kathryn.killebrew@gmail.com>\n    Katie Miller <katie@sub50.com>\n    Keith Bussell <kbussell@gmail.com>\n    Kenneth Love <kennethlove@gmail.com>\n    Kent Hauser <kent@khauser.net>\n    Kevin Grinberg <kevin@kevingrinberg.com>\n    Kevin Kubasik <kevin@kubasik.net>\n    Kevin McConnell <kevin.mcconnell@gmail.com>\n    Kieran Holland <http://www.kieranholland.com>\n    kilian <kilian.cavalotti@lip6.fr>\n    Kim Joon Hwan 김준환 <xncbf12@gmail.com>\n    Klaas van Schelven <klaas@vanschelven.com>\n    knox <christobzr@gmail.com>\n    konrad@gwu.edu\n    Kowito Charoenratchatabhan <kowito@felspar.com>\n    Krišjānis Vaiders <krisjanisvaiders@gmail.com>\n    krzysiek.pawlik@silvermedia.pl\n    Krzysztof Jurewicz <krzysztof.jurewicz@gmail.com>\n    Krzysztof Kulewski <kulewski@gmail.com>\n    kurtiss@meetro.com\n    Lakin Wecker <lakin@structuredabstraction.com>\n    Lars Yencken <lars.yencken@gmail.com>\n    Lau Bech Lauritzen\n    Laurent Luce <https://www.laurentluce.com/>\n    Laurent Rahuel <laurent.rahuel@gmail.com>\n    lcordier@point45.com\n    Leah Culver <leah.culver@gmail.com>\n    Leandra Finger <leandra.finger@gmail.com>\n    Lee Reilly <lee@leereilly.net>\n    Lee Sanghyuck <shlee322@elab.kr>\n    Leo \"hylje\" Honkanen <sealage@gmail.com>\n    Leo Shklovskii\n    Leo Soto <leo.soto@gmail.com>\n    lerouxb@gmail.com\n    Lex Berezhny <lex@damoti.com>\n    Liang Feng <hutuworm@gmail.com>\n    limodou\n    Lincoln Smith <lincoln.smith@anu.edu.au>\n    Liu Yijie <007gzs@gmail.com>\n    Loek van Gent <loek@barakken.nl>\n    Loïc Bistuer <loic.bistuer@sixmedia.com>\n    Lowe Thiderman <lowe.thiderman@gmail.com>\n    Luan Pablo <luanpab@gmail.com>\n    Lucas Connors <https://www.revolutiontech.ca/>\n    Luciano Ramalho\n    Ludvig Ericson <ludvig.ericson@gmail.com>\n    Luis C. Berrocal <luis.berrocal.1942@gmail.com>\n    Łukasz Langa <lukasz@langa.pl>\n    Łukasz Rekucki <lrekucki@gmail.com>\n    Luke Granger-Brown <django@lukegb.com>\n    Luke Plant <L.Plant.98@cantab.net>\n    Maciej Fijalkowski\n    Maciej Wiśniowski <pigletto@gmail.com>\n    Mads Jensen <https://github.com/atombrella>\n    Makoto Tsuyuki <mtsuyuki@gmail.com>\n    Malcolm Tredinnick\n    Manuel Saelices <msaelices@yaco.es>\n    Manuzhai\n    Marc Aymerich Gubern\n    Marc Egli <frog32@me.com>\n    Marcel Telka <marcel@telka.sk>\n    Marc Fargas <telenieko@telenieko.com>\n    Marc Garcia <marc.garcia@accopensys.com>\n    Marcin Wróbel\n    Marc Remolt <m.remolt@webmasters.de>\n    Marc Tamlyn <marc.tamlyn@gmail.com>\n    Marc-Aurèle Brothier <ma.brothier@gmail.com>\n    Marian Andre <django@andre.sk>\n    Marijn Vriens <marijn@metronomo.cl>\n    Mario Gonzalez <gonzalemario@gmail.com>\n    Mariusz Felisiak <felisiak.mariusz@gmail.com>\n    Mark Biggers <biggers@utsl.com>\n    Mark Gensler <mark.gensler@protonmail.com>\n    mark@junklight.com\n    Mark Lavin <markdlavin@gmail.com>\n    Mark Sandstrom <mark@deliciouslynerdy.com>\n    Markus Amalthea Magnuson <markus.magnuson@gmail.com>\n    Markus Holtermann <https://markusholtermann.eu>\n    Marten Kenbeek <marten.knbk+django@gmail.com>\n    Marti Raudsepp <marti@juffo.org>\n    martin.glueck@gmail.com\n    Martin Green\n    Martin Kosír <martin@martinkosir.net>\n    Martin Mahner <https://www.mahner.org/>\n    Martin Maney <http://www.chipy.org/Martin_Maney>\n    Martin von Gagern <gagern@google.com>\n    Mart Sõmermaa <http://mrts.pri.ee/>\n    Marty Alchin <gulopine@gamemusic.org>\n    Masashi Shibata <m.shibata1020@gmail.com>\n    masonsimon+django@gmail.com\n    Massimiliano Ravelli <massimiliano.ravelli@gmail.com>\n    Massimo Scamarcia <massimo.scamarcia@gmail.com>\n    Mathieu Agopian <mathieu.agopian@gmail.com>\n    Matías Bordese\n    Matt Boersma <matt@sprout.org>\n    Matt Croydon <http://www.postneo.com/>\n    Matt Deacalion Stevens <matt@dirtymonkey.co.uk>\n    Matt Dennenbaum\n    Matthew Flanagan <https://wadofstuff.blogspot.com/>\n    Matthew Schinckel <matt@schinckel.net>\n    Matthew Somerville <matthew-django@dracos.co.uk>\n    Matthew Tretter <m@tthewwithanm.com>\n    Matthew Wilkes <matt@matthewwilkes.name>\n    Matthias Kestenholz <mk@406.ch>\n    Matthias Pronk <django@masida.nl>\n    Matt Hoskins <skaffenuk@googlemail.com>\n    Matt McClanahan <https://mmcc.cx/>\n    Matt Riggott\n    Matt Robenolt <m@robenolt.com>\n    Mattia Larentis <mattia@laretis.eu>\n    Mattia Procopio <promat85@gmail.com>\n    Mattias Loverot <mattias@stubin.se>\n    mattycakes@gmail.com\n    Max Burstein <http://maxburstein.com>\n    Max Derkachev <mderk@yandex.ru>\n    Maxime Lorant <maxime.lorant@gmail.com>\n    Maxime Turcotte <maxocub@riseup.net>\n    Maximilian Merz <django@mxmerz.de>\n    Maximillian Dornseif <md@hudora.de>\n    mccutchen@gmail.com\n    Meir Kriheli <http://mksoft.co.il/>\n    Michael Hall <mhall1@ualberta.ca>\n    Michael Josephson <http://www.sdjournal.com/>\n    Michael Manfre <mmanfre@gmail.com>\n    michael.mcewan@gmail.com\n    Michael Placentra II <someone@michaelplacentra2.net>\n    Michael Radziej <mir@noris.de>\n    Michael Sanders <m.r.sanders@gmail.com>\n    Michael Schwarz <michi.schwarz@gmail.com>\n    Michael Sinov <sihaelov@gmail.com>\n    Michael Thornhill <michael.thornhill@gmail.com>\n    Michal Chruszcz <troll@pld-linux.org>\n    michal@plovarna.cz\n    Michał Modzelewski <michal.modzelewski@gmail.com>\n    Mihai Damian <yang_damian@yahoo.com>\n    Mihai Preda <mihai_preda@yahoo.com>\n    Mikaël Barbero <mikael.barbero nospam at nospam free.fr>\n    Mike Axiak <axiak@mit.edu>\n    Mike Grouchy <https://mikegrouchy.com/>\n    Mike Malone <mjmalone@gmail.com>\n    Mike Richardson\n    Mike Wiacek <mjwiacek@google.com>\n    Mikhail Korobov <kmike84@googlemail.com>\n    Mikko Hellsing <mikko@sorl.net>\n    Mikołaj Siedlarek <mikolaj.siedlarek@gmail.com>\n    milkomeda\n    Milton Waddams\n    mitakummaa@gmail.com\n    mmarshall\n    Moayad Mardini <moayad.m@gmail.com>\n    Morgan Aubert <morgan.aubert@zoho.com>\n    Moritz Sichert <moritz.sichert@googlemail.com>\n    Morten Bagai <m@bagai.com>\n    msaelices <msaelices@gmail.com>\n    msundstr\n    Mushtaq Ali <mushtaak@gmail.com>\n    Mykola Zamkovoi <nickzam@gmail.com>\n    Nadège Michel <michel.nadege@gmail.com>\n    Nagy Károly <charlie@rendszergazda.com>\n    Nasimul Haque <nasim.haque@gmail.com>\n    Nasir Hussain <nasirhjafri@gmail.com>\n    Natalia Bidart <nataliabidart@gmail.com>\n    Nate Bragg <jonathan.bragg@alum.rpi.edu>\n    Nathan Gaberel <nathan@gnab.fr>\n    Neal Norwitz <nnorwitz@google.com>\n    Nebojša Dorđević\n    Ned Batchelder <https://nedbatchelder.com/>\n    Nena Kojadin <nena@kiberpipa.org>\n    Niall Dalton <niall.dalton12@gmail.com>\n    Niall Kelly <duke.sam.vimes@gmail.com>\n    Nick Efford <nick@efford.org>\n    Nick Lane <nick.lane.au@gmail.com>\n    Nick Pope <nick@nickpope.me.uk>\n    Nick Presta <nick@nickpresta.ca>\n    Nick Sandford <nick.sandford@gmail.com>\n    Nick Sarbicki <nick.a.sarbicki@gmail.com>\n    Niclas Olofsson <n@niclasolofsson.se>\n    Nicola Larosa <nico@teknico.net>\n    Nicolas Lara <nicolaslara@gmail.com>\n    Nicolas Noé <nicolas@niconoe.eu>\n    Niran Babalola <niran@niran.org>\n    Nis Jørgensen <nis@superlativ.dk>\n    Nowell Strite <https://nowell.strite.org/>\n    Nuno Mariz <nmariz@gmail.com>\n    oggie rob <oz.robharvey@gmail.com>\n    oggy <ognjen.maric@gmail.com>\n    Oliver Beattie <oliver@obeattie.com>\n    Oliver Rutherfurd <http://rutherfurd.net/>\n    Olivier Sels <olivier.sels@gmail.com>\n    Olivier Tabone <olivier.tabone@ripplemotion.fr>\n    Orestis Markou <orestis@orestis.gr>\n    Orne Brocaar <http://brocaar.com/>\n    Oscar Ramirez <tuxskar@gmail.com>\n    Ossama M. Khayat <okhayat@yahoo.com>\n    Owen Griffiths\n    Pablo Martín <goinnn@gmail.com>\n    Panos Laganakos <panos.laganakos@gmail.com>\n    Paolo Melchiorre <paolo@melchiorre.org>\n    Pascal Hartig <phartig@rdrei.net>\n    Pascal Varet\n    Patrik Sletmo <patrik.sletmo@gmail.com>\n    Paul Bissex <http://e-scribe.com/>\n    Paul Collier <paul@paul-collier.com>\n    Paul Collins <paul.collins.iii@gmail.com>\n    Paul Donohue <django@PaulSD.com>\n    Paul Lanier <planier@google.com>\n    Paul McLanahan <paul@mclanahan.net>\n    Paul McMillan <Paul@McMillan.ws>\n    Paulo Poiati <paulogpoiati@gmail.com>\n    Paulo Scardine <paulo@scardine.com.br>\n    Paul Smith <blinkylights23@gmail.com>\n    Pavel Kulikov <kulikovpavel@gmail.com>\n    pavithran s <pavithran.s@gmail.com>\n    Pavlo Kapyshin <i@93z.org>\n    permonik@mesias.brnonet.cz\n    Petar Marić <http://www.petarmaric.com/>\n    Pete Crosier <pete.crosier@gmail.com>\n    peter@mymart.com\n    Peter Sheats <sheats@gmail.com>\n    Peter van Kampen\n    Peter Zsoldos <http://zsoldosp.eu>\n    Pete Shinners <pete@shinners.org>\n    Petr Marhoun <petr.marhoun@gmail.com>\n    pgross@thoughtworks.com\n    phaedo <http://phaedo.cx/>\n    phil.h.smith@gmail.com\n    Philip Lindborg <philip.lindborg@gmail.com>\n    Philippe Raoult <philippe.raoult@n2nsoft.com>\n    phil@produxion.net\n    Piotr Jakimiak <piotr.jakimiak@gmail.com>\n    Piotr Lewandowski <piotr.lewandowski@gmail.com>\n    plisk\n    polpak@yahoo.com\n    pradeep.gowda@gmail.com\n    Preston Holmes <preston@ptone.com>\n    Preston Timmons <prestontimmons@gmail.com>\n    Priyansh Saxena <askpriyansh@gmail.com>\n    Przemysław Buczkowski <przemub@przemub.pl>\n    Przemysław Suliga <http://suligap.net>\n    Rachel Tobin <rmtobin@me.com>\n    Rachel Willmer <http://www.willmer.com/kb/>\n    Radek Švarz <https://www.svarz.cz/translate/>\n    Raffaele Salmaso <raffaele@salmaso.org>\n    Rajesh Dhawan <rajesh.dhawan@gmail.com>\n    Ramez Ashraf <ramezashraf@gmail.com>\n    Ramin Farajpour Cami <ramin.blackhat@gmail.com>\n    Ramiro Morales <ramiro@rmorales.net>\n    Ramon Saraiva <ramonsaraiva@gmail.com>\n    Ram Rachum <ram@rachum.com>\n    Randy Barlow <randy@electronsweatshop.com>\n    Raphaël Barrois <raphael.barrois@m4x.org>\n    Raphael Michel <mail@raphaelmichel.de>\n    Raúl Cumplido <raulcumplido@gmail.com>\n    Rebecca Smith <rebkwok@gmail.com>\n    Remco Wendt <remco.wendt@gmail.com>\n    Renaud Parent <renaud.parent@gmail.com>\n    Renbi Yu <averybigant@gmail.com>\n    Reza Mohammadi <reza@zeerak.ir>\n    rhettg@gmail.com\n    Ricardo Javier Cárdenes Medina <ricardo.cardenes@gmail.com>\n    ricardojbarrios@gmail.com\n    Riccardo Di Virgilio\n    Riccardo Magliocchetti <riccardo.magliocchetti@gmail.com>\n    Richard Davies <richard.davies@elastichosts.com>\n    Richard House <Richard.House@i-logue.com>\n    Rick Wagner <rwagner@physics.ucsd.edu>\n    Rigel Di Scala <rigel.discala@propylon.com>\n    Robert Coup\n    Robert Myers <myer0052@gmail.com>\n    Roberto Aguilar <roberto@baremetal.io>\n    Robert Rock Howard <http://djangomojo.com/>\n    Robert Wittams\n    Rob Golding-Day <rob@golding-day.com>\n    Rob Hudson <https://rob.cogit8.org/>\n    Rob Nguyen <tienrobertnguyenn@gmail.com>\n    Robin Munn <http://www.geekforgod.com/>\n    Rodrigo Pinheiro Marques de Araújo <fenrrir@gmail.com>\n    Romain Garrigues <romain.garrigues.cs@gmail.com>\n    Ronny Haryanto <https://ronny.haryan.to/>\n    Ross Poulton <ross@rossp.org>\n    Rozza <ross.lawley@gmail.com>\n    Rudolph Froger <rfroger@estrate.nl>\n    Rudy Mutter\n    Rune Rønde Laursen <runerl@skjoldhoej.dk>\n    Russell Cloran <russell@rucus.net>\n    Russell Keith-Magee <russell@keith-magee.com>\n    Russ Webber\n    Ryan Hall <ryanhall989@gmail.com>\n    ryankanno\n    Ryan Kelly <ryan@rfk.id.au>\n    Ryan Niemeyer <https://profiles.google.com/ryan.niemeyer/about>\n    Ryan Petrello <ryan@ryanpetrello.com>\n    Ryan Rubin <ryanmrubin@gmail.com>\n    Ryno Mathee <rmathee@gmail.com>\n    Sachin Jat <sanch.jat@gmail.com>\n    Sage M. Abdullah <https://github.com/laymonage>\n    Sam Newman <http://www.magpiebrain.com/>\n    Sander Dijkhuis <sander.dijkhuis@gmail.com>\n    Sanket Saurav <sanketsaurav@gmail.com>\n    Sanyam Khurana <sanyam.khurana01@gmail.com>\n    Sarthak Mehrish <sarthakmeh03@gmail.com>\n    schwank@gmail.com\n    Scot Hacker <shacker@birdhouse.org>\n    Scott Barr <scott@divisionbyzero.com.au>\n    Scott Fitsimones <scott@airgara.ge>\n    Scott Pashley <github@scottpashley.co.uk>\n    scott@staplefish.com\n    Sean Brant\n    Sebastian Hillig <sebastian.hillig@gmail.com>\n    Sebastian Spiegel <https://www.tivix.com/>\n    Segyo Myung <myungsekyo@gmail.com>\n    Selwin Ong <selwin@ui.co.id>\n    Sengtha Chay <sengtha@e-khmer.com>\n    Senko Rašić <senko.rasic@dobarkod.hr>\n    serbaut@gmail.com\n    Sergei Maertens <sergeimaertens@gmail.com>\n    Sergey Fedoseev <fedoseev.sergey@gmail.com>\n    Sergey Kolosov <m17.admin@gmail.com>\n    Seth Hill <sethrh@gmail.com>\n    Shai Berger <shai@platonix.com>\n    Shannon -jj Behrens <https://www.jjinux.com/>\n    Shawn Milochik <shawn@milochik.com>\n    Silvan Spross <silvan.spross@gmail.com>\n    Simeon Visser <http://simeonvisser.com>\n    Simon Blanchard\n    Simon Charette <charette.s@gmail.com>\n    Simon Greenhill <dev@simon.net.nz>\n    Simon Litchfield <simon@quo.com.au>\n    Simon Meers <simon@simonmeers.com>\n    Simon Williams\n    Simon Willison <simon@simonwillison.net>\n    Sjoerd Job Postmus\n    Slawek Mikula <slawek dot mikula at gmail dot com>\n    sloonz <simon.lipp@insa-lyon.fr>\n    smurf@smurf.noris.de\n    sopel\n    Srinivas Reddy Thatiparthy <thatiparthysreenivas@gmail.com>\n    Stanislas Guerra <stan@slashdev.me>\n    Stanislaus Madueke\n    Stanislav Karpov <work@stkrp.ru>\n    starrynight <cmorgh@gmail.com>\n    Stefan R. Filipek\n    Stefane Fermgier <sf@fermigier.com>\n    Stefano Rivera <stefano@rivera.za.net>\n    Stéphane Raimbault <stephane.raimbault@gmail.com>\n    Stephan Jaekel <steph@rdev.info>\n    Stephen Burrows <stephen.r.burrows@gmail.com>\n    Steven L. Smith (fvox13) <steven@stevenlsmith.com>\n    Steven Noorbergen (Xaroth) <xaroth+django@xaroth.nl>\n    Stuart Langridge <https://www.kryogenix.org/>\n    Subhav Gautam <subhavgautam@yahoo.co.uk>\n    Sujay S Kumar <sujay.skumar141295@gmail.com>\n    Sune Kirkeby <https://ibofobi.dk/>\n    Sung-Jin Hong <serialx.net@gmail.com>\n    SuperJared\n    Susan Tan <susan.tan.fleckerl@gmail.com>\n    Sutrisno Efendi <kangfend@gmail.com>\n    Swaroop C H <http://www.swaroopch.info>\n    Szilveszter Farkas <szilveszter.farkas@gmail.com>\n    Taavi Teska <taaviteska@gmail.com>\n    Tai Lee <real.human@mrmachine.net>\n    Takashi Matsuo <matsuo.takashi@gmail.com>\n    Tareque Hossain <http://www.codexn.com>\n    Taylor Mitchell <taylor.mitchell@gmail.com>\n    Terry Huang <terryh.tp@gmail.com>\n    thebjorn <bp@datakortet.no>\n    Thejaswi Puthraya <thejaswi.puthraya@gmail.com>\n    Thijs van Dien <thijs@vandien.net>\n    Thom Wiggers\n    Thomas Chaumeny <t.chaumeny@gmail.com>\n    Thomas Güttler <hv@tbz-pariv.de>\n    Thomas Kerpe <thomas@kerpe.net>\n    Thomas Sorrel\n    Thomas Steinacher <http://www.eggdrop.ch/>\n    Thomas Stromberg <tstromberg@google.com>\n    Thomas Tanner <tanner@gmx.net>\n    tibimicu@gmx.net\n    Tim Allen <tim@pyphilly.org>\n    Tim Givois <tim.givois.mendez@gmail.com>\n    Tim Graham <timograham@gmail.com>\n    Tim Heap <tim@timheap.me>\n    Tim Saylor <tim.saylor@gmail.com>\n    Tobias Kunze <rixx@cutebit.de>\n    Tobias McNulty <https://www.caktusgroup.com/blog/>\n    tobias@neuyork.de\n    Todd O'Bryan <toddobryan@mac.com>\n    Tom Carrick <https://www.carrick.eu>\n    Tom Christie <tom@tomchristie.com>\n    Tom Forbes <tom@tomforb.es>\n    Tom Insam\n    Tom Tobin\n    Tomáš Ehrlich <tomas.ehrlich@gmail.com>\n    Tomáš Kopeček <permonik@m6.cz>\n    Tome Cvitan <tome@cvitan.com>\n    Tomek Paczkowski <tomek@hauru.eu>\n    Tomer Chachamu\n    Tommy Beadle <tbeadle@gmail.com>\n    Tore Lundqvist <tore.lundqvist@gmail.com>\n    torne-django@wolfpuppy.org.uk\n    Travis Cline <travis.cline@gmail.com>\n    Travis Pinney\n    Travis Swicegood <travis@domain51.com>\n    Travis Terry <tdterry7@gmail.com>\n    Trevor Caira <trevor@caira.com>\n    Trey Long <trey@ktrl.com>\n    tstromberg@google.com\n    tt@gurgle.no\n    Tyler Tarabula <tyler.tarabula@gmail.com>\n    Tyson Clugg <tyson@clugg.net>\n    Tyson Tate <tyson@fallingbullets.com>\n    Unai Zalakain <unai@gisa-elkartea.org>\n    Valentina Mukhamedzhanova <umirra@gmail.com>\n    valtron\n    Vasiliy Stavenko <stavenko@gmail.com>\n    Vasil Vangelovski\n    Vibhu Agarwal <vibhu-agarwal.github.io>\n    Victor Andrée\n    viestards.lists@gmail.com\n    Viktor Danyliuk <v.v.danyliuk@gmail.com>\n    Ville Säävuori <https://www.unessa.net/>\n    Vinay Karanam <https://github.com/vinayinvicible>\n    Vinay Sajip <vinay_sajip@yahoo.co.uk>\n    Vincent Foley <vfoleybourgon@yahoo.ca>\n    Vinny Do <vdo.code@gmail.com>\n    Vitaly Babiy <vbabiy86@gmail.com>\n    Vladimir Kuzma <vladimirkuzma.ch@gmail.com>\n    Vlado <vlado@labath.org>\n    Vsevolod Solovyov\n    Vytis Banaitis <vytis.banaitis@gmail.com>\n    wam-djangobug@wamber.net\n    Wang Chun <wangchun@exoweb.net>\n    Warren Smith <warren@wandrsmith.net>\n    Waylan Limberg <waylan@gmail.com>\n    Wiktor Kołodziej <wiktor@pykonik.org>\n    Wiley Kestner <wiley.kestner@gmail.com>\n    Wiliam Alves de Souza <wiliamsouza83@gmail.com>\n    Will Ayd <william.ayd@icloud.com>\n    William Schwartz <wkschwartz@gmail.com>\n    Will Hardy <django@willhardy.com.au>\n    Wilson Miner <wminer@gmail.com>\n    Wim Glenn <hey@wimglenn.com>\n    wojtek\n    Xavier Francisco <xavier.n.francisco@gmail.com>\n    Xia Kai <https://blog.xiaket.org/>\n    Yann Fouillat <gagaro42@gmail.com>\n    Yann Malet\n    Yasushi Masuda <whosaysni@gmail.com>\n    ye7cakf02@sneakemail.com\n    ymasuda@ethercube.com\n    Yoong Kang Lim <yoongkang.lim@gmail.com>\n    Yusuke Miyazaki <miyazaki.dev@gmail.com>\n    Zac Hatfield-Dodds <zac.hatfield.dodds@gmail.com>\n    Zachary Voase <zacharyvoase@gmail.com>\n    Zach Liu <zachliu@gmail.com>\n    Zach Thompson <zthompson47@gmail.com>\n    Zain Memon\n    Zak Johnson <zakj@nox.cx>\n    Žan Anderle <zan.anderle@gmail.com>\n    Zbigniew Siciarz <zbigniew@siciarz.net>\n    zegor\n    Zeynel Özdemir <ozdemir.zynl@gmail.com>\n    Zlatko Mašek <zlatko.masek@gmail.com>\n    zriv <https://github.com/zriv>\n    <Please alphabetize new entries>\n\nA big THANK YOU goes to:\n\n    Rob Curley and Ralph Gage for letting us open-source Django.\n\n    Frank Wiles for making excellent arguments for open-sourcing, and for\n    his sage sysadmin advice.\n\n    Ian Bicking for convincing Adrian to ditch code generation.\n\n    Mark Pilgrim for \"Dive Into Python\" (https://www.diveinto.org/python3/).\n\n    Guido van Rossum for creating Python.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":68,"nodeType":"Package","repoName":null,"name":"docs/ref/models","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":69,"nodeType":"TextFile","repoName":null,"name":"class.txt","path":"docs/ref/models","text":"=====================\nModel class reference\n=====================\n\n.. currentmodule:: django.db.models\n\nThis document covers features of the :class:`~django.db.models.Model` class.\nFor more information about models, see :doc:`the complete list of Model\nreference guides </ref/models/index>`.\n\nAttributes\n==========\n\n``objects``\n-----------\n\n.. attribute:: Model.objects\n\n    Each non-abstract :class:`~django.db.models.Model` class must have a\n    :class:`~django.db.models.Manager` instance added to it.\n    Django ensures that in your model class you have  at least a\n    default ``Manager`` specified. If you don't add your own ``Manager``,\n    Django will add an attribute ``objects`` containing default\n    :class:`~django.db.models.Manager` instance. If you add your own\n    :class:`~django.db.models.Manager` instance attribute, the default one does\n    not appear. Consider the following example::\n\n        from django.db import models\n\n        class Person(models.Model):\n            # Add manager with another name\n            people = models.Manager()\n\n    For more details on model managers see :doc:`Managers </topics/db/managers>`\n    and :ref:`Retrieving objects <retrieving-objects>`.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":70,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/ref/files","text":"=============\nFile handling\n=============\n\n.. module:: django.core.files\n   :synopsis: File handling and storage\n\n.. toctree::\n   :maxdepth: 2\n\n   file\n   storage\n   uploads\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":71,"nodeType":"TextFile","repoName":null,"name":"renderers.txt","path":"docs/ref/forms","text":"======================\nThe form rendering API\n======================\n\n.. module:: django.forms.renderers\n   :synopsis: Built-in form renderers.\n\nDjango's form widgets are rendered using Django's :doc:`template engines\nsystem </topics/templates>`.\n\nThe form rendering process can be customized at several levels:\n\n* Widgets can specify custom template names.\n* Forms and widgets can specify custom renderer classes.\n* A widget's template can be overridden by a project. (Reusable applications\n  typically shouldn't override built-in templates because they might conflict\n  with a project's custom templates.)\n\n.. _low-level-widget-render-api:\n\nThe low-level render API\n========================\n\nThe rendering of form templates is controlled by a customizable renderer class.\nA custom renderer can be specified by updating the :setting:`FORM_RENDERER`\nsetting. It defaults to\n``'``:class:`django.forms.renderers.DjangoTemplates`\\ ``'``.\n\nYou can also provide a custom renderer by setting the\n:attr:`.Form.default_renderer` attribute or by using the ``renderer`` argument\nof :meth:`.Widget.render`.\n\nUse one of the :ref:`built-in template form renderers\n<built-in-template-form-renderers>` or implement your own. Custom renderers\nmust implement a ``render(template_name, context, request=None)`` method. It\nshould return a rendered templates (as a string) or raise\n:exc:`~django.template.TemplateDoesNotExist`.\n\n.. _built-in-template-form-renderers:\n\nBuilt-in-template form renderers\n================================\n\n``DjangoTemplates``\n-------------------\n\n.. class:: DjangoTemplates\n\nThis renderer uses a standalone\n:class:`~django.template.backends.django.DjangoTemplates`\nengine (unconnected to what you might have configured in the\n:setting:`TEMPLATES` setting). It loads templates first from the built-in form\ntemplates directory in ``django/forms/templates`` and then from the installed\napps' templates directories using the :class:`app_directories\n<django.template.loaders.app_directories.Loader>` loader.\n\nIf you want to render templates with customizations from your\n:setting:`TEMPLATES` setting, such as context processors for example, use the\n:class:`TemplatesSetting` renderer.\n\n``Jinja2``\n----------\n\n.. class:: Jinja2\n\nThis renderer is the same as the :class:`DjangoTemplates` renderer except that\nit uses a :class:`~django.template.backends.jinja2.Jinja2` backend. Templates\nfor the built-in widgets are located in ``django/forms/jinja2`` and installed\napps can provide templates in a ``jinja2`` directory.\n\nTo use this backend, all the widgets in your project and its third-party apps\nmust have Jinja2 templates. Unless you provide your own Jinja2 templates for\nwidgets that don't have any, you can't use this renderer. For example,\n:mod:`django.contrib.admin` doesn't include Jinja2 templates for its widgets\ndue to their usage of Django template tags.\n\n``TemplatesSetting``\n--------------------\n\n.. class:: TemplatesSetting\n\nThis renderer gives you complete control of how widget templates are sourced.\nIt uses :func:`~django.template.loader.get_template` to find widget\ntemplates based on what's configured in the :setting:`TEMPLATES` setting.\n\nUsing this renderer along with the built-in widget templates requires either:\n\n* ``'django.forms'`` in :setting:`INSTALLED_APPS` and at least one engine\n  with :setting:`APP_DIRS=True <TEMPLATES-APP_DIRS>`.\n\n* Adding the built-in widgets templates directory in :setting:`DIRS\n  <TEMPLATES-DIRS>` of one of your template engines. To generate that path::\n\n    import django\n    django.__path__[0] + '/forms/templates'  # or '/forms/jinja2'\n\nUsing this renderer requires you to make sure the form templates your project\nneeds can be located.\n\nContext available in widget templates\n=====================================\n\nWidget templates receive a context from :meth:`.Widget.get_context`. By\ndefault, widgets receive a single value in the context, ``widget``. This is a\ndictionary that contains values like:\n\n* ``name``\n* ``value``\n* ``attrs``\n* ``is_hidden``\n* ``template_name``\n\nSome widgets add further information to the context. For instance, all widgets\nthat subclass ``Input`` defines ``widget['type']`` and :class:`.MultiWidget`\ndefines ``widget['subwidgets']`` for looping purposes.\n\n.. _overriding-built-in-widget-templates:\n\nOverriding built-in widget templates\n====================================\n\nEach widget has a ``template_name`` attribute with a value such as\n``input.html``. Built-in widget templates are stored in the\n``django/forms/widgets`` path. You can provide a custom template for\n``input.html`` by defining ``django/forms/widgets/input.html``, for example.\nSee :ref:`built-in widgets` for the name of each widget's template.\n\nTo override widget templates, you must use the :class:`TemplatesSetting`\nrenderer. Then overriding widget templates works :doc:`the same as\n</howto/overriding-templates>` overriding any other template in your project.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":72,"nodeType":"TextFile","repoName":null,"name":".eslintignore","path":"","text":"**/*.min.js\n**/vendor/**/*.js\ndjango/contrib/gis/templates/**/*.js\nnode_modules/**.js\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":73,"nodeType":"Package","repoName":null,"name":".tx","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":74,"nodeType":"TextFile","repoName":null,"name":"config","path":".tx","text":"[main]\nhost = https://www.transifex.com\nlang_map = sr@latin:sr_Latn, zh_CN:zh_Hans, zh_TW:zh_Hant\n\n[django.core]\nfile_filter = django/conf/locale/<lang>/LC_MESSAGES/django.po\nsource_file = django/conf/locale/en/LC_MESSAGES/django.po\nsource_lang = en\n\n[django.contrib-admin]\nfile_filter = django/contrib/admin/locale/<lang>/LC_MESSAGES/django.po\nsource_file = django/contrib/admin/locale/en/LC_MESSAGES/django.po\nsource_lang = en\n\n[django.contrib-admin-js]\nfile_filter = django/contrib/admin/locale/<lang>/LC_MESSAGES/djangojs.po\nsource_file = django/contrib/admin/locale/en/LC_MESSAGES/djangojs.po\nsource_lang = en\n\n[django.contrib-admindocs]\nfile_filter = django/contrib/admindocs/locale/<lang>/LC_MESSAGES/django.po\nsource_file = django/contrib/admindocs/locale/en/LC_MESSAGES/django.po\nsource_lang = en\n\n[django.contrib-auth]\nfile_filter = django/contrib/auth/locale/<lang>/LC_MESSAGES/django.po\nsource_file = django/contrib/auth/locale/en/LC_MESSAGES/django.po\nsource_lang = en\n\n[django.contrib-contenttypes]\nfile_filter = django/contrib/contenttypes/locale/<lang>/LC_MESSAGES/django.po\nsource_file = django/contrib/contenttypes/locale/en/LC_MESSAGES/django.po\nsource_lang = en\n\n[django.contrib-flatpages]\nfile_filter = django/contrib/flatpages/locale/<lang>/LC_MESSAGES/django.po\nsource_file = django/contrib/flatpages/locale/en/LC_MESSAGES/django.po\nsource_lang = en\n\n[django.contrib-gis]\nfile_filter = django/contrib/gis/locale/<lang>/LC_MESSAGES/django.po\nsource_file = django/contrib/gis/locale/en/LC_MESSAGES/django.po\nsource_lang = en\n\n[django.contrib-humanize]\nfile_filter = django/contrib/humanize/locale/<lang>/LC_MESSAGES/django.po\nsource_file = django/contrib/humanize/locale/en/LC_MESSAGES/django.po\nsource_lang = en\n\n[django.contrib-postgres]\nfile_filter = django/contrib/postgres/locale/<lang>/LC_MESSAGES/django.po\nsource_file = django/contrib/postgres/locale/en/LC_MESSAGES/django.po\nsource_lang = en\n\n[django.contrib-redirects]\nfile_filter = django/contrib/redirects/locale/<lang>/LC_MESSAGES/django.po\nsource_file = django/contrib/redirects/locale/en/LC_MESSAGES/django.po\nsource_lang = en\n\n[django.contrib-sessions]\nfile_filter = django/contrib/sessions/locale/<lang>/LC_MESSAGES/django.po\nsource_file = django/contrib/sessions/locale/en/LC_MESSAGES/django.po\nsource_lang = en\n\n[django.contrib-sites]\nfile_filter = django/contrib/sites/locale/<lang>/LC_MESSAGES/django.po\nsource_file = django/contrib/sites/locale/en/LC_MESSAGES/django.po\nsource_lang = en\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":75,"nodeType":"TextFile","repoName":null,"name":"contents.txt","path":"docs","text":"=============================\nDjango documentation contents\n=============================\n\n.. toctree::\n    :hidden:\n\n    index\n\n.. toctree::\n    :maxdepth: 3\n\n    intro/index\n    topics/index\n    howto/index\n    faq/index\n    ref/index\n    misc/index\n    glossary\n    releases/index\n    internals/index\n\nIndices, glossary and tables\n============================\n\n* :ref:`genindex`\n* :ref:`modindex`\n* :doc:`glossary`\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":76,"nodeType":"TextFile","repoName":null,"name":"fields.txt","path":"docs/ref/forms","text":"===========\nForm fields\n===========\n\n.. module:: django.forms.fields\n   :synopsis: Django's built-in form fields.\n\n.. currentmodule:: django.forms\n\n.. class:: Field(**kwargs)\n\nWhen you create a ``Form`` class, the most important part is defining the\nfields of the form. Each field has custom validation logic, along with a few\nother hooks.\n\n.. method:: Field.clean(value)\n\nAlthough the primary way you'll use ``Field`` classes is in ``Form`` classes,\nyou can also instantiate them and use them directly to get a better idea of\nhow they work. Each ``Field`` instance has a ``clean()`` method, which takes\na single argument and either raises a\n``django.core.exceptions.ValidationError`` exception or returns the clean\nvalue::\n\n    >>> from django import forms\n    >>> f = forms.EmailField()\n    >>> f.clean('foo@example.com')\n    'foo@example.com'\n    >>> f.clean('invalid email address')\n    Traceback (most recent call last):\n    ...\n    ValidationError: ['Enter a valid email address.']\n\n.. _core-field-arguments:\n\nCore field arguments\n====================\n\nEach ``Field`` class constructor takes at least these arguments. Some\n``Field`` classes take additional, field-specific arguments, but the following\nshould *always* be accepted:\n\n``required``\n------------\n\n.. attribute:: Field.required\n\nBy default, each ``Field`` class assumes the value is required, so if you pass\nan empty value -- either ``None`` or the empty string (``\"\"``) -- then\n``clean()`` will raise a ``ValidationError`` exception::\n\n    >>> from django import forms\n    >>> f = forms.CharField()\n    >>> f.clean('foo')\n    'foo'\n    >>> f.clean('')\n    Traceback (most recent call last):\n    ...\n    ValidationError: ['This field is required.']\n    >>> f.clean(None)\n    Traceback (most recent call last):\n    ...\n    ValidationError: ['This field is required.']\n    >>> f.clean(' ')\n    ' '\n    >>> f.clean(0)\n    '0'\n    >>> f.clean(True)\n    'True'\n    >>> f.clean(False)\n    'False'\n\nTo specify that a field is *not* required, pass ``required=False`` to the\n``Field`` constructor::\n\n    >>> f = forms.CharField(required=False)\n    >>> f.clean('foo')\n    'foo'\n    >>> f.clean('')\n    ''\n    >>> f.clean(None)\n    ''\n    >>> f.clean(0)\n    '0'\n    >>> f.clean(True)\n    'True'\n    >>> f.clean(False)\n    'False'\n\nIf a ``Field`` has ``required=False`` and you pass ``clean()`` an empty value,\nthen ``clean()`` will return a *normalized* empty value rather than raising\n``ValidationError``. For ``CharField``, this will be an empty string. For other\n``Field`` classes, it might be ``None``. (This varies from field to field.)\n\nWidgets of required form fields have the ``required`` HTML attribute. Set the\n:attr:`Form.use_required_attribute` attribute to ``False`` to disable it. The\n``required`` attribute isn't included on forms of formsets because the browser\nvalidation may not be correct when adding and deleting formsets.\n\n``label``\n---------\n\n.. attribute:: Field.label\n\nThe ``label`` argument lets you specify the \"human-friendly\" label for this\nfield. This is used when the ``Field`` is displayed in a ``Form``.\n\nAs explained in \"Outputting forms as HTML\" above, the default label for a\n``Field`` is generated from the field name by converting all underscores to\nspaces and upper-casing the first letter. Specify ``label`` if that default\nbehavior doesn't result in an adequate label.\n\nHere's a full example ``Form`` that implements ``label`` for two of its fields.\nWe've specified ``auto_id=False`` to simplify the output::\n\n    >>> from django import forms\n    >>> class CommentForm(forms.Form):\n    ...     name = forms.CharField(label='Your name')\n    ...     url = forms.URLField(label='Your website', required=False)\n    ...     comment = forms.CharField()\n    >>> f = CommentForm(auto_id=False)\n    >>> print(f)\n    <tr><th>Your name:</th><td><input type=\"text\" name=\"name\" required></td></tr>\n    <tr><th>Your website:</th><td><input type=\"url\" name=\"url\"></td></tr>\n    <tr><th>Comment:</th><td><input type=\"text\" name=\"comment\" required></td></tr>\n\n``label_suffix``\n----------------\n\n.. attribute:: Field.label_suffix\n\nThe ``label_suffix`` argument lets you override the form's\n:attr:`~django.forms.Form.label_suffix` on a per-field basis::\n\n    >>> class ContactForm(forms.Form):\n    ...     age = forms.IntegerField()\n    ...     nationality = forms.CharField()\n    ...     captcha_answer = forms.IntegerField(label='2 + 2', label_suffix=' =')\n    >>> f = ContactForm(label_suffix='?')\n    >>> print(f.as_p())\n    <p><label for=\"id_age\">Age?</label> <input id=\"id_age\" name=\"age\" type=\"number\" required></p>\n    <p><label for=\"id_nationality\">Nationality?</label> <input id=\"id_nationality\" name=\"nationality\" type=\"text\" required></p>\n    <p><label for=\"id_captcha_answer\">2 + 2 =</label> <input id=\"id_captcha_answer\" name=\"captcha_answer\" type=\"number\" required></p>\n\n``initial``\n-----------\n\n.. attribute:: Field.initial\n\nThe ``initial`` argument lets you specify the initial value to use when\nrendering this ``Field`` in an unbound ``Form``.\n\nTo specify dynamic initial data, see the :attr:`Form.initial` parameter.\n\nThe use-case for this is when you want to display an \"empty\" form in which a\nfield is initialized to a particular value. For example::\n\n    >>> from django import forms\n    >>> class CommentForm(forms.Form):\n    ...     name = forms.CharField(initial='Your name')\n    ...     url = forms.URLField(initial='http://')\n    ...     comment = forms.CharField()\n    >>> f = CommentForm(auto_id=False)\n    >>> print(f)\n    <tr><th>Name:</th><td><input type=\"text\" name=\"name\" value=\"Your name\" required></td></tr>\n    <tr><th>Url:</th><td><input type=\"url\" name=\"url\" value=\"http://\" required></td></tr>\n    <tr><th>Comment:</th><td><input type=\"text\" name=\"comment\" required></td></tr>\n\nYou may be thinking, why not just pass a dictionary of the initial values as\ndata when displaying the form? Well, if you do that, you'll trigger validation,\nand the HTML output will include any validation errors::\n\n    >>> class CommentForm(forms.Form):\n    ...     name = forms.CharField()\n    ...     url = forms.URLField()\n    ...     comment = forms.CharField()\n    >>> default_data = {'name': 'Your name', 'url': 'http://'}\n    >>> f = CommentForm(default_data, auto_id=False)\n    >>> print(f)\n    <tr><th>Name:</th><td><input type=\"text\" name=\"name\" value=\"Your name\" required></td></tr>\n    <tr><th>Url:</th><td><ul class=\"errorlist\"><li>Enter a valid URL.</li></ul><input type=\"url\" name=\"url\" value=\"http://\" required></td></tr>\n    <tr><th>Comment:</th><td><ul class=\"errorlist\"><li>This field is required.</li></ul><input type=\"text\" name=\"comment\" required></td></tr>\n\nThis is why ``initial`` values are only displayed for unbound forms. For bound\nforms, the HTML output will use the bound data.\n\nAlso note that ``initial`` values are *not* used as \"fallback\" data in\nvalidation if a particular field's value is not given. ``initial`` values are\n*only* intended for initial form display::\n\n    >>> class CommentForm(forms.Form):\n    ...     name = forms.CharField(initial='Your name')\n    ...     url = forms.URLField(initial='http://')\n    ...     comment = forms.CharField()\n    >>> data = {'name': '', 'url': '', 'comment': 'Foo'}\n    >>> f = CommentForm(data)\n    >>> f.is_valid()\n    False\n    # The form does *not* fall back to using the initial values.\n    >>> f.errors\n    {'url': ['This field is required.'], 'name': ['This field is required.']}\n\nInstead of a constant, you can also pass any callable::\n\n    >>> import datetime\n    >>> class DateForm(forms.Form):\n    ...     day = forms.DateField(initial=datetime.date.today)\n    >>> print(DateForm())\n    <tr><th>Day:</th><td><input type=\"text\" name=\"day\" value=\"12/23/2008\" required><td></tr>\n\nThe callable will be evaluated only when the unbound form is displayed, not when it is defined.\n\n``widget``\n----------\n\n.. attribute:: Field.widget\n\nThe ``widget`` argument lets you specify a ``Widget`` class to use when\nrendering this ``Field``. See :doc:`/ref/forms/widgets` for more information.\n\n``help_text``\n-------------\n\n.. attribute:: Field.help_text\n\nThe ``help_text`` argument lets you specify descriptive text for this\n``Field``. If you provide ``help_text``, it will be displayed next to the\n``Field`` when the ``Field`` is rendered by one of the convenience ``Form``\nmethods (e.g., ``as_ul()``).\n\nLike the model field's :attr:`~django.db.models.Field.help_text`, this value\nisn't HTML-escaped in automatically-generated forms.\n\nHere's a full example ``Form`` that implements ``help_text`` for two of its\nfields. We've specified ``auto_id=False`` to simplify the output::\n\n    >>> from django import forms\n    >>> class HelpTextContactForm(forms.Form):\n    ...     subject = forms.CharField(max_length=100, help_text='100 characters max.')\n    ...     message = forms.CharField()\n    ...     sender = forms.EmailField(help_text='A valid email address, please.')\n    ...     cc_myself = forms.BooleanField(required=False)\n    >>> f = HelpTextContactForm(auto_id=False)\n    >>> print(f.as_table())\n    <tr><th>Subject:</th><td><input type=\"text\" name=\"subject\" maxlength=\"100\" required><br><span class=\"helptext\">100 characters max.</span></td></tr>\n    <tr><th>Message:</th><td><input type=\"text\" name=\"message\" required></td></tr>\n    <tr><th>Sender:</th><td><input type=\"email\" name=\"sender\" required><br>A valid email address, please.</td></tr>\n    <tr><th>Cc myself:</th><td><input type=\"checkbox\" name=\"cc_myself\"></td></tr>\n    >>> print(f.as_ul()))\n    <li>Subject: <input type=\"text\" name=\"subject\" maxlength=\"100\" required> <span class=\"helptext\">100 characters max.</span></li>\n    <li>Message: <input type=\"text\" name=\"message\" required></li>\n    <li>Sender: <input type=\"email\" name=\"sender\" required> A valid email address, please.</li>\n    <li>Cc myself: <input type=\"checkbox\" name=\"cc_myself\"></li>\n    >>> print(f.as_p())\n    <p>Subject: <input type=\"text\" name=\"subject\" maxlength=\"100\" required> <span class=\"helptext\">100 characters max.</span></p>\n    <p>Message: <input type=\"text\" name=\"message\" required></p>\n    <p>Sender: <input type=\"email\" name=\"sender\" required> A valid email address, please.</p>\n    <p>Cc myself: <input type=\"checkbox\" name=\"cc_myself\"></p>\n\n``error_messages``\n------------------\n\n.. attribute:: Field.error_messages\n\nThe ``error_messages`` argument lets you override the default messages that the\nfield will raise. Pass in a dictionary with keys matching the error messages you\nwant to override. For example, here is the default error message::\n\n    >>> from django import forms\n    >>> generic = forms.CharField()\n    >>> generic.clean('')\n    Traceback (most recent call last):\n      ...\n    ValidationError: ['This field is required.']\n\nAnd here is a custom error message::\n\n    >>> name = forms.CharField(error_messages={'required': 'Please enter your name'})\n    >>> name.clean('')\n    Traceback (most recent call last):\n      ...\n    ValidationError: ['Please enter your name']\n\nIn the `built-in Field classes`_ section below, each ``Field`` defines the\nerror message keys it uses.\n\n``validators``\n--------------\n\n.. attribute:: Field.validators\n\nThe ``validators`` argument lets you provide a list of validation functions\nfor this field.\n\nSee the :doc:`validators documentation </ref/validators>` for more information.\n\n``localize``\n------------\n\n.. attribute:: Field.localize\n\nThe ``localize`` argument enables the localization of form data input, as well\nas the rendered output.\n\nSee the :doc:`format localization </topics/i18n/formatting>` documentation for\nmore information.\n\n``disabled``\n------------\n\n.. attribute:: Field.disabled\n\nThe ``disabled`` boolean argument, when set to ``True``, disables a form field\nusing the ``disabled`` HTML attribute so that it won't be editable by users.\nEven if a user tampers with the field's value submitted to the server, it will\nbe ignored in favor of the value from the form's initial data.\n\nChecking if the field data has changed\n======================================\n\n``has_changed()``\n-----------------\n\n.. method:: Field.has_changed()\n\nThe ``has_changed()`` method is used to determine if the field value has changed\nfrom the initial value. Returns ``True`` or ``False``.\n\nSee the :class:`Form.has_changed()` documentation for more information.\n\n.. _built-in-fields:\n\nBuilt-in ``Field`` classes\n==========================\n\nNaturally, the ``forms`` library comes with a set of ``Field`` classes that\nrepresent common validation needs. This section documents each built-in field.\n\nFor each field, we describe the default widget used if you don't specify\n``widget``. We also specify the value returned when you provide an empty value\n(see the section on ``required`` above to understand what that means).\n\n``BooleanField``\n----------------\n\n.. class:: BooleanField(**kwargs)\n\n    * Default widget: :class:`CheckboxInput`\n    * Empty value: ``False``\n    * Normalizes to: A Python ``True`` or ``False`` value.\n    * Validates that the value is ``True`` (e.g. the check box is checked) if\n      the field has ``required=True``.\n    * Error message keys: ``required``\n\n    .. note::\n\n        Since all ``Field`` subclasses have ``required=True`` by default, the\n        validation condition here is important. If you want to include a boolean\n        in your form that can be either ``True`` or ``False`` (e.g. a checked or\n        unchecked checkbox), you must remember to pass in ``required=False`` when\n        creating the ``BooleanField``.\n\n``CharField``\n-------------\n\n.. class:: CharField(**kwargs)\n\n    * Default widget: :class:`TextInput`\n    * Empty value: Whatever you've given as :attr:`empty_value`.\n    * Normalizes to: A string.\n    * Uses :class:`~django.core.validators.MaxLengthValidator` and\n      :class:`~django.core.validators.MinLengthValidator` if ``max_length`` and\n      ``min_length`` are provided. Otherwise, all inputs are valid.\n    * Error message keys: ``required``, ``max_length``, ``min_length``\n\n    Has three optional arguments for validation:\n\n    .. attribute:: max_length\n    .. attribute:: min_length\n\n    If provided, these arguments ensure that the string is at most or at least\n    the given length.\n\n    .. attribute:: strip\n\n       If ``True`` (default), the value will be stripped of leading and\n       trailing whitespace.\n\n    .. attribute:: empty_value\n\n       The value to use to represent \"empty\". Defaults to an empty string.\n\n``ChoiceField``\n---------------\n\n.. class:: ChoiceField(**kwargs)\n\n    * Default widget: :class:`Select`\n    * Empty value: ``''`` (an empty string)\n    * Normalizes to: A string.\n    * Validates that the given value exists in the list of choices.\n    * Error message keys: ``required``, ``invalid_choice``\n\n    The ``invalid_choice`` error message may contain ``%(value)s``, which will be\n    replaced with the selected choice.\n\n    Takes one extra argument:\n\n    .. attribute:: choices\n\n        Either an :term:`iterable` of 2-tuples to use as choices for this\n        field, or a callable that returns such an iterable. This argument\n        accepts the same formats as the ``choices`` argument to a model field.\n        See the :ref:`model field reference documentation on choices\n        <field-choices>` for more details. If the argument is a callable, it is\n        evaluated each time the field's form is initialized. Defaults to an\n        empty list.\n\n``TypedChoiceField``\n--------------------\n\n.. class:: TypedChoiceField(**kwargs)\n\n    Just like a :class:`ChoiceField`, except :class:`TypedChoiceField` takes two\n    extra arguments, :attr:`coerce` and :attr:`empty_value`.\n\n    * Default widget: :class:`Select`\n    * Empty value: Whatever you've given as :attr:`empty_value`.\n    * Normalizes to: A value of the type provided by the :attr:`coerce`\n      argument.\n    * Validates that the given value exists in the list of choices and can be\n      coerced.\n    * Error message keys: ``required``, ``invalid_choice``\n\n    Takes extra arguments:\n\n    .. attribute:: coerce\n\n        A function that takes one argument and returns a coerced value. Examples\n        include the built-in ``int``, ``float``, ``bool`` and other types. Defaults\n        to an identity function. Note that coercion happens after input\n        validation, so it is possible to coerce to a value not present in\n        ``choices``.\n\n    .. attribute:: empty_value\n\n        The value to use to represent \"empty.\" Defaults to the empty string;\n        ``None`` is another common choice here. Note that this value will not be\n        coerced by the function given in the ``coerce`` argument, so choose it\n        accordingly.\n\n``DateField``\n-------------\n\n.. class:: DateField(**kwargs)\n\n    * Default widget: :class:`DateInput`\n    * Empty value: ``None``\n    * Normalizes to: A Python ``datetime.date`` object.\n    * Validates that the given value is either a ``datetime.date``,\n      ``datetime.datetime`` or string formatted in a particular date format.\n    * Error message keys: ``required``, ``invalid``\n\n    Takes one optional argument:\n\n    .. attribute:: input_formats\n\n        A list of formats used to attempt to convert a string to a valid\n        ``datetime.date`` object.\n\n    If no ``input_formats`` argument is provided, the default input formats are\n    taken from :setting:`DATE_INPUT_FORMATS` if :setting:`USE_L10N` is\n    ``False``, or from the active locale format ``DATE_INPUT_FORMATS`` key if\n    localization is enabled. See also :doc:`format localization\n    </topics/i18n/formatting>`.\n\n``DateTimeField``\n-----------------\n\n.. class:: DateTimeField(**kwargs)\n\n    * Default widget: :class:`DateTimeInput`\n    * Empty value: ``None``\n    * Normalizes to: A Python ``datetime.datetime`` object.\n    * Validates that the given value is either a ``datetime.datetime``,\n      ``datetime.date`` or string formatted in a particular datetime format.\n    * Error message keys: ``required``, ``invalid``\n\n    Takes one optional argument:\n\n    .. attribute:: input_formats\n\n        A list of formats used to attempt to convert a string to a valid\n        ``datetime.datetime`` object, in addition to ISO 8601 formats.\n\n    The field always accepts strings in ISO 8601 formatted dates or similar\n    recognized by :func:`~django.utils.dateparse.parse_datetime`. Some examples\n    are::\n\n        * '2006-10-25 14:30:59'\n        * '2006-10-25T14:30:59'\n        * '2006-10-25 14:30'\n        * '2006-10-25T14:30'\n        * '2006-10-25T14:30Z'\n        * '2006-10-25T14:30+02:00'\n        * '2006-10-25'\n\n    If no ``input_formats`` argument is provided, the default input formats are\n    taken from :setting:`DATETIME_INPUT_FORMATS` and\n    :setting:`DATE_INPUT_FORMATS` if :setting:`USE_L10N` is ``False``, or from\n    the active locale format ``DATETIME_INPUT_FORMATS`` and\n    ``DATE_INPUT_FORMATS`` keys if localization is enabled. See also\n    :doc:`format localization </topics/i18n/formatting>`.\n\n    .. versionchanged:: 3.1\n\n        Support for ISO 8601 date string parsing (including optional timezone)\n        was added.\n\n        The fallback on ``DATE_INPUT_FORMATS`` in the default ``input_formats``\n        was added.\n\n``DecimalField``\n----------------\n\n.. class:: DecimalField(**kwargs)\n\n    * Default widget: :class:`NumberInput` when :attr:`Field.localize` is\n      ``False``, else :class:`TextInput`.\n    * Empty value: ``None``\n    * Normalizes to: A Python ``decimal``.\n    * Validates that the given value is a decimal. Uses\n      :class:`~django.core.validators.MaxValueValidator` and\n      :class:`~django.core.validators.MinValueValidator` if  ``max_value`` and\n      ``min_value`` are provided. Leading and trailing whitespace is ignored.\n    * Error message keys: ``required``, ``invalid``, ``max_value``,\n      ``min_value``, ``max_digits``, ``max_decimal_places``,\n      ``max_whole_digits``\n\n    The ``max_value`` and ``min_value`` error messages may contain\n    ``%(limit_value)s``, which will be substituted by the appropriate limit.\n    Similarly, the ``max_digits``, ``max_decimal_places`` and\n    ``max_whole_digits`` error messages may contain ``%(max)s``.\n\n    Takes four optional arguments:\n\n    .. attribute:: max_value\n    .. attribute:: min_value\n\n        These control the range of values permitted in the field, and should be\n        given as ``decimal.Decimal`` values.\n\n    .. attribute:: max_digits\n\n        The maximum number of digits (those before the decimal point plus those\n        after the decimal point, with leading zeros stripped) permitted in the\n        value.\n\n    .. attribute:: decimal_places\n\n        The maximum number of decimal places permitted.\n\n``DurationField``\n-----------------\n\n.. class:: DurationField(**kwargs)\n\n    * Default widget: :class:`TextInput`\n    * Empty value: ``None``\n    * Normalizes to: A Python :class:`~python:datetime.timedelta`.\n    * Validates that the given value is a string which can be converted into a\n      ``timedelta``. The value must be between :attr:`datetime.timedelta.min`\n      and :attr:`datetime.timedelta.max`.\n    * Error message keys: ``required``, ``invalid``, ``overflow``.\n\n    Accepts any format understood by\n    :func:`~django.utils.dateparse.parse_duration`.\n\n``EmailField``\n--------------\n\n.. class:: EmailField(**kwargs)\n\n    * Default widget: :class:`EmailInput`\n    * Empty value: ``''`` (an empty string)\n    * Normalizes to: A string.\n    * Uses :class:`~django.core.validators.EmailValidator` to validate that\n      the given value is a valid email address, using a moderately complex\n      regular expression.\n    * Error message keys: ``required``, ``invalid``\n\n    Has two optional arguments for validation, ``max_length`` and ``min_length``.\n    If provided, these arguments ensure that the string is at most or at least the\n    given length.\n\n``FileField``\n-------------\n\n.. class:: FileField(**kwargs)\n\n    * Default widget: :class:`ClearableFileInput`\n    * Empty value: ``None``\n    * Normalizes to: An ``UploadedFile`` object that wraps the file content\n      and file name into a single object.\n    * Can validate that non-empty file data has been bound to the form.\n    * Error message keys: ``required``, ``invalid``, ``missing``, ``empty``,\n      ``max_length``\n\n    Has two optional arguments for validation, ``max_length`` and\n    ``allow_empty_file``. If provided, these ensure that the file name is at\n    most the given length, and that validation will succeed even if the file\n    content is empty.\n\n    To learn more about the ``UploadedFile`` object, see the :doc:`file uploads\n    documentation </topics/http/file-uploads>`.\n\n    When you use a ``FileField`` in a form, you must also remember to\n    :ref:`bind the file data to the form <binding-uploaded-files>`.\n\n    The ``max_length`` error refers to the length of the filename. In the error\n    message for that key, ``%(max)d`` will be replaced with the maximum filename\n    length and ``%(length)d`` will be replaced with the current filename length.\n\n``FilePathField``\n-----------------\n\n.. class:: FilePathField(**kwargs)\n\n    * Default widget: :class:`Select`\n    * Empty value: ``''`` (an empty string)\n    * Normalizes to: A string.\n    * Validates that the selected choice exists in the list of choices.\n    * Error message keys: ``required``, ``invalid_choice``\n\n    The field allows choosing from files inside a certain directory. It takes five\n    extra arguments; only ``path`` is required:\n\n    .. attribute:: path\n\n        The absolute path to the directory whose contents you want listed. This\n        directory must exist.\n\n    .. attribute:: recursive\n\n        If ``False`` (the default) only the direct contents of ``path`` will be\n        offered as choices. If ``True``, the directory will be descended into\n        recursively and all descendants will be listed as choices.\n\n    .. attribute:: match\n\n        A regular expression pattern; only files with names matching this expression\n        will be allowed as choices.\n\n    .. attribute:: allow_files\n\n        Optional.  Either ``True`` or ``False``.  Default is ``True``.  Specifies\n        whether files in the specified location should be included.  Either this or\n        :attr:`allow_folders` must be ``True``.\n\n    .. attribute:: allow_folders\n\n        Optional.  Either ``True`` or ``False``.  Default is ``False``.  Specifies\n        whether folders in the specified location should be included.  Either this or\n        :attr:`allow_files` must be ``True``.\n\n\n``FloatField``\n--------------\n\n.. class:: FloatField(**kwargs)\n\n    * Default widget: :class:`NumberInput` when :attr:`Field.localize` is\n      ``False``, else :class:`TextInput`.\n    * Empty value: ``None``\n    * Normalizes to: A Python float.\n    * Validates that the given value is a float. Uses\n      :class:`~django.core.validators.MaxValueValidator` and\n      :class:`~django.core.validators.MinValueValidator` if ``max_value`` and\n      ``min_value`` are provided. Leading and trailing whitespace is allowed,\n      as in Python's ``float()`` function.\n    * Error message keys: ``required``, ``invalid``, ``max_value``,\n      ``min_value``\n\n    Takes two optional arguments for validation, ``max_value`` and ``min_value``.\n    These control the range of values permitted in the field.\n\n``ImageField``\n--------------\n\n.. class:: ImageField(**kwargs)\n\n    * Default widget: :class:`ClearableFileInput`\n    * Empty value: ``None``\n    * Normalizes to: An ``UploadedFile`` object that wraps the file content\n      and file name into a single object.\n    * Validates that file data has been bound to the form. Also uses\n      :class:`~django.core.validators.FileExtensionValidator` to validate that\n      the file extension is supported by Pillow.\n    * Error message keys: ``required``, ``invalid``, ``missing``, ``empty``,\n      ``invalid_image``\n\n    Using an ``ImageField`` requires that `Pillow`_ is installed with support\n    for the image formats you use. If you encounter a ``corrupt image`` error\n    when you upload an image, it usually means that Pillow doesn't understand\n    its format. To fix this, install the appropriate library and reinstall\n    Pillow.\n\n    When you use an ``ImageField`` on a form, you must also remember to\n    :ref:`bind the file data to the form <binding-uploaded-files>`.\n\n    After the field has been cleaned and validated, the ``UploadedFile``\n    object will have an additional ``image`` attribute containing the Pillow\n    `Image`_ instance used to check if the file was a valid image. Pillow\n    closes the underlying file descriptor after verifying an image, so whilst\n    non-image data attributes, such as ``format``, ``height``, and ``width``,\n    are available, methods that access the underlying image data, such as\n    ``getdata()`` or ``getpixel()``, cannot be used without reopening the file.\n    For example::\n\n        >>> from PIL import Image\n        >>> from django import forms\n        >>> from django.core.files.uploadedfile import SimpleUploadedFile\n        >>> class ImageForm(forms.Form):\n        ...     img = forms.ImageField()\n        >>> file_data = {'img': SimpleUploadedFile('test.png', <file data>)}\n        >>> form = ImageForm({}, file_data)\n        # Pillow closes the underlying file descriptor.\n        >>> form.is_valid()\n        True\n        >>> image_field = form.cleaned_data['img']\n        >>> image_field.image\n        <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=191x287 at 0x7F5985045C18>\n        >>> image_field.image.width\n        191\n        >>> image_field.image.height\n        287\n        >>> image_field.image.format\n        'PNG'\n        >>> image_field.image.getdata()\n        # Raises AttributeError: 'NoneType' object has no attribute 'seek'.\n        >>> image = Image.open(image_field)\n        >>> image.getdata()\n        <ImagingCore object at 0x7f5984f874b0>\n\n    Additionally, ``UploadedFile.content_type`` will be updated with the\n    image's content type if Pillow can determine it, otherwise it will be set\n    to ``None``.\n\n.. _Pillow: https://pillow.readthedocs.io/en/latest/\n.. _Image: https://pillow.readthedocs.io/en/latest/reference/Image.html\n\n``IntegerField``\n----------------\n\n.. class:: IntegerField(**kwargs)\n\n    * Default widget: :class:`NumberInput` when :attr:`Field.localize` is\n      ``False``, else :class:`TextInput`.\n    * Empty value: ``None``\n    * Normalizes to: A Python integer.\n    * Validates that the given value is an integer. Uses\n      :class:`~django.core.validators.MaxValueValidator` and\n      :class:`~django.core.validators.MinValueValidator` if ``max_value`` and\n      ``min_value`` are provided. Leading and trailing whitespace is allowed,\n      as in Python's ``int()`` function.\n    * Error message keys: ``required``, ``invalid``, ``max_value``,\n      ``min_value``\n\n    The ``max_value`` and ``min_value`` error messages may contain\n    ``%(limit_value)s``, which will be substituted by the appropriate limit.\n\n    Takes two optional arguments for validation:\n\n    .. attribute:: max_value\n    .. attribute:: min_value\n\n    These control the range of values permitted in the field.\n\n``JSONField``\n-------------\n\n.. class:: JSONField(encoder=None, decoder=None, **kwargs)\n\n    .. versionadded:: 3.1\n\n    A field which accepts JSON encoded data for a\n    :class:`~django.db.models.JSONField`.\n\n    * Default widget: :class:`Textarea`\n    * Empty value: ``''`` (an empty string)\n    * Normalizes to: A Python representation of the JSON value (usually as a\n      ``dict``, ``list``, or ``None``), depending on :attr:`JSONField.decoder`.\n    * Validates that the given value is a valid JSON.\n    * Error message keys: ``required``, ``invalid``\n\n    Takes two optional arguments:\n\n    .. attribute:: encoder\n\n        A :py:class:`json.JSONEncoder` subclass to serialize data types not\n        supported by the standard JSON serializer (e.g. ``datetime.datetime``\n        or :class:`~python:uuid.UUID`). For example, you can use the\n        :class:`~django.core.serializers.json.DjangoJSONEncoder` class.\n\n        Defaults to ``json.JSONEncoder``.\n\n    .. attribute:: decoder\n\n        A :py:class:`json.JSONDecoder` subclass to deserialize the input. Your\n        deserialization may need to account for the fact that you can't be\n        certain of the input type. For example, you run the risk of returning a\n        ``datetime`` that was actually a string that just happened to be in the\n        same format chosen for ``datetime``\\s.\n\n        The ``decoder`` can be used to validate the input. If\n        :py:class:`json.JSONDecodeError` is raised during the deserialization,\n        a ``ValidationError`` will be raised.\n\n        Defaults to ``json.JSONDecoder``.\n\n    .. note::\n\n        If you use a :class:`ModelForm <django.forms.ModelForm>`, the\n        ``encoder`` and ``decoder`` from :class:`~django.db.models.JSONField`\n        will be used.\n\n    .. admonition:: User friendly forms\n\n        ``JSONField`` is not particularly user friendly in most cases. However,\n        it is a useful way to format data from a client-side widget for\n        submission to the server.\n\n``GenericIPAddressField``\n-------------------------\n\n.. class:: GenericIPAddressField(**kwargs)\n\n    A field containing either an IPv4 or an IPv6 address.\n\n    * Default widget: :class:`TextInput`\n    * Empty value: ``''`` (an empty string)\n    * Normalizes to: A string. IPv6 addresses are normalized as described below.\n    * Validates that the given value is a valid IP address.\n    * Error message keys: ``required``, ``invalid``\n\n    The IPv6 address normalization follows :rfc:`4291#section-2.2` section 2.2,\n    including using the IPv4 format suggested in paragraph 3 of that section, like\n    ``::ffff:192.0.2.0``. For example, ``2001:0::0:01`` would be normalized to\n    ``2001::1``, and ``::ffff:0a0a:0a0a`` to ``::ffff:10.10.10.10``. All characters\n    are converted to lowercase.\n\n    Takes two optional arguments:\n\n    .. attribute:: protocol\n\n        Limits valid inputs to the specified protocol.\n        Accepted values are ``both`` (default), ``IPv4``\n        or ``IPv6``. Matching is case insensitive.\n\n    .. attribute:: unpack_ipv4\n\n        Unpacks IPv4 mapped addresses like ``::ffff:192.0.2.1``.\n        If this option is enabled that address would be unpacked to\n        ``192.0.2.1``. Default is disabled. Can only be used\n        when ``protocol`` is set to ``'both'``.\n\n``MultipleChoiceField``\n-----------------------\n\n.. class:: MultipleChoiceField(**kwargs)\n\n    * Default widget: :class:`SelectMultiple`\n    * Empty value: ``[]`` (an empty list)\n    * Normalizes to: A list of strings.\n    * Validates that every value in the given list of values exists in the list\n      of choices.\n    * Error message keys: ``required``, ``invalid_choice``, ``invalid_list``\n\n    The ``invalid_choice`` error message may contain ``%(value)s``, which will be\n    replaced with the selected choice.\n\n    Takes one extra required argument, ``choices``, as for :class:`ChoiceField`.\n\n``TypedMultipleChoiceField``\n----------------------------\n\n.. class:: TypedMultipleChoiceField(**kwargs)\n\n    Just like a :class:`MultipleChoiceField`, except :class:`TypedMultipleChoiceField`\n    takes two extra arguments, ``coerce`` and ``empty_value``.\n\n    * Default widget: :class:`SelectMultiple`\n    * Empty value: Whatever you've given as ``empty_value``\n    * Normalizes to: A list of values of the type provided by the ``coerce``\n      argument.\n    * Validates that the given values exists in the list of choices and can be\n      coerced.\n    * Error message keys: ``required``, ``invalid_choice``\n\n    The ``invalid_choice`` error message may contain ``%(value)s``, which will be\n    replaced with the selected choice.\n\n    Takes two extra arguments, ``coerce`` and ``empty_value``, as for\n    :class:`TypedChoiceField`.\n\n``NullBooleanField``\n--------------------\n\n.. class:: NullBooleanField(**kwargs)\n\n    * Default widget: :class:`NullBooleanSelect`\n    * Empty value: ``None``\n    * Normalizes to: A Python ``True``, ``False`` or ``None`` value.\n    * Validates nothing (i.e., it never raises a ``ValidationError``).\n\n``RegexField``\n--------------\n\n.. class:: RegexField(**kwargs)\n\n    * Default widget: :class:`TextInput`\n    * Empty value: ``''`` (an empty string)\n    * Normalizes to: A string.\n    * Uses :class:`~django.core.validators.RegexValidator` to validate that\n      the given value matches a certain regular expression.\n    * Error message keys: ``required``, ``invalid``\n\n    Takes one required argument:\n\n    .. attribute:: regex\n\n        A regular expression specified either as a string or a compiled regular\n        expression object.\n\n    Also takes ``max_length``, ``min_length``, and ``strip``, which work just\n    as they do for :class:`CharField`.\n\n    .. attribute:: strip\n\n        Defaults to ``False``. If enabled, stripping will be applied before the\n        regex validation.\n\n``SlugField``\n-------------\n\n.. class:: SlugField(**kwargs)\n\n   * Default widget: :class:`TextInput`\n   * Empty value: ``''`` (an empty string)\n   * Normalizes to: A string.\n   * Uses :class:`~django.core.validators.validate_slug` or\n     :class:`~django.core.validators.validate_unicode_slug` to validate that\n     the given value contains only letters, numbers, underscores, and hyphens.\n   * Error messages: ``required``, ``invalid``\n\n   This field is intended for use in representing a model\n   :class:`~django.db.models.SlugField` in forms.\n\n   Takes an optional parameter:\n\n   .. attribute:: allow_unicode\n\n       A boolean instructing the field to accept Unicode letters in addition\n       to ASCII letters. Defaults to ``False``.\n\n``TimeField``\n-------------\n\n.. class:: TimeField(**kwargs)\n\n    * Default widget: :class:`TimeInput`\n    * Empty value: ``None``\n    * Normalizes to: A Python ``datetime.time`` object.\n    * Validates that the given value is either a ``datetime.time`` or string\n      formatted in a particular time format.\n    * Error message keys: ``required``, ``invalid``\n\n    Takes one optional argument:\n\n    .. attribute:: input_formats\n\n        A list of formats used to attempt to convert a string to a valid\n        ``datetime.time`` object.\n\n    If no ``input_formats`` argument is provided, the default input formats are\n    taken from :setting:`TIME_INPUT_FORMATS` if :setting:`USE_L10N` is\n    ``False``, or from the active locale format ``TIME_INPUT_FORMATS`` key if\n    localization is enabled. See also :doc:`format localization\n    </topics/i18n/formatting>`.\n\n``URLField``\n------------\n\n.. class:: URLField(**kwargs)\n\n    * Default widget: :class:`URLInput`\n    * Empty value: ``''`` (an empty string)\n    * Normalizes to: A string.\n    * Uses :class:`~django.core.validators.URLValidator` to validate that the\n      given value is a valid URL.\n    * Error message keys: ``required``, ``invalid``\n\n    Takes the following optional arguments:\n\n    .. attribute:: max_length\n    .. attribute:: min_length\n\n    These are the same as ``CharField.max_length`` and ``CharField.min_length``.\n\n``UUIDField``\n-------------\n\n.. class:: UUIDField(**kwargs)\n\n    * Default widget: :class:`TextInput`\n    * Empty value: ``''`` (an empty string)\n    * Normalizes to: A :class:`~python:uuid.UUID` object.\n    * Error message keys: ``required``, ``invalid``\n\n    This field will accept any string format accepted as the ``hex`` argument\n    to the :class:`~python:uuid.UUID` constructor.\n\nSlightly complex built-in ``Field`` classes\n===========================================\n\n``ComboField``\n--------------\n\n.. class:: ComboField(**kwargs)\n\n    * Default widget: :class:`TextInput`\n    * Empty value: ``''`` (an empty string)\n    * Normalizes to: A string.\n    * Validates the given value against each of the fields specified\n      as an argument to the ``ComboField``.\n    * Error message keys: ``required``, ``invalid``\n\n    Takes one extra required argument:\n\n    .. attribute:: fields\n\n        The list of fields that should be used to validate the field's value (in\n        the order in which they are provided).\n\n            >>> from django.forms import ComboField\n            >>> f = ComboField(fields=[CharField(max_length=20), EmailField()])\n            >>> f.clean('test@example.com')\n            'test@example.com'\n            >>> f.clean('longemailaddress@example.com')\n            Traceback (most recent call last):\n            ...\n            ValidationError: ['Ensure this value has at most 20 characters (it has 28).']\n\n``MultiValueField``\n-------------------\n\n.. class:: MultiValueField(fields=(), **kwargs)\n\n    * Default widget: :class:`TextInput`\n    * Empty value: ``''`` (an empty string)\n    * Normalizes to: the type returned by the ``compress`` method of the subclass.\n    * Validates the given value against each of the fields specified\n      as an argument to the ``MultiValueField``.\n    * Error message keys: ``required``, ``invalid``, ``incomplete``\n\n    Aggregates the logic of multiple fields that together produce a single\n    value.\n\n    This field is abstract and must be subclassed. In contrast with the\n    single-value fields, subclasses of :class:`MultiValueField` must not\n    implement :meth:`~django.forms.Field.clean` but instead - implement\n    :meth:`~MultiValueField.compress`.\n\n    Takes one extra required argument:\n\n    .. attribute:: fields\n\n        A tuple of fields whose values are cleaned and subsequently combined\n        into a single value.  Each value of the field is cleaned by the\n        corresponding field in ``fields`` -- the first value is cleaned by the\n        first field, the second value is cleaned by the second field, etc.\n        Once all fields are cleaned, the list of clean values is combined into\n        a single value by :meth:`~MultiValueField.compress`.\n\n    Also takes some optional arguments:\n\n    .. attribute:: require_all_fields\n\n        Defaults to ``True``, in which case a ``required`` validation error\n        will be raised if no value is supplied for any field.\n\n        When set to ``False``, the :attr:`Field.required` attribute can be set\n        to ``False`` for individual fields to make them optional. If no value\n        is supplied for a required field, an ``incomplete`` validation error\n        will be raised.\n\n        A default ``incomplete`` error message can be defined on the\n        :class:`MultiValueField` subclass, or different messages can be defined\n        on each individual field. For example::\n\n            from django.core.validators import RegexValidator\n\n            class PhoneField(MultiValueField):\n                def __init__(self, **kwargs):\n                    # Define one message for all fields.\n                    error_messages = {\n                        'incomplete': 'Enter a country calling code and a phone number.',\n                    }\n                    # Or define a different message for each field.\n                    fields = (\n                        CharField(\n                            error_messages={'incomplete': 'Enter a country calling code.'},\n                            validators=[\n                                RegexValidator(r'^[0-9]+$', 'Enter a valid country calling code.'),\n                            ],\n                        ),\n                        CharField(\n                            error_messages={'incomplete': 'Enter a phone number.'},\n                            validators=[RegexValidator(r'^[0-9]+$', 'Enter a valid phone number.')],\n                        ),\n                        CharField(\n                            validators=[RegexValidator(r'^[0-9]+$', 'Enter a valid extension.')],\n                            required=False,\n                        ),\n                    )\n                    super().__init__(\n                        error_messages=error_messages, fields=fields,\n                        require_all_fields=False, **kwargs\n                    )\n\n    .. attribute:: MultiValueField.widget\n\n        Must be a subclass of :class:`django.forms.MultiWidget`.\n        Default value is :class:`~django.forms.TextInput`, which\n        probably is not very useful in this case.\n\n    .. method:: compress(data_list)\n\n        Takes a list of valid values and returns  a \"compressed\" version of\n        those values -- in a single value. For example,\n        :class:`SplitDateTimeField` is a subclass which combines a time field\n        and a date field into a ``datetime`` object.\n\n        This method must be implemented in the subclasses.\n\n``SplitDateTimeField``\n----------------------\n\n.. class:: SplitDateTimeField(**kwargs)\n\n    * Default widget: :class:`SplitDateTimeWidget`\n    * Empty value: ``None``\n    * Normalizes to: A Python ``datetime.datetime`` object.\n    * Validates that the given value is a ``datetime.datetime`` or string\n      formatted in a particular datetime format.\n    * Error message keys: ``required``, ``invalid``, ``invalid_date``,\n      ``invalid_time``\n\n    Takes two optional arguments:\n\n    .. attribute:: input_date_formats\n\n        A list of formats used to attempt to convert a string to a valid\n        ``datetime.date`` object.\n\n    If no ``input_date_formats`` argument is provided, the default input formats\n    for :class:`DateField` are used.\n\n    .. attribute:: input_time_formats\n\n        A list of formats used to attempt to convert a string to a valid\n        ``datetime.time`` object.\n\n    If no ``input_time_formats`` argument is provided, the default input formats\n    for :class:`TimeField` are used.\n\nFields which handle relationships\n=================================\n\nTwo fields are available for representing relationships between\nmodels: :class:`ModelChoiceField` and\n:class:`ModelMultipleChoiceField`.  Both of these fields require a\nsingle ``queryset`` parameter that is used to create the choices for\nthe field.  Upon form validation, these fields will place either one\nmodel object (in the case of ``ModelChoiceField``) or multiple model\nobjects (in the case of ``ModelMultipleChoiceField``) into the\n``cleaned_data`` dictionary of the form.\n\nFor more complex uses, you can specify ``queryset=None`` when declaring the\nform field and then populate the ``queryset`` in the form's ``__init__()``\nmethod::\n\n    class FooMultipleChoiceForm(forms.Form):\n        foo_select = forms.ModelMultipleChoiceField(queryset=None)\n\n        def __init__(self, *args, **kwargs):\n            super().__init__(*args, **kwargs)\n            self.fields['foo_select'].queryset = ...\n\nBoth ``ModelChoiceField`` and ``ModelMultipleChoiceField`` have an ``iterator``\nattribute which specifies the class used to iterate over the queryset when\ngenerating choices. See :ref:`iterating-relationship-choices` for details.\n\n``ModelChoiceField``\n--------------------\n\n.. class:: ModelChoiceField(**kwargs)\n\n    * Default widget: :class:`Select`\n    * Empty value: ``None``\n    * Normalizes to: A model instance.\n    * Validates that the given id exists in the queryset.\n    * Error message keys: ``required``, ``invalid_choice``\n\n    Allows the selection of a single model object, suitable for representing a\n    foreign key. Note that the default widget for ``ModelChoiceField`` becomes\n    impractical when the number of entries increases. You should avoid using it\n    for more than 100 items.\n\n    A single argument is required:\n\n    .. attribute:: queryset\n\n        A ``QuerySet`` of model objects from which the choices for the field\n        are derived and which is used to validate the user's selection. It's\n        evaluated when the form is rendered.\n\n    ``ModelChoiceField`` also takes two optional arguments:\n\n    .. attribute:: empty_label\n\n        By default the ``<select>`` widget used by ``ModelChoiceField`` will have an\n        empty choice at the top of the list. You can change the text of this\n        label (which is ``\"---------\"`` by default) with the ``empty_label``\n        attribute, or you can disable the empty label entirely by setting\n        ``empty_label`` to ``None``::\n\n            # A custom empty label\n            field1 = forms.ModelChoiceField(queryset=..., empty_label=\"(Nothing)\")\n\n            # No empty label\n            field2 = forms.ModelChoiceField(queryset=..., empty_label=None)\n\n        Note that if a ``ModelChoiceField`` is required and has a default\n        initial value, no empty choice is created (regardless of the value\n        of ``empty_label``).\n\n    .. attribute:: to_field_name\n\n        This optional argument is used to specify the field to use as the value\n        of the choices in the field's widget. Be sure it's a unique field for\n        the model, otherwise the selected value could match more than one\n        object. By default it is set to ``None``, in which case the primary key\n        of each object will be used. For example::\n\n            # No custom to_field_name\n            field1 = forms.ModelChoiceField(queryset=...)\n\n        would yield:\n\n        .. code-block:: html\n\n            <select id=\"id_field1\" name=\"field1\">\n            <option value=\"obj1.pk\">Object1</option>\n            <option value=\"obj2.pk\">Object2</option>\n            ...\n            </select>\n\n        and::\n\n            # to_field_name provided\n            field2 = forms.ModelChoiceField(queryset=..., to_field_name=\"name\")\n\n        would yield:\n\n        .. code-block:: html\n\n            <select id=\"id_field2\" name=\"field2\">\n            <option value=\"obj1.name\">Object1</option>\n            <option value=\"obj2.name\">Object2</option>\n            ...\n            </select>\n\n    ``ModelChoiceField`` also has the attribute:\n\n    .. attribute:: iterator\n\n        The iterator class used to generate field choices from ``queryset``. By\n        default, :class:`ModelChoiceIterator`.\n\n    The ``__str__()`` method of the model will be called to generate string\n    representations of the objects for use in the field's choices. To provide\n    customized representations, subclass ``ModelChoiceField`` and override\n    ``label_from_instance``. This method will receive a model object and should\n    return a string suitable for representing it. For example::\n\n        from django.forms import ModelChoiceField\n\n        class MyModelChoiceField(ModelChoiceField):\n            def label_from_instance(self, obj):\n                return \"My Object #%i\" % obj.id\n\n``ModelMultipleChoiceField``\n----------------------------\n\n.. class:: ModelMultipleChoiceField(**kwargs)\n\n    * Default widget: :class:`SelectMultiple`\n    * Empty value: An empty ``QuerySet`` (self.queryset.none())\n    * Normalizes to: A ``QuerySet`` of model instances.\n    * Validates that every id in the given list of values exists in the\n      queryset.\n    * Error message keys: ``required``, ``invalid_list``, ``invalid_choice``,\n      ``invalid_pk_value``\n\n    The ``invalid_choice`` message may contain ``%(value)s`` and the\n    ``invalid_pk_value`` message may contain ``%(pk)s``, which will be\n    substituted by the appropriate values.\n\n    Allows the selection of one or more model objects, suitable for\n    representing a many-to-many relation. As with :class:`ModelChoiceField`,\n    you can use ``label_from_instance`` to customize the object\n    representations.\n\n    A single argument is required:\n\n    .. attribute:: queryset\n\n        Same as :class:`ModelChoiceField.queryset`.\n\n    Takes one optional argument:\n\n    .. attribute:: to_field_name\n\n        Same as :class:`ModelChoiceField.to_field_name`.\n\n    ``ModelMultipleChoiceField`` also has the attribute:\n\n    .. attribute:: iterator\n\n        Same as :class:`ModelChoiceField.iterator`.\n\n.. deprecated:: 3.1\n\n    The ``list`` message is deprecated, use ``invalid_list`` instead.\n\n.. _iterating-relationship-choices:\n\nIterating relationship choices\n------------------------------\n\nBy default, :class:`ModelChoiceField` and :class:`ModelMultipleChoiceField` use\n:class:`ModelChoiceIterator` to generate their field ``choices``.\n\nWhen iterated, ``ModelChoiceIterator`` yields 2-tuple choices containing\n:class:`ModelChoiceIteratorValue` instances as the first ``value`` element in\neach choice. ``ModelChoiceIteratorValue`` wraps the choice value whilst\nmaintaining a reference to the source model instance that can be used in custom\nwidget implementations, for example, to add `data-* attributes`_ to\n``<option>`` elements.\n\n.. _`data-* attributes`: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-*\n\nFor example, consider the following models::\n\n    from django.db import models\n\n    class Topping(models.Model):\n        name = models.CharField(max_length=100)\n        price = models.DecimalField(decimal_places=2, max_digits=6)\n\n        def __str__(self):\n            return self.name\n\n    class Pizza(models.Model):\n        topping = models.ForeignKey(Topping, on_delete=models.CASCADE)\n\nYou can use a :class:`~django.forms.Select` widget subclass to include\nthe value of ``Topping.price`` as the HTML attribute ``data-price`` for each\n``<option>`` element::\n\n    from django import forms\n\n    class ToppingSelect(forms.Select):\n        def create_option(self, name, value, label, selected, index, subindex=None, attrs=None):\n            option = super().create_option(name, value, label, selected, index, subindex, attrs)\n            if value:\n                option['attrs']['data-price'] = value.instance.price\n            return option\n\n    class PizzaForm(forms.ModelForm):\n        class Meta:\n            model = Pizza\n            fields = ['topping']\n            widgets = {'topping': ToppingSelect}\n\nThis will render the ``Pizza.topping`` select as:\n\n.. code-block:: html\n\n    <select id=\"id_topping\" name=\"topping\" required>\n    <option value=\"\" selected>---------</option>\n    <option value=\"1\" data-price=\"1.50\">mushrooms</option>\n    <option value=\"2\" data-price=\"1.25\">onions</option>\n    <option value=\"3\" data-price=\"1.75\">peppers</option>\n    <option value=\"4\" data-price=\"2.00\">pineapple</option>\n    </select>\n\nFor more advanced usage you may subclass ``ModelChoiceIterator`` in order to\ncustomize the yielded 2-tuple choices.\n\n``ModelChoiceIterator``\n~~~~~~~~~~~~~~~~~~~~~~~\n\n.. class:: ModelChoiceIterator(field)\n\n    The default class assigned to the ``iterator`` attribute of\n    :class:`ModelChoiceField` and :class:`ModelMultipleChoiceField`. An\n    iterable that yields 2-tuple choices from the queryset.\n\n    A single argument is required:\n\n    .. attribute:: field\n\n        The instance of ``ModelChoiceField`` or ``ModelMultipleChoiceField`` to\n        iterator and yield choice.\n\n    ``ModelChoiceIterator`` has the following method:\n\n    .. method:: __iter__()\n\n        Yields 2-tuple choices, in the ``(value, label)`` format used by\n        :attr:`ChoiceField.choices`. The first ``value`` element is a\n        :class:`ModelChoiceIteratorValue` instance.\n\n        .. versionchanged:: 3.1\n\n            In older versions, the first ``value`` element in the choice tuple\n            is the ``field`` value itself, rather than a\n            ``ModelChoiceIteratorValue`` instance.\n\n``ModelChoiceIteratorValue``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. class:: ModelChoiceIteratorValue(value, instance)\n\n    .. versionadded:: 3.1\n\n    Two arguments are required:\n\n    .. attribute:: value\n\n        The value of the choice. This value is used to render the ``value``\n        attribute of an HTML ``<option>`` element.\n\n    .. attribute:: instance\n\n        The model instance from the queryset. The instance can be accessed in\n        custom ``ChoiceWidget.create_option()`` implementations to adjust the\n        rendered HTML.\n\n    ``ModelChoiceIteratorValue`` has the following method:\n\n    .. method:: __str__()\n\n        Return ``value`` as a string to be rendered in HTML.\n\nCreating custom fields\n======================\n\nIf the built-in ``Field`` classes don't meet your needs, you can create custom\n``Field`` classes. To do this, create a subclass of ``django.forms.Field``. Its\nonly requirements are that it implement a ``clean()`` method and that its\n``__init__()`` method accept the core arguments mentioned above (``required``,\n``label``, ``initial``, ``widget``, ``help_text``).\n\nYou can also customize how a field will be accessed by overriding\n:meth:`~django.forms.Field.get_bound_field()`.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":77,"nodeType":"TextFile","repoName":null,"name":"models.txt","path":"docs/ref/forms","text":"====================\nModel Form Functions\n====================\n\nModel Form API reference. For introductory material about model forms, see the\n:doc:`/topics/forms/modelforms` topic guide.\n\n.. module:: django.forms.models\n   :synopsis: Django's functions for building model forms and formsets.\n\n``modelform_factory``\n=====================\n\n.. function:: modelform_factory(model, form=ModelForm, fields=None, exclude=None, formfield_callback=None, widgets=None, localized_fields=None, labels=None, help_texts=None, error_messages=None, field_classes=None)\n\n    Returns a :class:`~django.forms.ModelForm` class for the given ``model``.\n    You can optionally pass a ``form`` argument to use as a starting point for\n    constructing the ``ModelForm``.\n\n    ``fields`` is an optional list of field names. If provided, only the named\n    fields will be included in the returned fields.\n\n    ``exclude`` is an optional list of field names. If provided, the named\n    fields will be excluded from the returned fields, even if they are listed\n    in the ``fields`` argument.\n\n    ``formfield_callback`` is a callable that takes a model field and returns\n    a form field.\n\n    ``widgets`` is a dictionary of model field names mapped to a widget.\n\n    ``localized_fields`` is a list of names of fields which should be localized.\n\n    ``labels`` is a dictionary of model field names mapped to a label.\n\n    ``help_texts`` is a dictionary of model field names mapped to a help text.\n\n    ``error_messages`` is a dictionary of model field names mapped to a\n    dictionary of error messages.\n\n    ``field_classes`` is a dictionary of model field names mapped to a form\n    field class.\n\n    See :ref:`modelforms-factory` for example usage.\n\n    You must provide the list of fields explicitly, either via keyword arguments\n    ``fields`` or ``exclude``, or the corresponding attributes on the form's\n    inner ``Meta`` class. See :ref:`modelforms-selecting-fields` for more\n    information. Omitting any definition of the fields to use will result in\n    an :exc:`~django.core.exceptions.ImproperlyConfigured` exception.\n\n``modelformset_factory``\n========================\n\n.. function:: modelformset_factory(model, form=ModelForm, formfield_callback=None, formset=BaseModelFormSet, extra=1, can_delete=False, can_order=False, max_num=None, fields=None, exclude=None, widgets=None, validate_max=False, localized_fields=None, labels=None, help_texts=None, error_messages=None, min_num=None, validate_min=False, field_classes=None)\n\n    Returns a ``FormSet`` class for the given ``model`` class.\n\n    Arguments ``model``, ``form``, ``fields``, ``exclude``,\n    ``formfield_callback``, ``widgets``, ``localized_fields``, ``labels``,\n    ``help_texts``, ``error_messages``, and ``field_classes`` are all passed\n    through to :func:`~django.forms.models.modelform_factory`.\n\n    Arguments ``formset``, ``extra``, ``max_num``, ``can_order``,\n    ``can_delete`` and ``validate_max`` are passed through to\n    :func:`~django.forms.formsets.formset_factory`. See :doc:`formsets\n    </topics/forms/formsets>` for details.\n\n    See :ref:`model-formsets` for example usage.\n\n``inlineformset_factory``\n=========================\n\n.. function:: inlineformset_factory(parent_model, model, form=ModelForm, formset=BaseInlineFormSet, fk_name=None, fields=None, exclude=None, extra=3, can_order=False, can_delete=True, max_num=None, formfield_callback=None, widgets=None, validate_max=False, localized_fields=None, labels=None, help_texts=None, error_messages=None, min_num=None, validate_min=False, field_classes=None)\n\n    Returns an ``InlineFormSet`` using :func:`modelformset_factory` with\n    defaults of ``formset=``:class:`~django.forms.models.BaseInlineFormSet`,\n    ``can_delete=True``, and ``extra=3``.\n\n    If your model has more than one :class:`~django.db.models.ForeignKey` to\n    the ``parent_model``, you must specify a ``fk_name``.\n\n    See :ref:`inline-formsets` for example usage.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":78,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/ref/forms","text":"=====\nForms\n=====\n\nDetailed form API reference. For introductory material, see the\n:doc:`/topics/forms/index` topic guide.\n\n.. toctree::\n   :maxdepth: 2\n\n   api\n   fields\n   models\n   formsets\n   renderers\n   widgets\n   validation\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":79,"nodeType":"TextFile","repoName":null,"name":"validation.txt","path":"docs/ref/forms","text":"=========================\nForm and field validation\n=========================\n\n.. currentmodule:: django.forms\n\nForm validation happens when the data is cleaned. If you want to customize\nthis process, there are various places to make changes, each one serving a\ndifferent purpose. Three types of cleaning methods are run during form\nprocessing. These are normally executed when you call the ``is_valid()``\nmethod on a form. There are other things that can also trigger cleaning and\nvalidation (accessing the ``errors`` attribute or calling ``full_clean()``\ndirectly), but normally they won't be needed.\n\nIn general, any cleaning method can raise ``ValidationError`` if there is a\nproblem with the data it is processing, passing the relevant information to\nthe ``ValidationError`` constructor. :ref:`See below <raising-validation-error>`\nfor the best practice in raising ``ValidationError``. If no ``ValidationError``\nis raised, the method should return the cleaned (normalized) data as a Python\nobject.\n\nMost validation can be done using `validators`_ - helpers that can be reused.\nValidators are functions (or callables) that take a single argument and raise\n``ValidationError`` on invalid input. Validators are run after the field's\n``to_python`` and ``validate`` methods have been called.\n\nValidation of a form is split into several steps, which can be customized or\noverridden:\n\n* The ``to_python()`` method on a ``Field`` is the first step in every\n  validation. It coerces the value to a correct datatype and raises\n  ``ValidationError`` if that is not possible. This method accepts the raw\n  value from the widget and returns the converted value. For example, a\n  ``FloatField`` will turn the data into a Python ``float`` or raise a\n  ``ValidationError``.\n\n* The ``validate()`` method on a ``Field`` handles field-specific validation\n  that is not suitable for a validator. It takes a value that has been\n  coerced to a correct datatype and raises ``ValidationError`` on any error.\n  This method does not return anything and shouldn't alter the value. You\n  should override it to handle validation logic that you can't or don't\n  want to put in a validator.\n\n* The ``run_validators()`` method on a ``Field`` runs all of the field's\n  validators and aggregates all the errors into a single\n  ``ValidationError``. You shouldn't need to override this method.\n\n* The ``clean()`` method on a ``Field`` subclass is responsible for running\n  ``to_python()``, ``validate()``, and ``run_validators()`` in the correct\n  order and propagating their errors. If, at any time, any of the methods\n  raise ``ValidationError``, the validation stops and that error is raised.\n  This method returns the clean data, which is then inserted into the\n  ``cleaned_data`` dictionary of the form.\n\n* The ``clean_<fieldname>()`` method is called on a form subclass -- where\n  ``<fieldname>`` is replaced with the name of the form field attribute.\n  This method does any cleaning that is specific to that particular\n  attribute, unrelated to the type of field that it is. This method is not\n  passed any parameters. You will need to look up the value of the field\n  in ``self.cleaned_data`` and remember that it will be a Python object\n  at this point, not the original string submitted in the form (it will be\n  in ``cleaned_data`` because the general field ``clean()`` method, above,\n  has already cleaned the data once).\n\n  For example, if you wanted to validate that the contents of a\n  ``CharField`` called ``serialnumber`` was unique,\n  ``clean_serialnumber()`` would be the right place to do this. You don't\n  need a specific field (it's a ``CharField``), but you want a\n  formfield-specific piece of validation and, possibly, cleaning/normalizing\n  the data.\n\n  The return value of this method replaces the existing value in\n  ``cleaned_data``, so it must be the field's value from ``cleaned_data`` (even\n  if this method didn't change it) or a new cleaned value.\n\n* The form subclass's ``clean()`` method can perform validation that requires\n  access to multiple form fields. This is where you might put in checks such as\n  \"if field ``A`` is supplied, field ``B`` must contain a valid email address\".\n  This method can return a completely different dictionary if it wishes, which\n  will be used as the ``cleaned_data``.\n\n  Since the field validation methods have been run by the time ``clean()`` is\n  called, you also have access to the form's ``errors`` attribute which\n  contains all the errors raised by cleaning of individual fields.\n\n  Note that any errors raised by your :meth:`Form.clean()` override will not\n  be associated with any field in particular. They go into a special\n  \"field\" (called ``__all__``), which you can access via the\n  :meth:`~django.forms.Form.non_field_errors` method if you need to. If you\n  want to attach errors to a specific field in the form, you need to call\n  :meth:`~django.forms.Form.add_error()`.\n\n  Also note that there are special considerations when overriding\n  the ``clean()`` method of a ``ModelForm`` subclass. (see the\n  :ref:`ModelForm documentation\n  <overriding-modelform-clean-method>` for more information)\n\nThese methods are run in the order given above, one field at a time.  That is,\nfor each field in the form (in the order they are declared in the form\ndefinition), the ``Field.clean()`` method (or its override) is run, then\n``clean_<fieldname>()``. Finally, once those two methods are run for every\nfield, the :meth:`Form.clean()` method, or its override, is executed whether\nor not the previous methods have raised errors.\n\nExamples of each of these methods are provided below.\n\nAs mentioned, any of these methods can raise a ``ValidationError``. For any\nfield, if the ``Field.clean()`` method raises a ``ValidationError``, any\nfield-specific cleaning method is not called. However, the cleaning methods\nfor all remaining fields are still executed.\n\n.. _raising-validation-error:\n\nRaising ``ValidationError``\n===========================\n\nIn order to make error messages flexible and easy to override, consider the\nfollowing guidelines:\n\n* Provide a descriptive error ``code`` to the constructor::\n\n      # Good\n      ValidationError(_('Invalid value'), code='invalid')\n\n      # Bad\n      ValidationError(_('Invalid value'))\n\n* Don't coerce variables into the message; use placeholders and the ``params``\n  argument of the constructor::\n\n      # Good\n      ValidationError(\n          _('Invalid value: %(value)s'),\n          params={'value': '42'},\n      )\n\n      # Bad\n      ValidationError(_('Invalid value: %s') % value)\n\n* Use mapping keys instead of positional formatting. This enables putting\n  the variables in any order or omitting them altogether when rewriting the\n  message::\n\n      # Good\n      ValidationError(\n          _('Invalid value: %(value)s'),\n          params={'value': '42'},\n      )\n\n      # Bad\n      ValidationError(\n          _('Invalid value: %s'),\n          params=('42',),\n      )\n\n* Wrap the message with ``gettext`` to enable translation::\n\n      # Good\n      ValidationError(_('Invalid value'))\n\n      # Bad\n      ValidationError('Invalid value')\n\nPutting it all together::\n\n    raise ValidationError(\n        _('Invalid value: %(value)s'),\n        code='invalid',\n        params={'value': '42'},\n    )\n\nFollowing these guidelines is particularly necessary if you write reusable\nforms, form fields, and model fields.\n\nWhile not recommended, if you are at the end of the validation chain\n(i.e. your form ``clean()`` method) and you know you will *never* need\nto override your error message you can still opt for the less verbose::\n\n    ValidationError(_('Invalid value: %s') % value)\n\nThe :meth:`Form.errors.as_data() <django.forms.Form.errors.as_data()>` and\n:meth:`Form.errors.as_json() <django.forms.Form.errors.as_json()>` methods\ngreatly benefit from fully featured ``ValidationError``\\s (with a ``code`` name\nand a ``params`` dictionary).\n\nRaising multiple errors\n-----------------------\n\nIf you detect multiple errors during a cleaning method and wish to signal all\nof them to the form submitter, it is possible to pass a list of errors to the\n``ValidationError`` constructor.\n\nAs above, it is recommended to pass a list of ``ValidationError`` instances\nwith ``code``\\s and ``params`` but a list of strings will also work::\n\n    # Good\n    raise ValidationError([\n        ValidationError(_('Error 1'), code='error1'),\n        ValidationError(_('Error 2'), code='error2'),\n    ])\n\n    # Bad\n    raise ValidationError([\n        _('Error 1'),\n        _('Error 2'),\n    ])\n\nUsing validation in practice\n============================\n\nThe previous sections explained how validation works in general for forms.\nSince it can sometimes be easier to put things into place by seeing each\nfeature in use, here are a series of small examples that use each of the\nprevious features.\n\n.. _validators:\n\nUsing validators\n----------------\n\nDjango's form (and model) fields support use of utility functions and classes\nknown as validators. A validator is a callable object or function that takes a\nvalue and returns nothing if the value is valid or raises a\n:exc:`~django.core.exceptions.ValidationError` if not. These can be passed to a\nfield's constructor, via the field's ``validators`` argument, or defined on the\n:class:`~django.forms.Field` class itself with the ``default_validators``\nattribute.\n\nValidators can be used to validate values inside the field, let's have a look\nat Django's ``SlugField``::\n\n    from django.core import validators\n    from django.forms import CharField\n\n    class SlugField(CharField):\n        default_validators = [validators.validate_slug]\n\nAs you can see, ``SlugField`` is a ``CharField`` with a customized validator\nthat validates that submitted text obeys to some character rules. This can also\nbe done on field definition so::\n\n    slug = forms.SlugField()\n\nis equivalent to::\n\n    slug = forms.CharField(validators=[validators.validate_slug])\n\nCommon cases such as validating against an email or a regular expression can be\nhandled using existing validator classes available in Django. For example,\n``validators.validate_slug`` is an instance of\na :class:`~django.core.validators.RegexValidator` constructed with the first\nargument being the pattern: ``^[-a-zA-Z0-9_]+$``. See the section on\n:doc:`writing validators </ref/validators>` to see a list of what is already\navailable and for an example of how to write a validator.\n\nForm field default cleaning\n---------------------------\n\nLet's first create a custom form field that validates its input is a string\ncontaining comma-separated email addresses. The full class looks like this::\n\n    from django import forms\n    from django.core.validators import validate_email\n\n    class MultiEmailField(forms.Field):\n        def to_python(self, value):\n            \"\"\"Normalize data to a list of strings.\"\"\"\n            # Return an empty list if no input was given.\n            if not value:\n                return []\n            return value.split(',')\n\n        def validate(self, value):\n            \"\"\"Check if value consists only of valid emails.\"\"\"\n            # Use the parent's handling of required fields, etc.\n            super().validate(value)\n            for email in value:\n                validate_email(email)\n\nEvery form that uses this field will have these methods run before anything\nelse can be done with the field's data. This is cleaning that is specific to\nthis type of field, regardless of how it is subsequently used.\n\nLet's create a ``ContactForm`` to demonstrate how you'd use this field::\n\n    class ContactForm(forms.Form):\n        subject = forms.CharField(max_length=100)\n        message = forms.CharField()\n        sender = forms.EmailField()\n        recipients = MultiEmailField()\n        cc_myself = forms.BooleanField(required=False)\n\nUse ``MultiEmailField`` like any other form field. When the ``is_valid()``\nmethod is called on the form, the ``MultiEmailField.clean()`` method will be\nrun as part of the cleaning process and it will, in turn, call the custom\n``to_python()`` and ``validate()`` methods.\n\nCleaning a specific field attribute\n-----------------------------------\n\nContinuing on from the previous example, suppose that in our ``ContactForm``,\nwe want to make sure that the ``recipients`` field always contains the address\n``\"fred@example.com\"``. This is validation that is specific to our form, so we\ndon't want to put it into the general ``MultiEmailField`` class. Instead, we\nwrite a cleaning method that operates on the ``recipients`` field, like so::\n\n    from django import forms\n    from django.core.exceptions import ValidationError\n\n    class ContactForm(forms.Form):\n        # Everything as before.\n        ...\n\n        def clean_recipients(self):\n            data = self.cleaned_data['recipients']\n            if \"fred@example.com\" not in data:\n                raise ValidationError(\"You have forgotten about Fred!\")\n\n            # Always return a value to use as the new cleaned data, even if\n            # this method didn't change it.\n            return data\n\n.. _validating-fields-with-clean:\n\nCleaning and validating fields that depend on each other\n--------------------------------------------------------\n\nSuppose we add another requirement to our contact form: if the ``cc_myself``\nfield is ``True``, the ``subject`` must contain the word ``\"help\"``. We are\nperforming validation on more than one field at a time, so the form's\n:meth:`~Form.clean()` method is a good spot to do this. Notice that we are\ntalking about the ``clean()`` method on the form here, whereas earlier we were\nwriting a ``clean()`` method on a field. It's important to keep the field and\nform difference clear when working out where to validate things. Fields are\nsingle data points, forms are a collection of fields.\n\nBy the time the form's ``clean()`` method is called, all the individual field\nclean methods will have been run (the previous two sections), so\n``self.cleaned_data`` will be populated with any data that has survived so\nfar. So you also need to remember to allow for the fact that the fields you\nare wanting to validate might not have survived the initial individual field\nchecks.\n\nThere are two ways to report any errors from this step. Probably the most\ncommon method is to display the error at the top of the form. To create such\nan error, you can raise a ``ValidationError`` from the ``clean()`` method. For\nexample::\n\n    from django import forms\n    from django.core.exceptions import ValidationError\n\n    class ContactForm(forms.Form):\n        # Everything as before.\n        ...\n\n        def clean(self):\n            cleaned_data = super().clean()\n            cc_myself = cleaned_data.get(\"cc_myself\")\n            subject = cleaned_data.get(\"subject\")\n\n            if cc_myself and subject:\n                # Only do something if both fields are valid so far.\n                if \"help\" not in subject:\n                    raise ValidationError(\n                        \"Did not send for 'help' in the subject despite \"\n                        \"CC'ing yourself.\"\n                    )\n\nIn this code, if the validation error is raised, the form will display an\nerror message at the top of the form (normally) describing the problem. Such\nerrors are non-field errors, which are displayed in the template with\n``{{ form.non_field_errors }}``.\n\nThe call to ``super().clean()`` in the example code ensures that any validation\nlogic in parent classes is maintained. If your form inherits another that\ndoesn't return a ``cleaned_data`` dictionary in its ``clean()`` method (doing\nso is optional), then don't assign ``cleaned_data`` to the result of the\n``super()`` call and use ``self.cleaned_data`` instead::\n\n    def clean(self):\n        super().clean()\n        cc_myself = self.cleaned_data.get(\"cc_myself\")\n        ...\n\nThe second approach for reporting validation errors might involve assigning the\nerror message to one of the fields. In this case, let's assign an error message\nto both the \"subject\" and \"cc_myself\" rows in the form display. Be careful when\ndoing this in practice, since it can lead to confusing form output. We're\nshowing what is possible here and leaving it up to you and your designers to\nwork out what works effectively in your particular situation. Our new code\n(replacing the previous sample) looks like this::\n\n    from django import forms\n\n    class ContactForm(forms.Form):\n        # Everything as before.\n        ...\n\n        def clean(self):\n            cleaned_data = super().clean()\n            cc_myself = cleaned_data.get(\"cc_myself\")\n            subject = cleaned_data.get(\"subject\")\n\n            if cc_myself and subject and \"help\" not in subject:\n                msg = \"Must put 'help' in subject when cc'ing yourself.\"\n                self.add_error('cc_myself', msg)\n                self.add_error('subject', msg)\n\nThe second argument of ``add_error()`` can be a string, or preferably an\ninstance of ``ValidationError``. See :ref:`raising-validation-error` for more\ndetails. Note that ``add_error()`` automatically removes the field from\n``cleaned_data``.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":80,"nodeType":"TextFile","repoName":null,"name":"setup.cfg","path":"","text":"[metadata]\nname = Django\nversion = attr: django.__version__\nurl = https://www.djangoproject.com/\nauthor = Django Software Foundation\nauthor_email = foundation@djangoproject.com\ndescription = A high-level Python Web framework that encourages rapid development and clean, pragmatic design.\nlong_description = file: README.rst\nlicense = BSD-3-Clause\nclassifiers =\n    Development Status :: 2 - Pre-Alpha\n    Environment :: Web Environment\n    Framework :: Django\n    Intended Audience :: Developers\n    License :: OSI Approved :: BSD License\n    Operating System :: OS Independent\n    Programming Language :: Python\n    Programming Language :: Python :: 3\n    Programming Language :: Python :: 3 :: Only\n    Programming Language :: Python :: 3.6\n    Programming Language :: Python :: 3.7\n    Programming Language :: Python :: 3.8\n    Topic :: Internet :: WWW/HTTP\n    Topic :: Internet :: WWW/HTTP :: Dynamic Content\n    Topic :: Internet :: WWW/HTTP :: WSGI\n    Topic :: Software Development :: Libraries :: Application Frameworks\n    Topic :: Software Development :: Libraries :: Python Modules\nproject_urls =\n    Documentation = https://docs.djangoproject.com/\n    Release notes = https://docs.djangoproject.com/en/stable/releases/\n    Funding = https://www.djangoproject.com/fundraising/\n    Source = https://github.com/django/django\n    Tracker = https://code.djangoproject.com/\n\n[options]\npython_requires = >=3.6\npackages = find:\n# When the django-admin.py deprecation ends, remove \"scripts\".\nscripts = django/bin/django-admin.py\ninclude_package_data = true\nzip_safe = false\ninstall_requires =\n    asgiref >= 3.2\n    pytz\n    sqlparse >= 0.2.2\n\n[options.entry_points]\nconsole_scripts =\n    django-admin = django.core.management:execute_from_command_line\n\n[options.extras_require]\nargon2 = argon2-cffi >= 16.1.0\nbcrypt = bcrypt\n\n[bdist_rpm]\ndoc_files = docs extras AUTHORS INSTALL LICENSE README.rst\ninstall-script = scripts/rpm-install.sh\n\n[flake8]\nexclude = build,.git,.tox,./tests/.env\nignore = W504,W601\nmax-line-length = 119\n\n[isort]\ncombine_as_imports = true\ndefault_section = THIRDPARTY\ninclude_trailing_comma = true\nknown_first_party = django\nline_length = 79\nmulti_line_output = 5\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":81,"nodeType":"TextFile","repoName":null,"name":".gitattributes","path":"","text":"# Normalize line endings to avoid spurious failures in the core test suite on Windows.\n*html text eol=lf\n*css text eol=lf\n*js text eol=lf\ntests/staticfiles_tests/apps/test/static/test/*txt text eol=lf\ntests/staticfiles_tests/project/documents/test/*txt text eol=lf\ndocs/releases/*.txt merge=union\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":82,"nodeType":"TextFile","repoName":null,"name":".eslintrc","path":"","text":"{\n    \"rules\": {\n        \"camelcase\": [\"off\", {\"properties\": \"always\"}],\n        \"comma-spacing\": [\"error\", {\"before\": false, \"after\": true}],\n        \"curly\": [\"error\", \"all\"],\n        \"dot-notation\": [\"error\", {\"allowKeywords\": true}],\n        \"eqeqeq\": [\"error\"],\n        \"indent\": [\"error\", 4],\n        \"key-spacing\": [\"error\", {\"beforeColon\": false, \"afterColon\": true}],\n        \"linebreak-style\": [\"error\", \"unix\"],\n        \"new-cap\": [\"off\", {\"newIsCap\": true, \"capIsNew\": true}],\n        \"no-alert\": [\"off\"],\n        \"no-eval\": [\"error\"],\n        \"no-extend-native\": [\"error\", {\"exceptions\": [\"Date\", \"String\"]}],\n        \"no-multi-spaces\": [\"error\"],\n        \"no-octal-escape\": [\"error\"],\n        \"no-script-url\": [\"error\"],\n        \"no-shadow\": [\"error\", {\"hoist\": \"functions\"}],\n        \"no-underscore-dangle\": [\"error\"],\n        \"no-unused-vars\": [\"error\", {\"vars\": \"local\", \"args\": \"none\"}],\n        \"no-var\": [\"error\"],\n        \"prefer-const\": [\"error\"],\n        \"quotes\": [\"off\", \"single\"],\n        \"semi\": [\"error\", \"always\"],\n        \"space-before-blocks\": [\"error\", \"always\"],\n        \"space-before-function-paren\": [\"error\", {\"anonymous\": \"never\", \"named\": \"never\"}],\n        \"space-infix-ops\": [\"error\", {\"int32Hint\": false}],\n        \"strict\": [\"error\", \"global\"]\n    },\n    \"env\": {\n        \"browser\": true,\n        \"es6\": true\n    },\n    \"globals\": {\n        \"django\": false\n    }\n}\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":83,"nodeType":"TextFile","repoName":null,"name":"make.bat","path":"docs","text":"@ECHO OFF\n\nREM Command file for Sphinx documentation\n\nif \"%SPHINXBUILD%\" == \"\" (\n\tset SPHINXBUILD=sphinx-build\n)\nset BUILDDIR=_build\nset ALLSPHINXOPTS=-n -d %BUILDDIR%/doctrees %SPHINXOPTS% .\nif NOT \"%PAPER%\" == \"\" (\n\tset ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%\n\tset I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%\n)\n\nif \"%1\" == \"\" goto help\n\nif \"%1\" == \"help\" (\n\t:help\n\techo.Please use `make ^<target^>` where ^<target^> is one of\n\techo.  html       to make standalone HTML files\n\techo.  dirhtml    to make HTML files named index.html in directories\n\techo.  singlehtml to make a single large HTML file\n\techo.  pickle     to make pickle files\n\techo.  json       to make JSON files\n\techo.  htmlhelp   to make HTML files and a HTML help project\n\techo.  qthelp     to make HTML files and a qthelp project\n\techo.  devhelp    to make HTML files and a Devhelp project\n\techo.  epub       to make an epub\n\techo.  latex      to make LaTeX files, you can set PAPER=a4 or PAPER=letter\n\techo.  text       to make text files\n\techo.  man        to make manual pages\n\techo.  texinfo    to make a Texinfo source file\n\techo.  gettext    to make PO message catalogs\n\techo.  changes    to make an overview over all changed/added/deprecated items\n\techo.  linkcheck  to check all external links for integrity\n\techo.  doctest    to run all doctests embedded in the documentation if enabled\n\tgoto end\n)\n\nif \"%1\" == \"clean\" (\n\tfor /d %%i in (%BUILDDIR%\\*) do rmdir /q /s %%i\n\tdel /q /s %BUILDDIR%\\*\n\tgoto end\n)\n\nif \"%1\" == \"html\" (\n\t%SPHINXBUILD% -b djangohtml %ALLSPHINXOPTS% %BUILDDIR%/html\n\tif errorlevel 1 exit /b 1\n\techo.\n\techo.Build finished. The HTML pages are in %BUILDDIR%/html.\n\tgoto end\n)\n\nif \"%1\" == \"dirhtml\" (\n\t%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml\n\tif errorlevel 1 exit /b 1\n\techo.\n\techo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.\n\tgoto end\n)\n\nif \"%1\" == \"singlehtml\" (\n\t%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml\n\tif errorlevel 1 exit /b 1\n\techo.\n\techo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.\n\tgoto end\n)\n\nif \"%1\" == \"pickle\" (\n\t%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle\n\tif errorlevel 1 exit /b 1\n\techo.\n\techo.Build finished; now you can process the pickle files.\n\tgoto end\n)\n\nif \"%1\" == \"json\" (\n\t%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json\n\tif errorlevel 1 exit /b 1\n\techo.\n\techo.Build finished; now you can process the JSON files.\n\tgoto end\n)\n\nif \"%1\" == \"htmlhelp\" (\n\t%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp\n\tif errorlevel 1 exit /b 1\n\techo.\n\techo.Build finished; now you can run HTML Help Workshop with the ^\n.hhp project file in %BUILDDIR%/htmlhelp.\n\tgoto end\n)\n\nif \"%1\" == \"qthelp\" (\n\t%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp\n\tif errorlevel 1 exit /b 1\n\techo.\n\techo.Build finished; now you can run \"qcollectiongenerator\" with the ^\n.qhcp project file in %BUILDDIR%/qthelp, like this:\n\techo.^> qcollectiongenerator %BUILDDIR%\\qthelp\\django.qhcp\n\techo.To view the help file:\n\techo.^> assistant -collectionFile %BUILDDIR%\\qthelp\\django.qhc\n\tgoto end\n)\n\nif \"%1\" == \"devhelp\" (\n\t%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp\n\tif errorlevel 1 exit /b 1\n\techo.\n\techo.Build finished.\n\tgoto end\n)\n\nif \"%1\" == \"epub\" (\n\t%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub\n\tif errorlevel 1 exit /b 1\n\techo.\n\techo.Build finished. The epub file is in %BUILDDIR%/epub.\n\tgoto end\n)\n\nif \"%1\" == \"latex\" (\n\t%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex\n\tif errorlevel 1 exit /b 1\n\techo.\n\techo.Build finished; the LaTeX files are in %BUILDDIR%/latex.\n\tgoto end\n)\n\nif \"%1\" == \"text\" (\n\t%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text\n\tif errorlevel 1 exit /b 1\n\techo.\n\techo.Build finished. The text files are in %BUILDDIR%/text.\n\tgoto end\n)\n\nif \"%1\" == \"man\" (\n\t%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man\n\tif errorlevel 1 exit /b 1\n\techo.\n\techo.Build finished. The manual pages are in %BUILDDIR%/man.\n\tgoto end\n)\n\nif \"%1\" == \"texinfo\" (\n\t%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo\n\tif errorlevel 1 exit /b 1\n\techo.\n\techo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.\n\tgoto end\n)\n\nif \"%%1\" == \"gettext\" (\n\t%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale\n\tif errorlevel 1 exit /b 1\n\techo.\n\techo.Build finished. The message catalogs are in %BUILDDIR%/locale.\n\tgoto end\n)\n\nif \"%1\" == \"changes\" (\n\t%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes\n\tif errorlevel 1 exit /b 1\n\techo.\n\techo.The overview file is in %BUILDDIR%/changes.\n\tgoto end\n)\n\nif \"%1\" == \"linkcheck\" (\n\t%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck\n\tif errorlevel 1 exit /b 1\n\techo.\n\techo.Link check complete; look for any errors in the above output ^\nor in %BUILDDIR%/linkcheck/output.txt.\n\tgoto end\n)\n\nif \"%1\" == \"doctest\" (\n\t%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest\n\tif errorlevel 1 exit /b 1\n\techo.\n\techo.Testing of doctests in the sources finished, look at the ^\nresults in %BUILDDIR%/doctest/output.txt.\n\tgoto end\n)\n\n:end\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":84,"nodeType":"TextFile","repoName":null,"name":"Makefile","path":"docs","text":"# Makefile for Sphinx documentation\n#\n\n# You can set these variables from the command line.\nPYTHON        ?= python\nSPHINXOPTS    ?=\nSPHINXBUILD   ?= sphinx-build\nPAPER         ?=\nBUILDDIR      ?= _build\nLANGUAGE      ?=\n\n# Convert something like \"en_US\" to \"en\", because Sphinx does not recognize\n# underscores. Country codes should be passed using a dash, e.g. \"pt-BR\".\nLANGUAGEOPT = $(firstword $(subst _, ,$(LANGUAGE)))\n\n# Internal variables.\nPAPEROPT_a4     = -D latex_paper_size=a4\nPAPEROPT_letter = -D latex_paper_size=letter\nALLSPHINXOPTS   = -n -d $(BUILDDIR)/doctrees -D language=$(LANGUAGEOPT) $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .\n# the i18n builder cannot share the environment and doctrees with the others\nI18NSPHINXOPTS  = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .\n\n.PHONY: help clean html htmlview dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext\n\nhelp:\n\t@echo \"Please use \\`make <target>' where <target> is one of\"\n\t@echo \"  html       to make standalone HTML files\"\n\t@echo \"  htmlview   to open the index page built by the html target in your browser\"\n\t@echo \"  dirhtml    to make HTML files named index.html in directories\"\n\t@echo \"  singlehtml to make a single large HTML file\"\n\t@echo \"  pickle     to make pickle files\"\n\t@echo \"  json       to make JSON files\"\n\t@echo \"  htmlhelp   to make HTML files and a HTML help project\"\n\t@echo \"  qthelp     to make HTML files and a qthelp project\"\n\t@echo \"  devhelp    to make HTML files and a Devhelp project\"\n\t@echo \"  epub       to make an epub\"\n\t@echo \"  latex      to make LaTeX files, you can set PAPER=a4 or PAPER=letter\"\n\t@echo \"  latexpdf   to make LaTeX files and run them through pdflatex\"\n\t@echo \"  text       to make text files\"\n\t@echo \"  man        to make manual pages\"\n\t@echo \"  texinfo    to make a Texinfo source file\"\n\t@echo \"  gettext    to make PO message catalogs\"\n\t@echo \"  changes    to make an overview of all changed/added/deprecated items\"\n\t@echo \"  linkcheck  to check all external links for integrity\"\n\t@echo \"  doctest    to run all doctests embedded in the documentation (if enabled)\"\n\t@echo \"  spelling   to check for typos in documentation\"\n\n\nclean:\n\t-rm -rf $(BUILDDIR)/*\n\nhtml:\n\t$(SPHINXBUILD) -b djangohtml $(ALLSPHINXOPTS) $(BUILDDIR)/html\n\t@echo\n\t@echo \"Build finished. The HTML pages are in $(BUILDDIR)/html.\"\n\nhtmlview: html\n\t$(PYTHON) -c \"import webbrowser; webbrowser.open('_build/html/index.html')\"\n\ndirhtml:\n\t$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml\n\t@echo\n\t@echo \"Build finished. The HTML pages are in $(BUILDDIR)/dirhtml.\"\n\nsinglehtml:\n\t$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml\n\t@echo\n\t@echo \"Build finished. The HTML page is in $(BUILDDIR)/singlehtml.\"\n\npickle:\n\t$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle\n\t@echo\n\t@echo \"Build finished; now you can process the pickle files.\"\n\njson:\n\t$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json\n\t@echo\n\t@echo \"Build finished; now you can process the JSON files.\"\n\nhtmlhelp:\n\t$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp\n\t@echo\n\t@echo \"Build finished; now you can run HTML Help Workshop with the\" \\\n\t      \".hhp project file in $(BUILDDIR)/htmlhelp.\"\n\nqthelp:\n\t$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp\n\t@echo\n\t@echo \"Build finished; now you can run \"qcollectiongenerator\" with the\" \\\n\t      \".qhcp project file in $(BUILDDIR)/qthelp, like this:\"\n\t@echo \"# qcollectiongenerator $(BUILDDIR)/qthelp/django.qhcp\"\n\t@echo \"To view the help file:\"\n\t@echo \"# assistant -collectionFile $(BUILDDIR)/qthelp/django.qhc\"\n\ndevhelp:\n\t$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp\n\t@echo\n\t@echo \"Build finished.\"\n\t@echo \"To view the help file:\"\n\t@echo \"# mkdir -p $$HOME/.local/share/devhelp/django\"\n\t@echo \"# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/django\"\n\t@echo \"# devhelp\"\n\nepub:\n\t$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub\n\t@echo\n\t@echo \"Build finished. The epub file is in $(BUILDDIR)/epub.\"\n\nlatex:\n\t$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex\n\t@echo\n\t@echo \"Build finished; the LaTeX files are in $(BUILDDIR)/latex.\"\n\t@echo \"Run \\`make' in that directory to run these through (pdf)latex\" \\\n\t      \"(use \\`make latexpdf' here to do that automatically).\"\n\nlatexpdf:\n\t$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex\n\t@echo \"Running LaTeX files through pdflatex...\"\n\tmake -C $(BUILDDIR)/latex all-pdf\n\t@echo \"pdflatex finished; the PDF files are in $(BUILDDIR)/latex.\"\n\ntext:\n\t$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text\n\t@echo\n\t@echo \"Build finished. The text files are in $(BUILDDIR)/text.\"\n\nman:\n\t$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man\n\t@echo\n\t@echo \"Build finished. The manual pages are in $(BUILDDIR)/man.\"\n\ntexinfo:\n\t$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo\n\t@echo\n\t@echo \"Build finished; the Texinfo files are in $(BUILDDIR)/texinfo.\"\n\ngettext:\n\t$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale\n\t@echo\n\t@echo \"Build finished. The message catalogs are in $(BUILDDIR)/locale.\"\n\nchanges:\n\t$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes\n\t@echo\n\t@echo \"The overview file is in $(BUILDDIR)/changes.\"\n\nlinkcheck:\n\t$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck\n\t@echo\n\t@echo \"Link check complete; look for any errors in the above output \" \\\n\t      \"or in $(BUILDDIR)/linkcheck/output.txt.\"\n\ndoctest:\n\t$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest\n\t@echo \"Testing of doctests in the sources finished, look at the \" \\\n\t      \"results in $(BUILDDIR)/doctest/output.txt.\"\n\nspelling:\n\t$(SPHINXBUILD) -b spelling $(ALLSPHINXOPTS) $(BUILDDIR)/spelling\n\t@echo\n\t@echo \"Check finished. Wrong words can be found in \" \\\n\t\t\"$(BUILDDIR)/spelling/output.txt.\"\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":85,"nodeType":"TextFile","repoName":null,"name":"conditional-expressions.txt","path":"docs/ref/models","text":"=======================\nConditional Expressions\n=======================\n\n.. currentmodule:: django.db.models.expressions\n\nConditional expressions let you use :keyword:`if` ... :keyword:`elif` ...\n:keyword:`else` logic within filters, annotations, aggregations, and updates. A\nconditional expression evaluates a series of conditions for each row of a\ntable and returns the matching result expression. Conditional expressions can\nalso be combined and nested like other :doc:`expressions <expressions>`.\n\nThe conditional expression classes\n==================================\n\nWe'll be using the following model in the subsequent examples::\n\n    from django.db import models\n\n    class Client(models.Model):\n        REGULAR = 'R'\n        GOLD = 'G'\n        PLATINUM = 'P'\n        ACCOUNT_TYPE_CHOICES = [\n            (REGULAR, 'Regular'),\n            (GOLD, 'Gold'),\n            (PLATINUM, 'Platinum'),\n        ]\n        name = models.CharField(max_length=50)\n        registered_on = models.DateField()\n        account_type = models.CharField(\n            max_length=1,\n            choices=ACCOUNT_TYPE_CHOICES,\n            default=REGULAR,\n        )\n\n``When``\n--------\n\n.. class:: When(condition=None, then=None, **lookups)\n\nA ``When()`` object is used to encapsulate a condition and its result for use\nin the conditional expression. Using a ``When()`` object is similar to using\nthe :meth:`~django.db.models.query.QuerySet.filter` method. The condition can\nbe specified using :ref:`field lookups <field-lookups>`,\n:class:`~django.db.models.Q` objects, or :class:`~django.db.models.Expression`\nobjects that have an ``output_field`` that is a\n:class:`~django.db.models.BooleanField`. The result is provided using the\n``then`` keyword.\n\nSome examples::\n\n    >>> from django.db.models import F, Q, When\n    >>> # String arguments refer to fields; the following two examples are equivalent:\n    >>> When(account_type=Client.GOLD, then='name')\n    >>> When(account_type=Client.GOLD, then=F('name'))\n    >>> # You can use field lookups in the condition\n    >>> from datetime import date\n    >>> When(registered_on__gt=date(2014, 1, 1),\n    ...      registered_on__lt=date(2015, 1, 1),\n    ...      then='account_type')\n    >>> # Complex conditions can be created using Q objects\n    >>> When(Q(name__startswith=\"John\") | Q(name__startswith=\"Paul\"),\n    ...      then='name')\n    >>> # Condition can be created using boolean expressions.\n    >>> from django.db.models import Exists, OuterRef\n    >>> non_unique_account_type = Client.objects.filter(\n    ...     account_type=OuterRef('account_type'),\n    ... ).exclude(pk=OuterRef('pk')).values('pk')\n    >>> When(Exists(non_unique_account_type), then=Value('non unique'))\n\nKeep in mind that each of these values can be an expression.\n\n.. note::\n\n    Since the ``then`` keyword argument is reserved for the result of the\n    ``When()``, there is a potential conflict if a\n    :class:`~django.db.models.Model` has a field named ``then``. This can be\n    resolved in two ways::\n\n        >>> When(then__exact=0, then=1)\n        >>> When(Q(then=0), then=1)\n\n``Case``\n--------\n\n.. class:: Case(*cases, **extra)\n\nA ``Case()`` expression is like the :keyword:`if` ... :keyword:`elif` ...\n:keyword:`else` statement in ``Python``. Each ``condition`` in the provided\n``When()`` objects is evaluated in order, until one evaluates to a\ntruthful value. The ``result`` expression from the matching ``When()`` object\nis returned.\n\nAn example::\n\n    >>>\n    >>> from datetime import date, timedelta\n    >>> from django.db.models import Case, CharField, Value, When\n    >>> Client.objects.create(\n    ...     name='Jane Doe',\n    ...     account_type=Client.REGULAR,\n    ...     registered_on=date.today() - timedelta(days=36))\n    >>> Client.objects.create(\n    ...     name='James Smith',\n    ...     account_type=Client.GOLD,\n    ...     registered_on=date.today() - timedelta(days=5))\n    >>> Client.objects.create(\n    ...     name='Jack Black',\n    ...     account_type=Client.PLATINUM,\n    ...     registered_on=date.today() - timedelta(days=10 * 365))\n    >>> # Get the discount for each Client based on the account type\n    >>> Client.objects.annotate(\n    ...     discount=Case(\n    ...         When(account_type=Client.GOLD, then=Value('5%')),\n    ...         When(account_type=Client.PLATINUM, then=Value('10%')),\n    ...         default=Value('0%'),\n    ...         output_field=CharField(),\n    ...     ),\n    ... ).values_list('name', 'discount')\n    <QuerySet [('Jane Doe', '0%'), ('James Smith', '5%'), ('Jack Black', '10%')]>\n\n``Case()`` accepts any number of ``When()`` objects as individual arguments.\nOther options are provided using keyword arguments. If none of the conditions\nevaluate to ``TRUE``, then the expression given with the ``default`` keyword\nargument is returned. If a ``default`` argument isn't provided, ``None`` is\nused.\n\nIf we wanted to change our previous query to get the discount based on how long\nthe ``Client`` has been with us, we could do so using lookups::\n\n    >>> a_month_ago = date.today() - timedelta(days=30)\n    >>> a_year_ago = date.today() - timedelta(days=365)\n    >>> # Get the discount for each Client based on the registration date\n    >>> Client.objects.annotate(\n    ...     discount=Case(\n    ...         When(registered_on__lte=a_year_ago, then=Value('10%')),\n    ...         When(registered_on__lte=a_month_ago, then=Value('5%')),\n    ...         default=Value('0%'),\n    ...         output_field=CharField(),\n    ...     )\n    ... ).values_list('name', 'discount')\n    <QuerySet [('Jane Doe', '5%'), ('James Smith', '0%'), ('Jack Black', '10%')]>\n\n.. note::\n\n    Remember that the conditions are evaluated in order, so in the above\n    example we get the correct result even though the second condition matches\n    both Jane Doe and Jack Black. This works just like an :keyword:`if` ...\n    :keyword:`elif` ... :keyword:`else` statement in ``Python``.\n\n``Case()`` also works in a ``filter()`` clause. For example, to find gold\nclients that registered more than a month ago and platinum clients that\nregistered more than a year ago::\n\n    >>> a_month_ago = date.today() - timedelta(days=30)\n    >>> a_year_ago = date.today() - timedelta(days=365)\n    >>> Client.objects.filter(\n    ...     registered_on__lte=Case(\n    ...         When(account_type=Client.GOLD, then=a_month_ago),\n    ...         When(account_type=Client.PLATINUM, then=a_year_ago),\n    ...     ),\n    ... ).values_list('name', 'account_type')\n    <QuerySet [('Jack Black', 'P')]>\n\nAdvanced queries\n================\n\nConditional expressions can be used in annotations, aggregations, filters,\nlookups, and updates. They can also be combined and nested with other\nexpressions. This allows you to make powerful conditional queries.\n\nConditional update\n------------------\n\nLet's say we want to change the ``account_type`` for our clients to match\ntheir registration dates. We can do this using a conditional expression and the\n:meth:`~django.db.models.query.QuerySet.update` method::\n\n    >>> a_month_ago = date.today() - timedelta(days=30)\n    >>> a_year_ago = date.today() - timedelta(days=365)\n    >>> # Update the account_type for each Client from the registration date\n    >>> Client.objects.update(\n    ...     account_type=Case(\n    ...         When(registered_on__lte=a_year_ago,\n    ...              then=Value(Client.PLATINUM)),\n    ...         When(registered_on__lte=a_month_ago,\n    ...              then=Value(Client.GOLD)),\n    ...         default=Value(Client.REGULAR)\n    ...     ),\n    ... )\n    >>> Client.objects.values_list('name', 'account_type')\n    <QuerySet [('Jane Doe', 'G'), ('James Smith', 'R'), ('Jack Black', 'P')]>\n\n.. _conditional-aggregation:\n\nConditional aggregation\n-----------------------\n\nWhat if we want to find out how many clients there are for each\n``account_type``? We can use the ``filter`` argument of :ref:`aggregate\nfunctions <aggregation-functions>` to achieve this::\n\n    >>> # Create some more Clients first so we can have something to count\n    >>> Client.objects.create(\n    ...     name='Jean Grey',\n    ...     account_type=Client.REGULAR,\n    ...     registered_on=date.today())\n    >>> Client.objects.create(\n    ...     name='James Bond',\n    ...     account_type=Client.PLATINUM,\n    ...     registered_on=date.today())\n    >>> Client.objects.create(\n    ...     name='Jane Porter',\n    ...     account_type=Client.PLATINUM,\n    ...     registered_on=date.today())\n    >>> # Get counts for each value of account_type\n    >>> from django.db.models import Count\n    >>> Client.objects.aggregate(\n    ...     regular=Count('pk', filter=Q(account_type=Client.REGULAR)),\n    ...     gold=Count('pk', filter=Q(account_type=Client.GOLD)),\n    ...     platinum=Count('pk', filter=Q(account_type=Client.PLATINUM)),\n    ... )\n    {'regular': 2, 'gold': 1, 'platinum': 3}\n\nThis aggregate produces a query with the SQL 2003 ``FILTER WHERE`` syntax\non databases that support it:\n\n.. code-block:: sql\n\n    SELECT count('id') FILTER (WHERE account_type=1) as regular,\n           count('id') FILTER (WHERE account_type=2) as gold,\n           count('id') FILTER (WHERE account_type=3) as platinum\n    FROM clients;\n\nOn other databases, this is emulated using a ``CASE`` statement:\n\n.. code-block:: sql\n\n    SELECT count(CASE WHEN account_type=1 THEN id ELSE null) as regular,\n           count(CASE WHEN account_type=2 THEN id ELSE null) as gold,\n           count(CASE WHEN account_type=3 THEN id ELSE null) as platinum\n    FROM clients;\n\nThe two SQL statements are functionally equivalent but the more explicit\n``FILTER`` may perform better.\n\nConditional filter\n------------------\n\nWhen a conditional expression returns a boolean value, it is possible to use it\ndirectly in filters. This means that it will not be added to the ``SELECT``\ncolumns, but you can still use it to filter results::\n\n    >>> non_unique_account_type = Client.objects.filter(\n    ...     account_type=OuterRef('account_type'),\n    ... ).exclude(pk=OuterRef('pk')).values('pk')\n    >>> Client.objects.filter(~Exists(non_unique_account_type))\n\nIn SQL terms, that evaluates to:\n\n.. code-block:: sql\n\n    SELECT ...\n    FROM client c0\n    WHERE NOT EXISTS (\n      SELECT c1.id\n      FROM client c1\n      WHERE c1.account_type = c0.account_type AND NOT c1.id = c0.id\n    )\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":86,"nodeType":"TextFile","repoName":null,"name":"database-functions.txt","path":"docs/ref/models","text":"==================\nDatabase Functions\n==================\n\n.. module:: django.db.models.functions\n    :synopsis: Database Functions\n\nThe classes documented below provide a way for users to use functions provided\nby the underlying database as annotations, aggregations, or filters in Django.\nFunctions are also :doc:`expressions <expressions>`, so they can be used and\ncombined with other expressions like :ref:`aggregate functions\n<aggregation-functions>`.\n\nWe'll be using the following model in examples of each function::\n\n    class Author(models.Model):\n        name = models.CharField(max_length=50)\n        age = models.PositiveIntegerField(null=True, blank=True)\n        alias = models.CharField(max_length=50, null=True, blank=True)\n        goes_by = models.CharField(max_length=50, null=True, blank=True)\n\nWe don't usually recommend allowing ``null=True`` for ``CharField`` since this\nallows the field to have two \"empty values\", but it's important for the\n``Coalesce`` example below.\n\n.. _comparison-functions:\n\nComparison and conversion functions\n===================================\n\n``Cast``\n--------\n\n.. class:: Cast(expression, output_field)\n\nForces the result type of ``expression`` to be the one from ``output_field``.\n\nUsage example::\n\n    >>> from django.db.models import FloatField\n    >>> from django.db.models.functions import Cast\n    >>> Author.objects.create(age=25, name='Margaret Smith')\n    >>> author = Author.objects.annotate(\n    ...    age_as_float=Cast('age', output_field=FloatField()),\n    ... ).get()\n    >>> print(author.age_as_float)\n    25.0\n\n``Coalesce``\n------------\n\n.. class:: Coalesce(*expressions, **extra)\n\nAccepts a list of at least two field names or expressions and returns the\nfirst non-null value (note that an empty string is not considered a null\nvalue). Each argument must be of a similar type, so mixing text and numbers\nwill result in a database error.\n\nUsage examples::\n\n    >>> # Get a screen name from least to most public\n    >>> from django.db.models import Sum, Value as V\n    >>> from django.db.models.functions import Coalesce\n    >>> Author.objects.create(name='Margaret Smith', goes_by='Maggie')\n    >>> author = Author.objects.annotate(\n    ...    screen_name=Coalesce('alias', 'goes_by', 'name')).get()\n    >>> print(author.screen_name)\n    Maggie\n\n    >>> # Prevent an aggregate Sum() from returning None\n    >>> aggregated = Author.objects.aggregate(\n    ...    combined_age=Coalesce(Sum('age'), V(0)),\n    ...    combined_age_default=Sum('age'))\n    >>> print(aggregated['combined_age'])\n    0\n    >>> print(aggregated['combined_age_default'])\n    None\n\n.. warning::\n\n    A Python value passed to ``Coalesce`` on MySQL may be converted to an\n    incorrect type unless explicitly cast to the correct database type:\n\n    >>> from django.db.models import DateTimeField\n    >>> from django.db.models.functions import Cast, Coalesce\n    >>> from django.utils import timezone\n    >>> now = timezone.now()\n    >>> Coalesce('updated', Cast(now, DateTimeField()))\n\n``Greatest``\n------------\n\n.. class:: Greatest(*expressions, **extra)\n\nAccepts a list of at least two field names or expressions and returns the\ngreatest value. Each argument must be of a similar type, so mixing text and\nnumbers will result in a database error.\n\nUsage example::\n\n    class Blog(models.Model):\n        body = models.TextField()\n        modified = models.DateTimeField(auto_now=True)\n\n    class Comment(models.Model):\n        body = models.TextField()\n        modified = models.DateTimeField(auto_now=True)\n        blog = models.ForeignKey(Blog, on_delete=models.CASCADE)\n\n    >>> from django.db.models.functions import Greatest\n    >>> blog = Blog.objects.create(body='Greatest is the best.')\n    >>> comment = Comment.objects.create(body='No, Least is better.', blog=blog)\n    >>> comments = Comment.objects.annotate(last_updated=Greatest('modified', 'blog__modified'))\n    >>> annotated_comment = comments.get()\n\n``annotated_comment.last_updated`` will be the most recent of ``blog.modified``\nand ``comment.modified``.\n\n.. warning::\n\n    The behavior of ``Greatest`` when one or more expression may be ``null``\n    varies between databases:\n\n    - PostgreSQL: ``Greatest`` will return the largest non-null expression,\n      or ``null`` if all expressions are ``null``.\n    - SQLite, Oracle, and MySQL: If any expression is ``null``, ``Greatest``\n      will return ``null``.\n\n    The PostgreSQL behavior can be emulated using ``Coalesce`` if you know\n    a sensible minimum value to provide as a default.\n\n``Least``\n---------\n\n.. class:: Least(*expressions, **extra)\n\nAccepts a list of at least two field names or expressions and returns the\nleast value. Each argument must be of a similar type, so mixing text and numbers\nwill result in a database error.\n\n.. warning::\n\n    The behavior of ``Least`` when one or more expression may be ``null``\n    varies between databases:\n\n    - PostgreSQL: ``Least`` will return the smallest non-null expression,\n      or ``null`` if all expressions are ``null``.\n    - SQLite, Oracle, and MySQL: If any expression is ``null``, ``Least``\n      will return ``null``.\n\n    The PostgreSQL behavior can be emulated using ``Coalesce`` if you know\n    a sensible maximum value to provide as a default.\n\n``NullIf``\n----------\n\n.. class:: NullIf(expression1, expression2)\n\nAccepts two expressions and returns ``None`` if they are equal, otherwise\nreturns ``expression1``.\n\n.. admonition:: Caveats on Oracle\n\n    Due to an :ref:`Oracle convention<oracle-null-empty-strings>`, this\n    function returns the empty string instead of ``None`` when the expressions\n    are of type :class:`~django.db.models.CharField`.\n\n    Passing ``Value(None)`` to ``expression1`` is prohibited on Oracle since\n    Oracle doesn't accept ``NULL`` as the first argument.\n\n.. _date-functions:\n\nDate functions\n==============\n\nWe'll be using the following model in examples of each function::\n\n    class Experiment(models.Model):\n        start_datetime = models.DateTimeField()\n        start_date = models.DateField(null=True, blank=True)\n        start_time = models.TimeField(null=True, blank=True)\n        end_datetime = models.DateTimeField(null=True, blank=True)\n        end_date = models.DateField(null=True, blank=True)\n        end_time = models.TimeField(null=True, blank=True)\n\n``Extract``\n-----------\n\n.. class:: Extract(expression, lookup_name=None, tzinfo=None, **extra)\n\nExtracts a component of a date as a number.\n\nTakes an ``expression`` representing a ``DateField``, ``DateTimeField``,\n``TimeField``, or ``DurationField`` and a ``lookup_name``, and returns the part\nof the date referenced by ``lookup_name`` as an ``IntegerField``.\nDjango usually uses the databases' extract function, so you may use any\n``lookup_name`` that your database supports. A ``tzinfo`` subclass, usually\nprovided by ``pytz``, can be passed to extract a value in a specific timezone.\n\nGiven the datetime ``2015-06-15 23:30:01.000321+00:00``, the built-in\n``lookup_name``\\s return:\n\n* \"year\": 2015\n* \"iso_year\": 2015\n* \"quarter\": 2\n* \"month\": 6\n* \"day\": 15\n* \"week\": 25\n* \"week_day\": 2\n* \"iso_week_day\": 1\n* \"hour\": 23\n* \"minute\": 30\n* \"second\": 1\n\nIf a different timezone like ``Australia/Melbourne`` is active in Django, then\nthe datetime is converted to the timezone before the value is extracted. The\ntimezone offset for Melbourne in the example date above is +10:00. The values\nreturned when this timezone is active will be the same as above except for:\n\n* \"day\": 16\n* \"week_day\": 3\n* \"iso_week_day\": 2\n* \"hour\": 9\n\n.. admonition:: ``week_day`` values\n\n    The ``week_day`` ``lookup_type`` is calculated differently from most\n    databases and from Python's standard functions. This function will return\n    ``1`` for Sunday, ``2`` for Monday, through ``7`` for Saturday.\n\n    The equivalent calculation in Python is::\n\n        >>> from datetime import datetime\n        >>> dt = datetime(2015, 6, 15)\n        >>> (dt.isoweekday() % 7) + 1\n        2\n\n.. admonition:: ``week`` values\n\n    The ``week`` ``lookup_type`` is calculated based on `ISO-8601\n    <https://en.wikipedia.org/wiki/ISO-8601>`_, i.e.,\n    a week starts on a Monday. The first week of a year is the one that\n    contains the year's first Thursday, i.e. the first week has the majority\n    (four or more) of its days in the year. The value returned is in the range\n    1 to 52 or 53.\n\nEach ``lookup_name`` above has a corresponding ``Extract`` subclass (listed\nbelow) that should typically be used instead of the more verbose equivalent,\ne.g. use ``ExtractYear(...)`` rather than ``Extract(..., lookup_name='year')``.\n\nUsage example::\n\n    >>> from datetime import datetime\n    >>> from django.db.models.functions import Extract\n    >>> start = datetime(2015, 6, 15)\n    >>> end = datetime(2015, 7, 2)\n    >>> Experiment.objects.create(\n    ...    start_datetime=start, start_date=start.date(),\n    ...    end_datetime=end, end_date=end.date())\n    >>> # Add the experiment start year as a field in the QuerySet.\n    >>> experiment = Experiment.objects.annotate(\n    ...    start_year=Extract('start_datetime', 'year')).get()\n    >>> experiment.start_year\n    2015\n    >>> # How many experiments completed in the same year in which they started?\n    >>> Experiment.objects.filter(\n    ...    start_datetime__year=Extract('end_datetime', 'year')).count()\n    1\n\n``DateField`` extracts\n~~~~~~~~~~~~~~~~~~~~~~\n\n.. class:: ExtractYear(expression, tzinfo=None, **extra)\n\n    .. attribute:: lookup_name = 'year'\n\n.. class:: ExtractIsoYear(expression, tzinfo=None, **extra)\n\n    Returns the ISO-8601 week-numbering year.\n\n    .. attribute:: lookup_name = 'iso_year'\n\n.. class:: ExtractMonth(expression, tzinfo=None, **extra)\n\n    .. attribute:: lookup_name = 'month'\n\n.. class:: ExtractDay(expression, tzinfo=None, **extra)\n\n    .. attribute:: lookup_name = 'day'\n\n.. class:: ExtractWeekDay(expression, tzinfo=None, **extra)\n\n    .. attribute:: lookup_name = 'week_day'\n\n.. class:: ExtractIsoWeekDay(expression, tzinfo=None, **extra)\n\n    .. versionadded:: 3.1\n\n    Returns the ISO-8601 week day with day 1 being Monday and day 7 being\n    Sunday.\n\n    .. attribute:: lookup_name = 'iso_week_day'\n\n.. class:: ExtractWeek(expression, tzinfo=None, **extra)\n\n    .. attribute:: lookup_name = 'week'\n\n.. class:: ExtractQuarter(expression, tzinfo=None, **extra)\n\n    .. attribute:: lookup_name = 'quarter'\n\nThese are logically equivalent to ``Extract('date_field', lookup_name)``. Each\nclass is also a ``Transform`` registered on ``DateField`` and ``DateTimeField``\nas ``__(lookup_name)``, e.g. ``__year``.\n\nSince ``DateField``\\s don't have a time component, only ``Extract`` subclasses\nthat deal with date-parts can be used with ``DateField``::\n\n    >>> from datetime import datetime\n    >>> from django.utils import timezone\n    >>> from django.db.models.functions import (\n    ...     ExtractDay, ExtractMonth, ExtractQuarter, ExtractWeek,\n    ...     ExtractIsoWeekDay, ExtractWeekDay, ExtractIsoYear, ExtractYear,\n    ... )\n    >>> start_2015 = datetime(2015, 6, 15, 23, 30, 1, tzinfo=timezone.utc)\n    >>> end_2015 = datetime(2015, 6, 16, 13, 11, 27, tzinfo=timezone.utc)\n    >>> Experiment.objects.create(\n    ...    start_datetime=start_2015, start_date=start_2015.date(),\n    ...    end_datetime=end_2015, end_date=end_2015.date())\n    >>> Experiment.objects.annotate(\n    ...     year=ExtractYear('start_date'),\n    ...     isoyear=ExtractIsoYear('start_date'),\n    ...     quarter=ExtractQuarter('start_date'),\n    ...     month=ExtractMonth('start_date'),\n    ...     week=ExtractWeek('start_date'),\n    ...     day=ExtractDay('start_date'),\n    ...     weekday=ExtractWeekDay('start_date'),\n    ...     isoweekday=ExtractIsoWeekDay('start_date'),\n    ... ).values(\n    ...     'year', 'isoyear', 'quarter', 'month', 'week', 'day', 'weekday',\n    ...     'isoweekday',\n    ... ).get(end_date__year=ExtractYear('start_date'))\n    {'year': 2015, 'isoyear': 2015, 'quarter': 2, 'month': 6, 'week': 25,\n     'day': 15, 'weekday': 2, 'isoweekday': 1}\n\n``DateTimeField`` extracts\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIn addition to the following, all extracts for ``DateField`` listed above may\nalso be used on ``DateTimeField``\\s .\n\n.. class:: ExtractHour(expression, tzinfo=None, **extra)\n\n    .. attribute:: lookup_name = 'hour'\n\n.. class:: ExtractMinute(expression, tzinfo=None, **extra)\n\n    .. attribute:: lookup_name = 'minute'\n\n.. class:: ExtractSecond(expression, tzinfo=None, **extra)\n\n    .. attribute:: lookup_name = 'second'\n\nThese are logically equivalent to ``Extract('datetime_field', lookup_name)``.\nEach class is also a ``Transform`` registered on ``DateTimeField`` as\n``__(lookup_name)``, e.g. ``__minute``.\n\n``DateTimeField`` examples::\n\n    >>> from datetime import datetime\n    >>> from django.utils import timezone\n    >>> from django.db.models.functions import (\n    ...     ExtractDay, ExtractHour, ExtractMinute, ExtractMonth,\n    ...     ExtractQuarter, ExtractSecond, ExtractWeek, ExtractIsoWeekDay,\n    ...     ExtractWeekDay, ExtractIsoYear, ExtractYear,\n    ... )\n    >>> start_2015 = datetime(2015, 6, 15, 23, 30, 1, tzinfo=timezone.utc)\n    >>> end_2015 = datetime(2015, 6, 16, 13, 11, 27, tzinfo=timezone.utc)\n    >>> Experiment.objects.create(\n    ...    start_datetime=start_2015, start_date=start_2015.date(),\n    ...    end_datetime=end_2015, end_date=end_2015.date())\n    >>> Experiment.objects.annotate(\n    ...     year=ExtractYear('start_datetime'),\n    ...     isoyear=ExtractIsoYear('start_datetime'),\n    ...     quarter=ExtractQuarter('start_datetime'),\n    ...     month=ExtractMonth('start_datetime'),\n    ...     week=ExtractWeek('start_datetime'),\n    ...     day=ExtractDay('start_datetime'),\n    ...     weekday=ExtractWeekDay('start_datetime'),\n    ...     isoweekday=ExtractIsoWeekDay('start_datetime'),\n    ...     hour=ExtractHour('start_datetime'),\n    ...     minute=ExtractMinute('start_datetime'),\n    ...     second=ExtractSecond('start_datetime'),\n    ... ).values(\n    ...     'year', 'isoyear', 'month', 'week', 'day',\n    ...     'weekday', 'isoweekday', 'hour', 'minute', 'second',\n    ... ).get(end_datetime__year=ExtractYear('start_datetime'))\n    {'year': 2015, 'isoyear': 2015, 'quarter': 2, 'month': 6, 'week': 25,\n     'day': 15, 'weekday': 2, 'isoweekday': 1, 'hour': 23, 'minute': 30,\n     'second': 1}\n\nWhen :setting:`USE_TZ` is ``True`` then datetimes are stored in the database\nin UTC. If a different timezone is active in Django, the datetime is converted\nto that timezone before the value is extracted. The example below converts to\nthe Melbourne timezone (UTC +10:00), which changes the day, weekday, and hour\nvalues that are returned::\n\n    >>> import pytz\n    >>> melb = pytz.timezone('Australia/Melbourne')  # UTC+10:00\n    >>> with timezone.override(melb):\n    ...    Experiment.objects.annotate(\n    ...        day=ExtractDay('start_datetime'),\n    ...        weekday=ExtractWeekDay('start_datetime'),\n    ...        isoweekday=ExtractIsoWeekDay('start_datetime'),\n    ...        hour=ExtractHour('start_datetime'),\n    ...    ).values('day', 'weekday', 'isoweekday', 'hour').get(\n    ...        end_datetime__year=ExtractYear('start_datetime'),\n    ...    )\n    {'day': 16, 'weekday': 3, 'isoweekday': 2, 'hour': 9}\n\nExplicitly passing the timezone to the ``Extract`` function behaves in the same\nway, and takes priority over an active timezone::\n\n    >>> import pytz\n    >>> melb = pytz.timezone('Australia/Melbourne')\n    >>> Experiment.objects.annotate(\n    ...     day=ExtractDay('start_datetime', tzinfo=melb),\n    ...     weekday=ExtractWeekDay('start_datetime', tzinfo=melb),\n    ...     isoweekday=ExtractIsoWeekDay('start_datetime', tzinfo=melb),\n    ...     hour=ExtractHour('start_datetime', tzinfo=melb),\n    ... ).values('day', 'weekday', 'isoweekday', 'hour').get(\n    ...     end_datetime__year=ExtractYear('start_datetime'),\n    ... )\n    {'day': 16, 'weekday': 3, 'isoweekday': 2, 'hour': 9}\n\n``Now``\n-------\n\n.. class:: Now()\n\nReturns the database server's current date and time when the query is executed,\ntypically using the SQL ``CURRENT_TIMESTAMP``.\n\nUsage example::\n\n    >>> from django.db.models.functions import Now\n    >>> Article.objects.filter(published__lte=Now())\n    <QuerySet [<Article: How to Django>]>\n\n.. admonition:: PostgreSQL considerations\n\n    On PostgreSQL, the SQL ``CURRENT_TIMESTAMP`` returns the time that the\n    current transaction started. Therefore for cross-database compatibility,\n    ``Now()`` uses ``STATEMENT_TIMESTAMP`` instead. If you need the transaction\n    timestamp, use :class:`django.contrib.postgres.functions.TransactionNow`.\n\n``Trunc``\n---------\n\n.. class:: Trunc(expression, kind, output_field=None, tzinfo=None, is_dst=None, **extra)\n\nTruncates a date up to a significant component.\n\nWhen you only care if something happened in a particular year, hour, or day,\nbut not the exact second, then ``Trunc`` (and its subclasses) can be useful to\nfilter or aggregate your data. For example, you can use ``Trunc`` to calculate\nthe number of sales per day.\n\n``Trunc`` takes a single ``expression``, representing a ``DateField``,\n``TimeField``, or ``DateTimeField``, a ``kind`` representing a date or time\npart, and an ``output_field`` that's either ``DateTimeField()``,\n``TimeField()``, or ``DateField()``. It returns a datetime, date, or time\ndepending on ``output_field``, with fields up to ``kind`` set to their minimum\nvalue. If ``output_field`` is omitted, it will default to the ``output_field``\nof ``expression``. A ``tzinfo`` subclass, usually provided by ``pytz``, can be\npassed to truncate a value in a specific timezone.\n\nThe ``is_dst`` parameter indicates whether or not ``pytz`` should interpret\nnonexistent and ambiguous datetimes in daylight saving time. By default (when\n``is_dst=None``), ``pytz`` raises an exception for such datetimes.\n\nGiven the datetime ``2015-06-15 14:30:50.000321+00:00``, the built-in ``kind``\\s\nreturn:\n\n* \"year\": 2015-01-01 00:00:00+00:00\n* \"quarter\": 2015-04-01 00:00:00+00:00\n* \"month\": 2015-06-01 00:00:00+00:00\n* \"week\": 2015-06-15 00:00:00+00:00\n* \"day\": 2015-06-15 00:00:00+00:00\n* \"hour\": 2015-06-15 14:00:00+00:00\n* \"minute\": 2015-06-15 14:30:00+00:00\n* \"second\": 2015-06-15 14:30:50+00:00\n\nIf a different timezone like ``Australia/Melbourne`` is active in Django, then\nthe datetime is converted to the new timezone before the value is truncated.\nThe timezone offset for Melbourne in the example date above is +10:00. The\nvalues returned when this timezone is active will be:\n\n* \"year\": 2015-01-01 00:00:00+11:00\n* \"quarter\": 2015-04-01 00:00:00+10:00\n* \"month\": 2015-06-01 00:00:00+10:00\n* \"week\": 2015-06-16 00:00:00+10:00\n* \"day\": 2015-06-16 00:00:00+10:00\n* \"hour\": 2015-06-16 00:00:00+10:00\n* \"minute\": 2015-06-16 00:30:00+10:00\n* \"second\": 2015-06-16 00:30:50+10:00\n\nThe year has an offset of +11:00 because the result transitioned into daylight\nsaving time.\n\nEach ``kind`` above has a corresponding ``Trunc`` subclass (listed below) that\nshould typically be used instead of the more verbose equivalent,\ne.g. use ``TruncYear(...)`` rather than ``Trunc(..., kind='year')``.\n\nThe subclasses are all defined as transforms, but they aren't registered with\nany fields, because the lookup names are already reserved by the ``Extract``\nsubclasses.\n\nUsage example::\n\n    >>> from datetime import datetime\n    >>> from django.db.models import Count, DateTimeField\n    >>> from django.db.models.functions import Trunc\n    >>> Experiment.objects.create(start_datetime=datetime(2015, 6, 15, 14, 30, 50, 321))\n    >>> Experiment.objects.create(start_datetime=datetime(2015, 6, 15, 14, 40, 2, 123))\n    >>> Experiment.objects.create(start_datetime=datetime(2015, 12, 25, 10, 5, 27, 999))\n    >>> experiments_per_day = Experiment.objects.annotate(\n    ...    start_day=Trunc('start_datetime', 'day', output_field=DateTimeField())\n    ... ).values('start_day').annotate(experiments=Count('id'))\n    >>> for exp in experiments_per_day:\n    ...     print(exp['start_day'], exp['experiments'])\n    ...\n    2015-06-15 00:00:00 2\n    2015-12-25 00:00:00 1\n    >>> experiments = Experiment.objects.annotate(\n    ...    start_day=Trunc('start_datetime', 'day', output_field=DateTimeField())\n    ... ).filter(start_day=datetime(2015, 6, 15))\n    >>> for exp in experiments:\n    ...     print(exp.start_datetime)\n    ...\n    2015-06-15 14:30:50.000321\n    2015-06-15 14:40:02.000123\n\n``DateField`` truncation\n~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. class:: TruncYear(expression, output_field=None, tzinfo=None, is_dst=None, **extra)\n\n    .. attribute:: kind = 'year'\n\n.. class:: TruncMonth(expression, output_field=None, tzinfo=None, is_dst=None, **extra)\n\n    .. attribute:: kind = 'month'\n\n.. class:: TruncWeek(expression, output_field=None, tzinfo=None, is_dst=None, **extra)\n\n    Truncates to midnight on the Monday of the week.\n\n    .. attribute:: kind = 'week'\n\n.. class:: TruncQuarter(expression, output_field=None, tzinfo=None, is_dst=None, **extra)\n\n    .. attribute:: kind = 'quarter'\n\nThese are logically equivalent to ``Trunc('date_field', kind)``. They truncate\nall parts of the date up to ``kind`` which allows grouping or filtering dates\nwith less precision. ``expression`` can have an ``output_field`` of either\n``DateField`` or ``DateTimeField``.\n\nSince ``DateField``\\s don't have a time component, only ``Trunc`` subclasses\nthat deal with date-parts can be used with ``DateField``::\n\n    >>> from datetime import datetime\n    >>> from django.db.models import Count\n    >>> from django.db.models.functions import TruncMonth, TruncYear\n    >>> from django.utils import timezone\n    >>> start1 = datetime(2014, 6, 15, 14, 30, 50, 321, tzinfo=timezone.utc)\n    >>> start2 = datetime(2015, 6, 15, 14, 40, 2, 123, tzinfo=timezone.utc)\n    >>> start3 = datetime(2015, 12, 31, 17, 5, 27, 999, tzinfo=timezone.utc)\n    >>> Experiment.objects.create(start_datetime=start1, start_date=start1.date())\n    >>> Experiment.objects.create(start_datetime=start2, start_date=start2.date())\n    >>> Experiment.objects.create(start_datetime=start3, start_date=start3.date())\n    >>> experiments_per_year = Experiment.objects.annotate(\n    ...    year=TruncYear('start_date')).values('year').annotate(\n    ...    experiments=Count('id'))\n    >>> for exp in experiments_per_year:\n    ...     print(exp['year'], exp['experiments'])\n    ...\n    2014-01-01 1\n    2015-01-01 2\n\n    >>> import pytz\n    >>> melb = pytz.timezone('Australia/Melbourne')\n    >>> experiments_per_month = Experiment.objects.annotate(\n    ...    month=TruncMonth('start_datetime', tzinfo=melb)).values('month').annotate(\n    ...    experiments=Count('id'))\n    >>> for exp in experiments_per_month:\n    ...     print(exp['month'], exp['experiments'])\n    ...\n    2015-06-01 00:00:00+10:00 1\n    2016-01-01 00:00:00+11:00 1\n    2014-06-01 00:00:00+10:00 1\n\n``DateTimeField`` truncation\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. class:: TruncDate(expression, **extra)\n\n    .. attribute:: lookup_name = 'date'\n    .. attribute:: output_field = DateField()\n\n``TruncDate`` casts ``expression`` to a date rather than using the built-in SQL\ntruncate function. It's also registered as a transform on  ``DateTimeField`` as\n``__date``.\n\n.. class:: TruncTime(expression, **extra)\n\n    .. attribute:: lookup_name = 'time'\n    .. attribute:: output_field = TimeField()\n\n``TruncTime`` casts ``expression`` to a time rather than using the built-in SQL\ntruncate function. It's also registered as a transform on ``DateTimeField`` as\n``__time``.\n\n.. class:: TruncDay(expression, output_field=None, tzinfo=None, is_dst=None, **extra)\n\n    .. attribute:: kind = 'day'\n\n.. class:: TruncHour(expression, output_field=None, tzinfo=None, is_dst=None, **extra)\n\n    .. attribute:: kind = 'hour'\n\n.. class:: TruncMinute(expression, output_field=None, tzinfo=None, is_dst=None, **extra)\n\n    .. attribute:: kind = 'minute'\n\n.. class:: TruncSecond(expression, output_field=None, tzinfo=None, is_dst=None, **extra)\n\n    .. attribute:: kind = 'second'\n\nThese are logically equivalent to ``Trunc('datetime_field', kind)``. They\ntruncate all parts of the date up to ``kind`` and allow grouping or filtering\ndatetimes with less precision. ``expression`` must have an ``output_field`` of\n``DateTimeField``.\n\nUsage example::\n\n    >>> from datetime import date, datetime\n    >>> from django.db.models import Count\n    >>> from django.db.models.functions import (\n    ...     TruncDate, TruncDay, TruncHour, TruncMinute, TruncSecond,\n    ... )\n    >>> from django.utils import timezone\n    >>> import pytz\n    >>> start1 = datetime(2014, 6, 15, 14, 30, 50, 321, tzinfo=timezone.utc)\n    >>> Experiment.objects.create(start_datetime=start1, start_date=start1.date())\n    >>> melb = pytz.timezone('Australia/Melbourne')\n    >>> Experiment.objects.annotate(\n    ...     date=TruncDate('start_datetime'),\n    ...     day=TruncDay('start_datetime', tzinfo=melb),\n    ...     hour=TruncHour('start_datetime', tzinfo=melb),\n    ...     minute=TruncMinute('start_datetime'),\n    ...     second=TruncSecond('start_datetime'),\n    ... ).values('date', 'day', 'hour', 'minute', 'second').get()\n    {'date': datetime.date(2014, 6, 15),\n     'day': datetime.datetime(2014, 6, 16, 0, 0, tzinfo=<DstTzInfo 'Australia/Melbourne' AEST+10:00:00 STD>),\n     'hour': datetime.datetime(2014, 6, 16, 0, 0, tzinfo=<DstTzInfo 'Australia/Melbourne' AEST+10:00:00 STD>),\n     'minute': 'minute': datetime.datetime(2014, 6, 15, 14, 30, tzinfo=<UTC>),\n     'second': datetime.datetime(2014, 6, 15, 14, 30, 50, tzinfo=<UTC>)\n    }\n\n``TimeField`` truncation\n~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. class:: TruncHour(expression, output_field=None, tzinfo=None, is_dst=None, **extra)\n    :noindex:\n\n    .. attribute:: kind = 'hour'\n\n.. class:: TruncMinute(expression, output_field=None, tzinfo=None, is_dst=None, **extra)\n    :noindex:\n\n    .. attribute:: kind = 'minute'\n\n.. class:: TruncSecond(expression, output_field=None, tzinfo=None, is_dst=None, **extra)\n    :noindex:\n\n    .. attribute:: kind = 'second'\n\nThese are logically equivalent to ``Trunc('time_field', kind)``. They truncate\nall parts of the time up to ``kind`` which allows grouping or filtering times\nwith less precision. ``expression`` can have an ``output_field`` of either\n``TimeField`` or ``DateTimeField``.\n\nSince ``TimeField``\\s don't have a date component, only ``Trunc`` subclasses\nthat deal with time-parts can be used with ``TimeField``::\n\n    >>> from datetime import datetime\n    >>> from django.db.models import Count, TimeField\n    >>> from django.db.models.functions import TruncHour\n    >>> from django.utils import timezone\n    >>> start1 = datetime(2014, 6, 15, 14, 30, 50, 321, tzinfo=timezone.utc)\n    >>> start2 = datetime(2014, 6, 15, 14, 40, 2, 123, tzinfo=timezone.utc)\n    >>> start3 = datetime(2015, 12, 31, 17, 5, 27, 999, tzinfo=timezone.utc)\n    >>> Experiment.objects.create(start_datetime=start1, start_time=start1.time())\n    >>> Experiment.objects.create(start_datetime=start2, start_time=start2.time())\n    >>> Experiment.objects.create(start_datetime=start3, start_time=start3.time())\n    >>> experiments_per_hour = Experiment.objects.annotate(\n    ...    hour=TruncHour('start_datetime', output_field=TimeField()),\n    ... ).values('hour').annotate(experiments=Count('id'))\n    >>> for exp in experiments_per_hour:\n    ...     print(exp['hour'], exp['experiments'])\n    ...\n    14:00:00 2\n    17:00:00 1\n\n    >>> import pytz\n    >>> melb = pytz.timezone('Australia/Melbourne')\n    >>> experiments_per_hour = Experiment.objects.annotate(\n    ...    hour=TruncHour('start_datetime', tzinfo=melb),\n    ... ).values('hour').annotate(experiments=Count('id'))\n    >>> for exp in experiments_per_hour:\n    ...     print(exp['hour'], exp['experiments'])\n    ...\n    2014-06-16 00:00:00+10:00 2\n    2016-01-01 04:00:00+11:00 1\n\n.. _math-functions:\n\nMath Functions\n==============\n\nWe'll be using the following model in math function examples::\n\n    class Vector(models.Model):\n        x = models.FloatField()\n        y = models.FloatField()\n\n``Abs``\n-------\n\n.. class:: Abs(expression, **extra)\n\nReturns the absolute value of a numeric field or expression.\n\nUsage example::\n\n    >>> from django.db.models.functions import Abs\n    >>> Vector.objects.create(x=-0.5, y=1.1)\n    >>> vector = Vector.objects.annotate(x_abs=Abs('x'), y_abs=Abs('y')).get()\n    >>> vector.x_abs, vector.y_abs\n    (0.5, 1.1)\n\nIt can also be registered as a transform. For example::\n\n    >>> from django.db.models import FloatField\n    >>> from django.db.models.functions import Abs\n    >>> FloatField.register_lookup(Abs)\n    >>> # Get vectors inside the unit cube\n    >>> vectors = Vector.objects.filter(x__abs__lt=1, y__abs__lt=1)\n\n``ACos``\n--------\n\n.. class:: ACos(expression, **extra)\n\nReturns the arccosine of a numeric field or expression. The expression value\nmust be within the range -1 to 1.\n\nUsage example::\n\n    >>> from django.db.models.functions import ACos\n    >>> Vector.objects.create(x=0.5, y=-0.9)\n    >>> vector = Vector.objects.annotate(x_acos=ACos('x'), y_acos=ACos('y')).get()\n    >>> vector.x_acos, vector.y_acos\n    (1.0471975511965979, 2.6905658417935308)\n\nIt can also be registered as a transform. For example::\n\n    >>> from django.db.models import FloatField\n    >>> from django.db.models.functions import ACos\n    >>> FloatField.register_lookup(ACos)\n    >>> # Get vectors whose arccosine is less than 1\n    >>> vectors = Vector.objects.filter(x__acos__lt=1, y__acos__lt=1)\n\n``ASin``\n--------\n\n.. class:: ASin(expression, **extra)\n\nReturns the arcsine of a numeric field or expression. The expression value must\nbe in the range -1 to 1.\n\nUsage example::\n\n    >>> from django.db.models.functions import ASin\n    >>> Vector.objects.create(x=0, y=1)\n    >>> vector = Vector.objects.annotate(x_asin=ASin('x'), y_asin=ASin('y')).get()\n    >>> vector.x_asin, vector.y_asin\n    (0.0, 1.5707963267948966)\n\nIt can also be registered as a transform. For example::\n\n    >>> from django.db.models import FloatField\n    >>> from django.db.models.functions import ASin\n    >>> FloatField.register_lookup(ASin)\n    >>> # Get vectors whose arcsine is less than 1\n    >>> vectors = Vector.objects.filter(x__asin__lt=1, y__asin__lt=1)\n\n``ATan``\n--------\n\n.. class:: ATan(expression, **extra)\n\nReturns the arctangent of a numeric field or expression.\n\nUsage example::\n\n    >>> from django.db.models.functions import ATan\n    >>> Vector.objects.create(x=3.12, y=6.987)\n    >>> vector = Vector.objects.annotate(x_atan=ATan('x'), y_atan=ATan('y')).get()\n    >>> vector.x_atan, vector.y_atan\n    (1.2606282660069106, 1.428638798133829)\n\nIt can also be registered as a transform. For example::\n\n    >>> from django.db.models import FloatField\n    >>> from django.db.models.functions import ATan\n    >>> FloatField.register_lookup(ATan)\n    >>> # Get vectors whose arctangent is less than 2\n    >>> vectors = Vector.objects.filter(x__atan__lt=2, y__atan__lt=2)\n\n``ATan2``\n---------\n\n.. class:: ATan2(expression1, expression2, **extra)\n\nReturns the arctangent of ``expression1 / expression2``.\n\nUsage example::\n\n    >>> from django.db.models.functions import ATan2\n    >>> Vector.objects.create(x=2.5, y=1.9)\n    >>> vector = Vector.objects.annotate(atan2=ATan2('x', 'y')).get()\n    >>> vector.atan2\n    0.9209258773829491\n\n``Ceil``\n--------\n\n.. class:: Ceil(expression, **extra)\n\nReturns the smallest integer greater than or equal to a numeric field or\nexpression.\n\nUsage example::\n\n    >>> from django.db.models.functions import Ceil\n    >>> Vector.objects.create(x=3.12, y=7.0)\n    >>> vector = Vector.objects.annotate(x_ceil=Ceil('x'), y_ceil=Ceil('y')).get()\n    >>> vector.x_ceil, vector.y_ceil\n    (4.0, 7.0)\n\nIt can also be registered as a transform. For example::\n\n    >>> from django.db.models import FloatField\n    >>> from django.db.models.functions import Ceil\n    >>> FloatField.register_lookup(Ceil)\n    >>> # Get vectors whose ceil is less than 10\n    >>> vectors = Vector.objects.filter(x__ceil__lt=10, y__ceil__lt=10)\n\n``Cos``\n-------\n\n.. class:: Cos(expression, **extra)\n\nReturns the cosine  of a numeric field or expression.\n\nUsage example::\n\n    >>> from django.db.models.functions import Cos\n    >>> Vector.objects.create(x=-8.0, y=3.1415926)\n    >>> vector = Vector.objects.annotate(x_cos=Cos('x'), y_cos=Cos('y')).get()\n    >>> vector.x_cos, vector.y_cos\n    (-0.14550003380861354, -0.9999999999999986)\n\nIt can also be registered as a transform. For example::\n\n    >>> from django.db.models import FloatField\n    >>> from django.db.models.functions import Cos\n    >>> FloatField.register_lookup(Cos)\n    >>> # Get vectors whose cosine is less than 0.5\n    >>> vectors = Vector.objects.filter(x__cos__lt=0.5, y__cos__lt=0.5)\n\n``Cot``\n-------\n\n.. class:: Cot(expression, **extra)\n\nReturns the cotangent of a numeric field or expression.\n\nUsage example::\n\n    >>> from django.db.models.functions import Cot\n    >>> Vector.objects.create(x=12.0, y=1.0)\n    >>> vector = Vector.objects.annotate(x_cot=Cot('x'), y_cot=Cot('y')).get()\n    >>> vector.x_cot, vector.y_cot\n    (-1.5726734063976826, 0.642092615934331)\n\nIt can also be registered as a transform. For example::\n\n    >>> from django.db.models import FloatField\n    >>> from django.db.models.functions import Cot\n    >>> FloatField.register_lookup(Cot)\n    >>> # Get vectors whose cotangent is less than 1\n    >>> vectors = Vector.objects.filter(x__cot__lt=1, y__cot__lt=1)\n\n``Degrees``\n-----------\n\n.. class:: Degrees(expression, **extra)\n\nConverts a numeric field or expression from radians to degrees.\n\nUsage example::\n\n    >>> from django.db.models.functions import Degrees\n    >>> Vector.objects.create(x=-1.57, y=3.14)\n    >>> vector = Vector.objects.annotate(x_d=Degrees('x'), y_d=Degrees('y')).get()\n    >>> vector.x_d, vector.y_d\n    (-89.95437383553924, 179.9087476710785)\n\nIt can also be registered as a transform. For example::\n\n    >>> from django.db.models import FloatField\n    >>> from django.db.models.functions import Degrees\n    >>> FloatField.register_lookup(Degrees)\n    >>> # Get vectors whose degrees are less than 360\n    >>> vectors = Vector.objects.filter(x__degrees__lt=360, y__degrees__lt=360)\n\n``Exp``\n-------\n\n.. class:: Exp(expression, **extra)\n\nReturns the value of ``e`` (the natural logarithm base) raised to the power of\na numeric field or expression.\n\nUsage example::\n\n    >>> from django.db.models.functions import Exp\n    >>> Vector.objects.create(x=5.4, y=-2.0)\n    >>> vector = Vector.objects.annotate(x_exp=Exp('x'), y_exp=Exp('y')).get()\n    >>> vector.x_exp, vector.y_exp\n    (221.40641620418717, 0.1353352832366127)\n\nIt can also be registered as a transform. For example::\n\n    >>> from django.db.models import FloatField\n    >>> from django.db.models.functions import Exp\n    >>> FloatField.register_lookup(Exp)\n    >>> # Get vectors whose exp() is greater than 10\n    >>> vectors = Vector.objects.filter(x__exp__gt=10, y__exp__gt=10)\n\n``Floor``\n---------\n\n.. class:: Floor(expression, **extra)\n\nReturns the largest integer value not greater than a numeric field or\nexpression.\n\nUsage example::\n\n    >>> from django.db.models.functions import Floor\n    >>> Vector.objects.create(x=5.4, y=-2.3)\n    >>> vector = Vector.objects.annotate(x_floor=Floor('x'), y_floor=Floor('y')).get()\n    >>> vector.x_floor, vector.y_floor\n    (5.0, -3.0)\n\nIt can also be registered as a transform. For example::\n\n    >>> from django.db.models import FloatField\n    >>> from django.db.models.functions import Floor\n    >>> FloatField.register_lookup(Floor)\n    >>> # Get vectors whose floor() is greater than 10\n    >>> vectors = Vector.objects.filter(x__floor__gt=10, y__floor__gt=10)\n\n``Ln``\n------\n\n.. class:: Ln(expression, **extra)\n\nReturns the natural logarithm a numeric field or expression.\n\nUsage example::\n\n    >>> from django.db.models.functions import Ln\n    >>> Vector.objects.create(x=5.4, y=233.0)\n    >>> vector = Vector.objects.annotate(x_ln=Ln('x'), y_ln=Ln('y')).get()\n    >>> vector.x_ln, vector.y_ln\n    (1.6863989535702288, 5.4510384535657)\n\nIt can also be registered as a transform. For example::\n\n    >>> from django.db.models import FloatField\n    >>> from django.db.models.functions import Ln\n    >>> FloatField.register_lookup(Ln)\n    >>> # Get vectors whose value greater than e\n    >>> vectors = Vector.objects.filter(x__ln__gt=1, y__ln__gt=1)\n\n``Log``\n-------\n\n.. class:: Log(expression1, expression2, **extra)\n\nAccepts two numeric fields or expressions and returns the logarithm of\nthe first to base of the second.\n\nUsage example::\n\n    >>> from django.db.models.functions import Log\n    >>> Vector.objects.create(x=2.0, y=4.0)\n    >>> vector = Vector.objects.annotate(log=Log('x', 'y')).get()\n    >>> vector.log\n    2.0\n\n``Mod``\n-------\n\n.. class:: Mod(expression1, expression2, **extra)\n\nAccepts two numeric fields or expressions and returns the remainder of\nthe first divided by the second (modulo operation).\n\nUsage example::\n\n    >>> from django.db.models.functions import Mod\n    >>> Vector.objects.create(x=5.4, y=2.3)\n    >>> vector = Vector.objects.annotate(mod=Mod('x', 'y')).get()\n    >>> vector.mod\n    0.8\n\n``Pi``\n------\n\n.. class:: Pi(**extra)\n\nReturns the value of the mathematical constant ``π``.\n\n``Power``\n---------\n\n.. class:: Power(expression1, expression2, **extra)\n\nAccepts two numeric fields or expressions and returns the value of the first\nraised to the power of the second.\n\nUsage example::\n\n    >>> from django.db.models.functions import Power\n    >>> Vector.objects.create(x=2, y=-2)\n    >>> vector = Vector.objects.annotate(power=Power('x', 'y')).get()\n    >>> vector.power\n    0.25\n\n``Radians``\n-----------\n\n.. class:: Radians(expression, **extra)\n\nConverts a numeric field or expression from degrees to radians.\n\nUsage example::\n\n    >>> from django.db.models.functions import Radians\n    >>> Vector.objects.create(x=-90, y=180)\n    >>> vector = Vector.objects.annotate(x_r=Radians('x'), y_r=Radians('y')).get()\n    >>> vector.x_r, vector.y_r\n    (-1.5707963267948966, 3.141592653589793)\n\nIt can also be registered as a transform. For example::\n\n    >>> from django.db.models import FloatField\n    >>> from django.db.models.functions import Radians\n    >>> FloatField.register_lookup(Radians)\n    >>> # Get vectors whose radians are less than 1\n    >>> vectors = Vector.objects.filter(x__radians__lt=1, y__radians__lt=1)\n\n``Round``\n---------\n\n.. class:: Round(expression, **extra)\n\nRounds a numeric field or expression to the nearest integer. Whether half\nvalues are rounded up or down depends on the database.\n\nUsage example::\n\n    >>> from django.db.models.functions import Round\n    >>> Vector.objects.create(x=5.4, y=-2.3)\n    >>> vector = Vector.objects.annotate(x_r=Round('x'), y_r=Round('y')).get()\n    >>> vector.x_r, vector.y_r\n    (5.0, -2.0)\n\nIt can also be registered as a transform. For example::\n\n    >>> from django.db.models import FloatField\n    >>> from django.db.models.functions import Round\n    >>> FloatField.register_lookup(Round)\n    >>> # Get vectors whose round() is less than 20\n    >>> vectors = Vector.objects.filter(x__round__lt=20, y__round__lt=20)\n\n``Sign``\n--------\n\n.. class:: Sign(expression, **extra)\n\nReturns the sign (-1, 0, 1) of a numeric field or expression.\n\nUsage example::\n\n    >>> from django.db.models.functions import Sign\n    >>> Vector.objects.create(x=5.4, y=-2.3)\n    >>> vector = Vector.objects.annotate(x_sign=Sign('x'), y_sign=Sign('y')).get()\n    >>> vector.x_sign, vector.y_sign\n    (1, -1)\n\nIt can also be registered as a transform. For example::\n\n    >>> from django.db.models import FloatField\n    >>> from django.db.models.functions import Sign\n    >>> FloatField.register_lookup(Sign)\n    >>> # Get vectors whose signs of components are less than 0.\n    >>> vectors = Vector.objects.filter(x__sign__lt=0, y__sign__lt=0)\n\n``Sin``\n-------\n\n.. class:: Sin(expression, **extra)\n\nReturns the sine of a numeric field or expression.\n\nUsage example::\n\n    >>> from django.db.models.functions import Sin\n    >>> Vector.objects.create(x=5.4, y=-2.3)\n    >>> vector = Vector.objects.annotate(x_sin=Sin('x'), y_sin=Sin('y')).get()\n    >>> vector.x_sin, vector.y_sin\n    (-0.7727644875559871, -0.7457052121767203)\n\nIt can also be registered as a transform. For example::\n\n    >>> from django.db.models import FloatField\n    >>> from django.db.models.functions import Sin\n    >>> FloatField.register_lookup(Sin)\n    >>> # Get vectors whose sin() is less than 0\n    >>> vectors = Vector.objects.filter(x__sin__lt=0, y__sin__lt=0)\n\n``Sqrt``\n--------\n\n.. class:: Sqrt(expression, **extra)\n\nReturns the square root of a nonnegative numeric field or expression.\n\nUsage example::\n\n    >>> from django.db.models.functions import Sqrt\n    >>> Vector.objects.create(x=4.0, y=12.0)\n    >>> vector = Vector.objects.annotate(x_sqrt=Sqrt('x'), y_sqrt=Sqrt('y')).get()\n    >>> vector.x_sqrt, vector.y_sqrt\n    (2.0, 3.46410)\n\nIt can also be registered as a transform. For example::\n\n    >>> from django.db.models import FloatField\n    >>> from django.db.models.functions import Sqrt\n    >>> FloatField.register_lookup(Sqrt)\n    >>> # Get vectors whose sqrt() is less than 5\n    >>> vectors = Vector.objects.filter(x__sqrt__lt=5, y__sqrt__lt=5)\n\n``Tan``\n-------\n\n.. class:: Tan(expression, **extra)\n\nReturns the tangent of a numeric field or expression.\n\nUsage example::\n\n    >>> from django.db.models.functions import Tan\n    >>> Vector.objects.create(x=0, y=12)\n    >>> vector = Vector.objects.annotate(x_tan=Tan('x'), y_tan=Tan('y')).get()\n    >>> vector.x_tan, vector.y_tan\n    (0.0, -0.6358599286615808)\n\nIt can also be registered as a transform. For example::\n\n    >>> from django.db.models import FloatField\n    >>> from django.db.models.functions import Tan\n    >>> FloatField.register_lookup(Tan)\n    >>> # Get vectors whose tangent is less than 0\n    >>> vectors = Vector.objects.filter(x__tan__lt=0, y__tan__lt=0)\n\n.. _text-functions:\n\nText functions\n==============\n\n``Chr``\n-------\n\n.. class:: Chr(expression, **extra)\n\nAccepts a numeric field or expression and returns the text representation of\nthe expression as a single character. It works the same as Python's :func:`chr`\nfunction.\n\nLike :class:`Length`, it can be registered as a transform on ``IntegerField``.\nThe default lookup name is ``chr``.\n\nUsage example::\n\n    >>> from django.db.models.functions import Chr\n    >>> Author.objects.create(name='Margaret Smith')\n    >>> author = Author.objects.filter(name__startswith=Chr(ord('M'))).get()\n    >>> print(author.name)\n    Margaret Smith\n\n``Concat``\n----------\n\n.. class:: Concat(*expressions, **extra)\n\nAccepts a list of at least two text fields or expressions and returns the\nconcatenated text. Each argument must be of a text or char type. If you want\nto concatenate a ``TextField()`` with a ``CharField()``, then be sure to tell\nDjango that the ``output_field`` should be a ``TextField()``. Specifying an\n``output_field`` is also required when concatenating a ``Value`` as in the\nexample below.\n\nThis function will never have a null result. On backends where a null argument\nresults in the entire expression being null, Django will ensure that each null\npart is converted to an empty string first.\n\nUsage example::\n\n    >>> # Get the display name as \"name (goes_by)\"\n    >>> from django.db.models import CharField, Value as V\n    >>> from django.db.models.functions import Concat\n    >>> Author.objects.create(name='Margaret Smith', goes_by='Maggie')\n    >>> author = Author.objects.annotate(\n    ...     screen_name=Concat(\n    ...         'name', V(' ('), 'goes_by', V(')'),\n    ...         output_field=CharField()\n    ...     )\n    ... ).get()\n    >>> print(author.screen_name)\n    Margaret Smith (Maggie)\n\n``Left``\n--------\n\n.. class:: Left(expression, length, **extra)\n\nReturns the first ``length`` characters of the given text field or expression.\n\nUsage example::\n\n    >>> from django.db.models.functions import Left\n    >>> Author.objects.create(name='Margaret Smith')\n    >>> author = Author.objects.annotate(first_initial=Left('name', 1)).get()\n    >>> print(author.first_initial)\n    M\n\n``Length``\n----------\n\n.. class:: Length(expression, **extra)\n\nAccepts a single text field or expression and returns the number of characters\nthe value has. If the expression is null, then the length will also be null.\n\nUsage example::\n\n    >>> # Get the length of the name and goes_by fields\n    >>> from django.db.models.functions import Length\n    >>> Author.objects.create(name='Margaret Smith')\n    >>> author = Author.objects.annotate(\n    ...    name_length=Length('name'),\n    ...    goes_by_length=Length('goes_by')).get()\n    >>> print(author.name_length, author.goes_by_length)\n    (14, None)\n\nIt can also be registered as a transform. For example::\n\n    >>> from django.db.models import CharField\n    >>> from django.db.models.functions import Length\n    >>> CharField.register_lookup(Length)\n    >>> # Get authors whose name is longer than 7 characters\n    >>> authors = Author.objects.filter(name__length__gt=7)\n\n``Lower``\n---------\n\n.. class:: Lower(expression, **extra)\n\nAccepts a single text field or expression and returns the lowercase\nrepresentation.\n\nIt can also be registered as a transform as described in :class:`Length`.\n\nUsage example::\n\n    >>> from django.db.models.functions import Lower\n    >>> Author.objects.create(name='Margaret Smith')\n    >>> author = Author.objects.annotate(name_lower=Lower('name')).get()\n    >>> print(author.name_lower)\n    margaret smith\n\n``LPad``\n--------\n\n.. class:: LPad(expression, length, fill_text=Value(' '), **extra)\n\nReturns the value of the given text field or expression padded on the left side\nwith ``fill_text`` so that the resulting value is ``length`` characters long.\nThe default ``fill_text`` is a space.\n\nUsage example::\n\n    >>> from django.db.models import Value\n    >>> from django.db.models.functions import LPad\n    >>> Author.objects.create(name='John', alias='j')\n    >>> Author.objects.update(name=LPad('name', 8, Value('abc')))\n    1\n    >>> print(Author.objects.get(alias='j').name)\n    abcaJohn\n\n``LTrim``\n---------\n\n.. class:: LTrim(expression, **extra)\n\nSimilar to :class:`~django.db.models.functions.Trim`, but removes only leading\nspaces.\n\n``MD5``\n-------\n\n.. class:: MD5(expression, **extra)\n\nAccepts a single text field or expression and returns the MD5 hash of the\nstring.\n\nIt can also be registered as a transform as described in :class:`Length`.\n\nUsage example::\n\n    >>> from django.db.models.functions import MD5\n    >>> Author.objects.create(name='Margaret Smith')\n    >>> author = Author.objects.annotate(name_md5=MD5('name')).get()\n    >>> print(author.name_md5)\n    749fb689816b2db85f5b169c2055b247\n\n``Ord``\n-------\n\n.. class:: Ord(expression, **extra)\n\nAccepts a single text field or expression and returns the Unicode code point\nvalue for the first character of that expression. It works similar to Python's\n:func:`ord` function, but an exception isn't raised if the expression is more\nthan one character long.\n\nIt can also be registered as a transform as described in :class:`Length`.\nThe default lookup name is ``ord``.\n\nUsage example::\n\n    >>> from django.db.models.functions import Ord\n    >>> Author.objects.create(name='Margaret Smith')\n    >>> author = Author.objects.annotate(name_code_point=Ord('name')).get()\n    >>> print(author.name_code_point)\n    77\n\n``Repeat``\n----------\n\n.. class:: Repeat(expression, number, **extra)\n\nReturns the value of the given text field or expression repeated ``number``\ntimes.\n\nUsage example::\n\n    >>> from django.db.models.functions import Repeat\n    >>> Author.objects.create(name='John', alias='j')\n    >>> Author.objects.update(name=Repeat('name', 3))\n    1\n    >>> print(Author.objects.get(alias='j').name)\n    JohnJohnJohn\n\n``Replace``\n-----------\n\n.. class:: Replace(expression, text, replacement=Value(''), **extra)\n\nReplaces all occurrences of ``text`` with ``replacement`` in ``expression``.\nThe default replacement text is the empty string. The arguments to the function\nare case-sensitive.\n\nUsage example::\n\n    >>> from django.db.models import Value\n    >>> from django.db.models.functions import Replace\n    >>> Author.objects.create(name='Margaret Johnson')\n    >>> Author.objects.create(name='Margaret Smith')\n    >>> Author.objects.update(name=Replace('name', Value('Margaret'), Value('Margareth')))\n    2\n    >>> Author.objects.values('name')\n    <QuerySet [{'name': 'Margareth Johnson'}, {'name': 'Margareth Smith'}]>\n\n``Reverse``\n-----------\n\n.. class:: Reverse(expression, **extra)\n\nAccepts a single text field or expression and returns the characters of that\nexpression in reverse order.\n\nIt can also be registered as a transform as described in :class:`Length`. The\ndefault lookup name is ``reverse``.\n\nUsage example::\n\n    >>> from django.db.models.functions import Reverse\n    >>> Author.objects.create(name='Margaret Smith')\n    >>> author = Author.objects.annotate(backward=Reverse('name')).get()\n    >>> print(author.backward)\n    htimS teragraM\n\n``Right``\n---------\n\n.. class:: Right(expression, length, **extra)\n\nReturns the last ``length`` characters of the given text field or expression.\n\nUsage example::\n\n    >>> from django.db.models.functions import Right\n    >>> Author.objects.create(name='Margaret Smith')\n    >>> author = Author.objects.annotate(last_letter=Right('name', 1)).get()\n    >>> print(author.last_letter)\n    h\n\n``RPad``\n--------\n\n.. class:: RPad(expression, length, fill_text=Value(' '), **extra)\n\nSimilar to :class:`~django.db.models.functions.LPad`, but pads on the right\nside.\n\n``RTrim``\n---------\n\n.. class:: RTrim(expression, **extra)\n\nSimilar to :class:`~django.db.models.functions.Trim`, but removes only trailing\nspaces.\n\n``SHA1``, ``SHA224``, ``SHA256``, ``SHA384``, and ``SHA512``\n------------------------------------------------------------\n\n.. class:: SHA1(expression, **extra)\n.. class:: SHA224(expression, **extra)\n.. class:: SHA256(expression, **extra)\n.. class:: SHA384(expression, **extra)\n.. class:: SHA512(expression, **extra)\n\nAccepts a single text field or expression and returns the particular hash of\nthe string.\n\nThey can also be registered as transforms as described in :class:`Length`.\n\nUsage example::\n\n    >>> from django.db.models.functions import SHA1\n    >>> Author.objects.create(name='Margaret Smith')\n    >>> author = Author.objects.annotate(name_sha1=SHA1('name')).get()\n    >>> print(author.name_sha1)\n    b87efd8a6c991c390be5a68e8a7945a7851c7e5c\n\n.. admonition:: PostgreSQL\n\n    The `pgcrypto extension <https://www.postgresql.org/docs/current/\n    pgcrypto.html>`_ must be installed. You can use the\n    :class:`~django.contrib.postgres.operations.CryptoExtension` migration\n    operation to install it.\n\n.. admonition:: Oracle\n\n    Oracle doesn't support the ``SHA224`` function.\n\n``StrIndex``\n------------\n\n.. class:: StrIndex(string, substring, **extra)\n\nReturns a positive integer corresponding to the 1-indexed position of the first\noccurrence of ``substring`` inside ``string``, or 0 if ``substring`` is not\nfound.\n\nUsage example::\n\n    >>> from django.db.models import Value as V\n    >>> from django.db.models.functions import StrIndex\n    >>> Author.objects.create(name='Margaret Smith')\n    >>> Author.objects.create(name='Smith, Margaret')\n    >>> Author.objects.create(name='Margaret Jackson')\n    >>> Author.objects.filter(name='Margaret Jackson').annotate(\n    ...     smith_index=StrIndex('name', V('Smith'))\n    ... ).get().smith_index\n    0\n    >>> authors = Author.objects.annotate(\n    ...    smith_index=StrIndex('name', V('Smith'))\n    ... ).filter(smith_index__gt=0)\n    <QuerySet [<Author: Margaret Smith>, <Author: Smith, Margaret>]>\n\n.. warning::\n\n    In MySQL, a database table's :ref:`collation<mysql-collation>` determines\n    whether string comparisons (such as the ``expression`` and ``substring`` of\n    this function) are case-sensitive. Comparisons are case-insensitive by\n    default.\n\n``Substr``\n----------\n\n.. class:: Substr(expression, pos, length=None, **extra)\n\nReturns a substring of length ``length`` from the field or expression starting\nat position ``pos``. The position is 1-indexed, so the position must be greater\nthan 0. If ``length`` is ``None``, then the rest of the string will be returned.\n\nUsage example::\n\n    >>> # Set the alias to the first 5 characters of the name as lowercase\n    >>> from django.db.models.functions import Lower, Substr\n    >>> Author.objects.create(name='Margaret Smith')\n    >>> Author.objects.update(alias=Lower(Substr('name', 1, 5)))\n    1\n    >>> print(Author.objects.get(name='Margaret Smith').alias)\n    marga\n\n``Trim``\n--------\n\n.. class:: Trim(expression, **extra)\n\nReturns the value of the given text field or expression with leading and\ntrailing spaces removed.\n\nUsage example::\n\n    >>> from django.db.models.functions import Trim\n    >>> Author.objects.create(name='  John  ', alias='j')\n    >>> Author.objects.update(name=Trim('name'))\n    1\n    >>> print(Author.objects.get(alias='j').name)\n    John\n\n``Upper``\n---------\n\n.. class:: Upper(expression, **extra)\n\nAccepts a single text field or expression and returns the uppercase\nrepresentation.\n\nIt can also be registered as a transform as described in :class:`Length`.\n\nUsage example::\n\n    >>> from django.db.models.functions import Upper\n    >>> Author.objects.create(name='Margaret Smith')\n    >>> author = Author.objects.annotate(name_upper=Upper('name')).get()\n    >>> print(author.name_upper)\n    MARGARET SMITH\n\n.. _window-functions:\n\nWindow functions\n================\n\nThere are a number of functions to use in a\n:class:`~django.db.models.expressions.Window` expression for computing the rank\nof elements or the :class:`Ntile` of some rows.\n\n``CumeDist``\n------------\n\n.. class:: CumeDist(*expressions, **extra)\n\nCalculates the cumulative distribution of a value within a window or partition.\nThe cumulative distribution is defined as the number of rows preceding or\npeered with the current row divided by the total number of rows in the frame.\n\n``DenseRank``\n-------------\n\n.. class:: DenseRank(*expressions, **extra)\n\nEquivalent to :class:`Rank` but does not have gaps.\n\n``FirstValue``\n--------------\n\n.. class:: FirstValue(expression, **extra)\n\nReturns the value evaluated at the row that's the first row of the window\nframe, or ``None`` if no such value exists.\n\n``Lag``\n-------\n\n.. class:: Lag(expression, offset=1, default=None, **extra)\n\nCalculates the value offset by ``offset``, and if no row exists there, returns\n``default``.\n\n``default`` must have the same type as the ``expression``, however, this is\nonly validated by the database and not in Python.\n\n.. admonition:: MariaDB and ``default``\n\n    MariaDB `doesn't support <https://jira.mariadb.org/browse/MDEV-12981>`_\n    the ``default`` parameter.\n\n``LastValue``\n-------------\n\n.. class:: LastValue(expression, **extra)\n\nComparable to :class:`FirstValue`, it calculates the last value in a given\nframe clause.\n\n``Lead``\n--------\n\n.. class:: Lead(expression, offset=1, default=None, **extra)\n\nCalculates the leading value in a given :ref:`frame <window-frames>`. Both\n``offset`` and ``default`` are evaluated with respect to the current row.\n\n``default`` must have the same type as the ``expression``, however, this is\nonly validated by the database and not in Python.\n\n.. admonition:: MariaDB and ``default``\n\n    MariaDB `doesn't support <https://jira.mariadb.org/browse/MDEV-12981>`_\n    the ``default`` parameter.\n\n``NthValue``\n------------\n\n.. class:: NthValue(expression, nth=1, **extra)\n\nComputes the row relative to the offset ``nth`` (must be a positive value)\nwithin the window. Returns ``None`` if no row exists.\n\nSome databases may handle a nonexistent nth-value differently. For example,\nOracle returns an empty string rather than ``None`` for character-based\nexpressions. Django doesn't do any conversions in these cases.\n\n``Ntile``\n---------\n\n.. class:: Ntile(num_buckets=1, **extra)\n\nCalculates a partition for each of the rows in the frame clause, distributing\nnumbers as evenly as possible between 1 and ``num_buckets``. If the rows don't\ndivide evenly into a number of buckets, one or more buckets will be represented\nmore frequently.\n\n``PercentRank``\n---------------\n\n.. class:: PercentRank(*expressions, **extra)\n\nComputes the percentile rank of the rows in the frame clause. This\ncomputation is equivalent to evaluating::\n\n    (rank - 1) / (total rows - 1)\n\nThe following table explains the calculation for the percentile rank of a row:\n\n===== ===== ==== ============ ============\nRow # Value Rank Calculation  Percent Rank\n===== ===== ==== ============ ============\n1     15    1    (1-1)/(7-1)  0.0000\n2     20    2    (2-1)/(7-1)  0.1666\n3     20    2    (2-1)/(7-1)  0.1666\n4     20    2    (2-1)/(7-1)  0.1666\n5     30    5    (5-1)/(7-1)  0.6666\n6     30    5    (5-1)/(7-1)  0.6666\n7     40    7    (7-1)/(7-1)  1.0000\n===== ===== ==== ============ ============\n\n``Rank``\n--------\n\n.. class:: Rank(*expressions, **extra)\n\nComparable to ``RowNumber``, this function ranks rows in the window. The\ncomputed rank contains gaps. Use :class:`DenseRank` to compute rank without\ngaps.\n\n``RowNumber``\n-------------\n\n.. class:: RowNumber(*expressions, **extra)\n\nComputes the row number according to the ordering of either the frame clause\nor the ordering of the whole query if there is no partitioning of the\n:ref:`window frame <window-frames>`.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":87,"nodeType":"TextFile","repoName":null,"name":"constraints.txt","path":"docs/ref/models","text":"=====================\nConstraints reference\n=====================\n\n.. module:: django.db.models.constraints\n\n.. currentmodule:: django.db.models\n\nThe classes defined in this module create database constraints. They are added\nin the model :attr:`Meta.constraints <django.db.models.Options.constraints>`\noption.\n\n.. admonition:: Referencing built-in constraints\n\n    Constraints are defined in ``django.db.models.constraints``, but for\n    convenience they're imported into :mod:`django.db.models`. The standard\n    convention is to use ``from django.db import models`` and refer to the\n    constraints as ``models.<Foo>Constraint``.\n\n.. admonition:: Constraints in abstract base classes\n\n    You must always specify a unique name for the constraint. As such, you\n    cannot normally specify a constraint on an abstract base class, since the\n    :attr:`Meta.constraints <django.db.models.Options.constraints>` option is\n    inherited by subclasses, with exactly the same values for the attributes\n    (including ``name``) each time. To work around name collisions, part of the\n    name may contain ``'%(app_label)s'`` and ``'%(class)s'``, which are\n    replaced, respectively, by the lowercased app label and class name of the\n    concrete model. For example ``CheckConstraint(check=Q(age__gte=18),\n    name='%(app_label)s_%(class)s_is_adult')``.\n\n.. admonition:: Validation of Constraints\n\n    In general constraints are **not** checked during ``full_clean()``, and do\n    not raise ``ValidationError``\\s. Rather you'll get a database integrity\n    error on ``save()``. ``UniqueConstraint``\\s without a\n    :attr:`~UniqueConstraint.condition` (i.e. non-partial unique constraints)\n    are different in this regard, in that they leverage the existing\n    ``validate_unique()`` logic, and thus enable two-stage validation. In\n    addition to ``IntegrityError`` on ``save()``, ``ValidationError`` is also\n    raised during model validation when the ``UniqueConstraint`` is violated.\n\n``CheckConstraint``\n===================\n\n.. class:: CheckConstraint(*, check, name)\n\n    Creates a check constraint in the database.\n\n``check``\n---------\n\n.. attribute:: CheckConstraint.check\n\nA :class:`Q` object or boolean :class:`~django.db.models.Expression` that\nspecifies the check you want the constraint to enforce.\n\nFor example, ``CheckConstraint(check=Q(age__gte=18), name='age_gte_18')``\nensures the age field is never less than 18.\n\n.. versionchanged:: 3.1\n\n    Support for boolean :class:`~django.db.models.Expression` was added.\n\n``name``\n--------\n\n.. attribute:: CheckConstraint.name\n\nThe name of the constraint.\n\n``UniqueConstraint``\n====================\n\n.. class:: UniqueConstraint(*, fields, name, condition=None, deferrable=None)\n\n    Creates a unique constraint in the database.\n\n``fields``\n----------\n\n.. attribute:: UniqueConstraint.fields\n\nA list of field names that specifies the unique set of columns you want the\nconstraint to enforce.\n\nFor example, ``UniqueConstraint(fields=['room', 'date'],\nname='unique_booking')`` ensures each room can only be booked once for each\ndate.\n\n``name``\n--------\n\n.. attribute:: UniqueConstraint.name\n\nThe name of the constraint.\n\n``condition``\n-------------\n\n.. attribute:: UniqueConstraint.condition\n\nA :class:`Q` object that specifies the condition you want the constraint to\nenforce.\n\nFor example::\n\n    UniqueConstraint(fields=['user'], condition=Q(status='DRAFT'), name='unique_draft_user')\n\nensures that each user only has one draft.\n\nThese conditions have the same database restrictions as\n:attr:`Index.condition`.\n\n``deferrable``\n--------------\n\n.. attribute:: UniqueConstraint.deferrable\n\n.. versionadded:: 3.1\n\nSet this parameter to create a deferrable unique constraint. Accepted values\nare ``Deferrable.DEFERRED`` or ``Deferrable.IMMEDIATE``. For example::\n\n    from django.db.models import Deferrable, UniqueConstraint\n\n    UniqueConstraint(\n        name='unique_order',\n        fields=['order'],\n        deferrable=Deferrable.DEFERRED,\n    )\n\nBy default constraints are not deferred. A deferred constraint will not be\nenforced until the end of the transaction. An immediate constraint will be\nenforced immediately after every command.\n\n.. admonition:: MySQL, MariaDB, and SQLite.\n\n    Deferrable unique constraints are ignored on MySQL, MariaDB, and SQLite as\n    neither supports them.\n\n.. warning::\n\n    Deferred unique constraints may lead to a `performance penalty\n    <https://www.postgresql.org/docs/current/sql-createtable.html#id-1.9.3.85.9.4>`_.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":88,"nodeType":"Package","repoName":null,"name":"docs/ref/contrib","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":89,"nodeType":"TextFile","repoName":null,"name":"humanize.txt","path":"docs/ref/contrib","text":"===========================\n``django.contrib.humanize``\n===========================\n\n.. module:: django.contrib.humanize\n   :synopsis: A set of Django template filters useful for adding a \"human\n              touch\" to data.\n\nA set of Django template filters useful for adding a \"human touch\" to data.\n\nTo activate these filters, add ``'django.contrib.humanize'`` to your\n:setting:`INSTALLED_APPS` setting. Once you've done that, use\n``{% load humanize %}`` in a template, and you'll have access to the following\nfilters.\n\n.. templatefilter:: apnumber\n\n``apnumber``\n============\n\nFor numbers 1-9, returns the number spelled out. Otherwise, returns the\nnumber. This follows Associated Press style.\n\nExamples:\n\n* ``1`` becomes ``one``.\n* ``2`` becomes ``two``.\n* ``10`` becomes ``10``.\n\nYou can pass in either an integer or a string representation of an integer.\n\n.. templatefilter:: intcomma\n\n``intcomma``\n============\n\nConverts an integer or float (or a string representation of either) to a string\ncontaining commas every three digits.\n\nExamples:\n\n* ``4500`` becomes ``4,500``.\n* ``4500.2`` becomes ``4,500.2``.\n* ``45000`` becomes ``45,000``.\n* ``450000`` becomes ``450,000``.\n* ``4500000`` becomes ``4,500,000``.\n\n:doc:`/topics/i18n/formatting` will be respected if enabled,\ne.g. with the ``'de'`` language:\n\n* ``45000`` becomes ``'45.000'``.\n* ``450000`` becomes ``'450.000'``.\n\n.. templatefilter:: intword\n\n``intword``\n===========\n\nConverts a large integer (or a string representation of an integer) to a\nfriendly text representation. Translates ``1.0`` as a singular phrase and all\nother numeric values as plural, this may be incorrect for some languages. Works\nbest for numbers over 1 million.\n\nExamples:\n\n* ``1000000`` becomes ``1.0 million``.\n* ``1200000`` becomes ``1.2 million``.\n* ``1200000000`` becomes ``1.2 billion``.\n* ``-1200000000`` becomes ``-1.2 billion``.\n\nValues up to 10^100 (Googol) are supported.\n\n:doc:`/topics/i18n/formatting` will be respected if enabled,\ne.g. with the ``'de'`` language:\n\n* ``1000000`` becomes ``'1,0 Million'``.\n* ``1200000`` becomes ``'1,2 Millionen'``.\n* ``1200000000`` becomes ``'1,2 Milliarden'``.\n* ``-1200000000`` becomes ``'-1,2 Milliarden'``.\n\n.. versionchanged:: 3.1\n\n    Support for negative integers was added.\n\n.. templatefilter:: naturalday\n\n``naturalday``\n==============\n\nFor dates that are the current day or within one day, return \"today\",\n\"tomorrow\" or \"yesterday\", as appropriate. Otherwise, format the date using\nthe passed in format string.\n\n**Argument:** Date formatting string as described in the :tfilter:`date` tag.\n\nExamples (when 'today' is 17 Feb 2007):\n\n* ``16 Feb 2007`` becomes ``yesterday``.\n* ``17 Feb 2007`` becomes ``today``.\n* ``18 Feb 2007`` becomes ``tomorrow``.\n* Any other day is formatted according to given argument or the\n  :setting:`DATE_FORMAT` setting if no argument is given.\n\n.. templatefilter:: naturaltime\n\n``naturaltime``\n===============\n\nFor datetime values, returns a string representing how many seconds,\nminutes or hours ago it was -- falling back to the :tfilter:`timesince`\nformat if the value is more than a day old. In case the datetime value is in\nthe future the return value will automatically use an appropriate phrase.\n\nExamples (when 'now' is 17 Feb 2007 16:30:00):\n\n* ``17 Feb 2007 16:30:00`` becomes ``now``.\n* ``17 Feb 2007 16:29:31`` becomes ``29 seconds ago``.\n* ``17 Feb 2007 16:29:00`` becomes ``a minute ago``.\n* ``17 Feb 2007 16:25:35`` becomes ``4 minutes ago``.\n* ``17 Feb 2007 15:30:29`` becomes ``59 minutes ago``.\n* ``17 Feb 2007 15:30:01`` becomes ``59 minutes ago``.\n* ``17 Feb 2007 15:30:00`` becomes ``an hour ago``.\n* ``17 Feb 2007 13:31:29`` becomes ``2 hours ago``.\n* ``16 Feb 2007 13:31:29`` becomes ``1 day, 2 hours ago``.\n* ``16 Feb 2007 13:30:01`` becomes ``1 day, 2 hours ago``.\n* ``16 Feb 2007 13:30:00`` becomes ``1 day, 3 hours ago``.\n* ``17 Feb 2007 16:30:30`` becomes ``30 seconds from now``.\n* ``17 Feb 2007 16:30:29`` becomes ``29 seconds from now``.\n* ``17 Feb 2007 16:31:00`` becomes ``a minute from now``.\n* ``17 Feb 2007 16:34:35`` becomes ``4 minutes from now``.\n* ``17 Feb 2007 17:30:29`` becomes ``an hour from now``.\n* ``17 Feb 2007 18:31:29`` becomes ``2 hours from now``.\n* ``18 Feb 2007 16:31:29`` becomes ``1 day from now``.\n* ``26 Feb 2007 18:31:29`` becomes ``1 week, 2 days from now``.\n\n.. templatefilter:: ordinal\n\n``ordinal``\n===========\n\nConverts an integer to its ordinal as a string.\n\nExamples:\n\n* ``1`` becomes ``1st``.\n* ``2`` becomes ``2nd``.\n* ``3`` becomes ``3rd``.\n\nYou can pass in either an integer or a string representation of an integer.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":90,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/ref/models","text":"======\nModels\n======\n\nModel API reference. For introductory material, see :doc:`/topics/db/models`.\n\n.. toctree::\n   :maxdepth: 1\n\n   fields\n   indexes\n   constraints\n   meta\n   relations\n   class\n   options\n   instances\n   querysets\n   lookups\n   expressions\n   conditional-expressions\n   database-functions\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":91,"nodeType":"TextFile","repoName":null,"name":"meta.txt","path":"docs/ref/models","text":"===================\nModel ``_meta`` API\n===================\n\n.. module:: django.db.models.options\n   :synopsis: Model meta-class layer\n\n.. class:: Options\n\nThe model ``_meta`` API is at the core of the Django ORM. It enables other\nparts of the system such as lookups, queries, forms, and the admin to\nunderstand the capabilities of each model. The API is accessible through\nthe ``_meta`` attribute of each model class, which is an instance of an\n``django.db.models.options.Options`` object.\n\nMethods that it provides can be used to:\n\n* Retrieve all field instances of a model\n* Retrieve a single field instance of a model by name\n\n.. _model-meta-field-api:\n\nField access API\n================\n\nRetrieving a single field instance of a model by name\n-----------------------------------------------------\n\n.. method:: Options.get_field(field_name)\n\n    Returns the field instance given a name of a field.\n\n    ``field_name`` can be the name of a field on the model, a field\n    on an abstract or inherited model, or a field defined on another\n    model that points to the model. In the latter case, the ``field_name``\n    will be (in order of preference) the :attr:`~.ForeignKey.related_query_name`\n    set by the user, the :attr:`~.ForeignKey.related_name` set by the user, or\n    the name automatically generated by Django.\n\n    :attr:`Hidden fields <django.db.models.Field.hidden>` cannot be retrieved\n    by name.\n\n    If a field with the given name is not found a\n    :class:`~django.core.exceptions.FieldDoesNotExist` exception will be\n    raised.\n\n    .. code-block:: python\n\n        >>> from django.contrib.auth.models import User\n\n        # A field on the model\n        >>> User._meta.get_field('username')\n        <django.db.models.fields.CharField: username>\n\n        # A field from another model that has a relation with the current model\n        >>> User._meta.get_field('logentry')\n        <ManyToOneRel: admin.logentry>\n\n        # A non existent field\n        >>> User._meta.get_field('does_not_exist')\n        Traceback (most recent call last):\n            ...\n        FieldDoesNotExist: User has no field named 'does_not_exist'\n\nRetrieving all field instances of a model\n-----------------------------------------\n\n.. method:: Options.get_fields(include_parents=True, include_hidden=False)\n\n    Returns a tuple of fields associated with a model. ``get_fields()`` accepts\n    two parameters that can be used to control which fields are returned:\n\n    ``include_parents``\n        ``True`` by default. Recursively includes fields defined on parent\n        classes. If set to ``False``, ``get_fields()`` will only search for\n        fields declared directly on the current model. Fields from models that\n        directly inherit from abstract models or proxy classes are considered\n        to be local, not on the parent.\n\n    ``include_hidden``\n        ``False`` by default. If set to ``True``, ``get_fields()`` will include\n        fields that are used to back other field's functionality. This will\n        also include any fields that have a ``related_name`` (such\n        as :class:`~django.db.models.ManyToManyField`, or\n        :class:`~django.db.models.ForeignKey`) that start with a \"+\".\n\n    .. code-block:: python\n\n        >>> from django.contrib.auth.models import User\n        >>> User._meta.get_fields()\n        (<ManyToOneRel: admin.logentry>,\n         <django.db.models.fields.AutoField: id>,\n         <django.db.models.fields.CharField: password>,\n         <django.db.models.fields.DateTimeField: last_login>,\n         <django.db.models.fields.BooleanField: is_superuser>,\n         <django.db.models.fields.CharField: username>,\n         <django.db.models.fields.CharField: first_name>,\n         <django.db.models.fields.CharField: last_name>,\n         <django.db.models.fields.EmailField: email>,\n         <django.db.models.fields.BooleanField: is_staff>,\n         <django.db.models.fields.BooleanField: is_active>,\n         <django.db.models.fields.DateTimeField: date_joined>,\n         <django.db.models.fields.related.ManyToManyField: groups>,\n         <django.db.models.fields.related.ManyToManyField: user_permissions>)\n\n        # Also include hidden fields.\n        >>> User._meta.get_fields(include_hidden=True)\n        (<ManyToOneRel: auth.user_groups>,\n         <ManyToOneRel: auth.user_user_permissions>,\n         <ManyToOneRel: admin.logentry>,\n         <django.db.models.fields.AutoField: id>,\n         <django.db.models.fields.CharField: password>,\n         <django.db.models.fields.DateTimeField: last_login>,\n         <django.db.models.fields.BooleanField: is_superuser>,\n         <django.db.models.fields.CharField: username>,\n         <django.db.models.fields.CharField: first_name>,\n         <django.db.models.fields.CharField: last_name>,\n         <django.db.models.fields.EmailField: email>,\n         <django.db.models.fields.BooleanField: is_staff>,\n         <django.db.models.fields.BooleanField: is_active>,\n         <django.db.models.fields.DateTimeField: date_joined>,\n         <django.db.models.fields.related.ManyToManyField: groups>,\n         <django.db.models.fields.related.ManyToManyField: user_permissions>)\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":92,"nodeType":"TextFile","repoName":null,"name":"relations.txt","path":"docs/ref/models","text":"=========================\nRelated objects reference\n=========================\n\n.. currentmodule:: django.db.models.fields.related\n\n.. class:: RelatedManager\n\n    A \"related manager\" is a manager used in a one-to-many or many-to-many\n    related context. This happens in two cases:\n\n    * The \"other side\" of a :class:`~django.db.models.ForeignKey` relation.\n      That is::\n\n            from django.db import models\n\n            class Reporter(models.Model):\n                # ...\n                pass\n\n            class Article(models.Model):\n                reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)\n\n      In the above example, the methods below will be available on\n      the manager ``reporter.article_set``.\n\n    * Both sides of a :class:`~django.db.models.ManyToManyField` relation::\n\n            class Topping(models.Model):\n                # ...\n                pass\n\n            class Pizza(models.Model):\n                toppings = models.ManyToManyField(Topping)\n\n      In this example, the methods below will be available both on\n      ``topping.pizza_set`` and on ``pizza.toppings``.\n\n    .. method:: add(*objs, bulk=True, through_defaults=None)\n\n        Adds the specified model objects to the related object set.\n\n        Example::\n\n            >>> b = Blog.objects.get(id=1)\n            >>> e = Entry.objects.get(id=234)\n            >>> b.entry_set.add(e) # Associates Entry e with Blog b.\n\n        In the example above, in the case of a\n        :class:`~django.db.models.ForeignKey` relationship,\n        :meth:`QuerySet.update() <django.db.models.query.QuerySet.update>`\n        is used to perform the update. This requires the objects to already be\n        saved.\n\n        You can use the ``bulk=False`` argument to instead have the related\n        manager perform the update by calling ``e.save()``.\n\n        Using ``add()`` with a many-to-many relationship, however, will not\n        call any ``save()`` methods (the ``bulk`` argument doesn't exist), but\n        rather create the relationships using :meth:`QuerySet.bulk_create()\n        <django.db.models.query.QuerySet.bulk_create>`. If you need to execute\n        some custom logic when a relationship is created, listen to the\n        :data:`~django.db.models.signals.m2m_changed` signal, which will\n        trigger ``pre_add`` and ``post_add`` actions.\n\n        Using ``add()`` on a relation that already exists won't duplicate the\n        relation, but it will still trigger signals.\n\n        For many-to-many relationships ``add()`` accepts either model instances\n        or field values, normally primary keys, as the ``*objs`` argument.\n\n        Use the ``through_defaults`` argument to specify values for the new\n        :ref:`intermediate model <intermediary-manytomany>` instance(s), if\n        needed. You can use callables as values in the ``through_defaults``\n        dictionary and they will be evaluated once before creating any\n        intermediate instance(s).\n\n        .. versionchanged:: 3.1\n\n            ``through_defaults`` values can now be callables.\n\n    .. method:: create(through_defaults=None, **kwargs)\n\n        Creates a new object, saves it and puts it in the related object set.\n        Returns the newly created object::\n\n            >>> b = Blog.objects.get(id=1)\n            >>> e = b.entry_set.create(\n            ...     headline='Hello',\n            ...     body_text='Hi',\n            ...     pub_date=datetime.date(2005, 1, 1)\n            ... )\n\n            # No need to call e.save() at this point -- it's already been saved.\n\n        This is equivalent to (but simpler than)::\n\n            >>> b = Blog.objects.get(id=1)\n            >>> e = Entry(\n            ...     blog=b,\n            ...     headline='Hello',\n            ...     body_text='Hi',\n            ...     pub_date=datetime.date(2005, 1, 1)\n            ... )\n            >>> e.save(force_insert=True)\n\n        Note that there's no need to specify the keyword argument of the model\n        that defines the relationship. In the above example, we don't pass the\n        parameter ``blog`` to ``create()``. Django figures out that the new\n        ``Entry`` object's ``blog`` field should be set to ``b``.\n\n        Use the ``through_defaults`` argument to specify values for the new\n        :ref:`intermediate model <intermediary-manytomany>` instance, if\n        needed. You can use callables as values in the ``through_defaults``\n        dictionary.\n\n        .. versionchanged:: 3.1\n\n            ``through_defaults`` values can now be callables.\n\n    .. method:: remove(*objs, bulk=True)\n\n        Removes the specified model objects from the related object set::\n\n            >>> b = Blog.objects.get(id=1)\n            >>> e = Entry.objects.get(id=234)\n            >>> b.entry_set.remove(e) # Disassociates Entry e from Blog b.\n\n        Similar to :meth:`add()`, ``e.save()`` is called in the example above\n        to perform the update. Using ``remove()`` with a many-to-many\n        relationship, however, will delete the relationships using\n        :meth:`QuerySet.delete()<django.db.models.query.QuerySet.delete>` which\n        means no model ``save()`` methods are called; listen to the\n        :data:`~django.db.models.signals.m2m_changed` signal if you wish to\n        execute custom code when a relationship is deleted.\n\n        For many-to-many relationships ``remove()`` accepts either model\n        instances or field values, normally primary keys, as the ``*objs``\n        argument.\n\n        For :class:`~django.db.models.ForeignKey` objects, this method only\n        exists if ``null=True``. If the related field can't be set to ``None``\n        (``NULL``), then an object can't be removed from a relation without\n        being added to another. In the above example, removing ``e`` from\n        ``b.entry_set()`` is equivalent to doing ``e.blog = None``, and because\n        the ``blog`` :class:`~django.db.models.ForeignKey` doesn't have\n        ``null=True``, this is invalid.\n\n        For :class:`~django.db.models.ForeignKey` objects, this method accepts\n        a ``bulk`` argument to control how to perform the operation.\n        If ``True`` (the default), ``QuerySet.update()`` is used.\n        If ``bulk=False``, the ``save()`` method of each individual model\n        instance is called instead. This triggers the\n        :data:`~django.db.models.signals.pre_save` and\n        :data:`~django.db.models.signals.post_save` signals and comes at the\n        expense of performance.\n\n        For many-to-many relationships, the ``bulk`` keyword argument doesn't\n        exist.\n\n    .. method:: clear(bulk=True)\n\n        Removes all objects from the related object set::\n\n            >>> b = Blog.objects.get(id=1)\n            >>> b.entry_set.clear()\n\n        Note this doesn't delete the related objects -- it just disassociates\n        them.\n\n        Just like ``remove()``, ``clear()`` is only available on\n        :class:`~django.db.models.ForeignKey`\\s where ``null=True`` and it also\n        accepts the ``bulk`` keyword argument.\n\n        For many-to-many relationships, the ``bulk`` keyword argument doesn't\n        exist.\n\n    .. method:: set(objs, bulk=True, clear=False, through_defaults=None)\n\n        Replace the set of related objects::\n\n            >>> new_list = [obj1, obj2, obj3]\n            >>> e.related_set.set(new_list)\n\n        This method accepts a ``clear`` argument to control how to perform the\n        operation. If ``False`` (the default), the elements missing from the\n        new set are removed using ``remove()`` and only the new ones are added.\n        If ``clear=True``, the ``clear()`` method is called instead and the\n        whole set is added at once.\n\n        For :class:`~django.db.models.ForeignKey` objects, the ``bulk``\n        argument is passed on to :meth:`add` and :meth:`remove`.\n\n        For many-to-many relationships, the ``bulk`` keyword argument doesn't\n        exist.\n\n        Note that since ``set()`` is a compound operation, it is subject to\n        race conditions. For instance, new objects may be added to the database\n        in between the call to ``clear()`` and the call to ``add()``.\n\n        For many-to-many relationships ``set()`` accepts a list of either model\n        instances or field values, normally primary keys, as the ``objs``\n        argument.\n\n        Use the ``through_defaults`` argument to specify values for the new\n        :ref:`intermediate model <intermediary-manytomany>` instance(s), if\n        needed. You can use callables as values in the ``through_defaults``\n        dictionary and they will be evaluated once before creating any\n        intermediate instance(s).\n\n        .. versionchanged:: 3.1\n\n            ``through_defaults`` values can now be callables.\n\n    .. note::\n\n       Note that ``add()``, ``create()``, ``remove()``, ``clear()``, and\n       ``set()`` all apply database changes immediately for all types of\n       related fields. In other words, there is no need to call ``save()``\n       on either end of the relationship.\n\n       If you use :meth:`~django.db.models.query.QuerySet.prefetch_related`,\n       the ``add()``, ``remove()``, ``clear()``, and ``set()`` methods clear\n       the prefetched cache.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":93,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/ref/contrib","text":"====================\n``contrib`` packages\n====================\n\nDjango aims to follow Python's :ref:`\"batteries included\" philosophy\n<tut-batteries-included>`. It ships with a variety of extra, optional tools\nthat solve common Web-development problems.\n\nThis code lives in ``django/contrib`` in the Django distribution. This document\ngives a rundown of the packages in ``contrib``, along with any dependencies\nthose packages have.\n\n.. admonition:: Note\n\n    For most of these add-ons -- specifically, the add-ons that include either\n    models or template tags -- you'll need to add the package name (e.g.,\n    ``'django.contrib.redirects'``) to your :setting:`INSTALLED_APPS` setting\n    and re-run ``manage.py migrate``.\n\n.. toctree::\n   :maxdepth: 1\n\n   admin/index\n   auth\n   contenttypes\n   flatpages\n   gis/index\n   humanize\n   messages\n   postgres/index\n   redirects\n   sitemaps\n   sites\n   staticfiles\n   syndication\n\n``admin``\n=========\n\nThe automatic Django administrative interface. For more information, see\n:doc:`Tutorial 2 </intro/tutorial02>` and the\n:doc:`admin documentation </ref/contrib/admin/index>`.\n\nRequires the auth_ and contenttypes_ contrib packages to be installed.\n\n``auth``\n========\n\nDjango's authentication framework.\n\nSee :doc:`/topics/auth/index`.\n\n``contenttypes``\n================\n\nA light framework for hooking into \"types\" of content, where each installed\nDjango model is a separate content type.\n\nSee the :doc:`contenttypes documentation </ref/contrib/contenttypes>`.\n\n``flatpages``\n=============\n\nA framework for managing \"flat\" HTML content in a database.\n\nSee the :doc:`flatpages documentation </ref/contrib/flatpages>`.\n\nRequires the sites_ contrib package to be installed as well.\n\n``gis``\n=======\n\nA world-class geospatial framework built on top of Django, that enables\nstorage, manipulation and display of spatial data.\n\nSee the :doc:`/ref/contrib/gis/index` documentation for more.\n\n``humanize``\n============\n\nA set of Django template filters useful for adding a \"human touch\" to data.\n\nSee the :doc:`humanize documentation </ref/contrib/humanize>`.\n\n``messages``\n============\n\nA framework for storing and retrieving temporary cookie- or session-based\nmessages\n\nSee the :doc:`messages documentation </ref/contrib/messages>`.\n\n``postgres``\n============\n\nA collection of PostgreSQL specific features.\n\nSee the :doc:`contrib.postgres documentation </ref/contrib/postgres/index>`.\n\n``redirects``\n=============\n\nA framework for managing redirects.\n\nSee the :doc:`redirects documentation </ref/contrib/redirects>`.\n\n``sessions``\n============\n\nA framework for storing data in anonymous sessions.\n\nSee the :doc:`sessions documentation </topics/http/sessions>`.\n\n``sites``\n=========\n\nA light framework that lets you operate multiple websites off of the same\ndatabase and Django installation. It gives you hooks for associating objects to\none or more sites.\n\nSee the :doc:`sites documentation </ref/contrib/sites>`.\n\n``sitemaps``\n============\n\nA framework for generating Google sitemap XML files.\n\nSee the :doc:`sitemaps documentation </ref/contrib/sitemaps>`.\n\n``syndication``\n===============\n\nA framework for generating syndication feeds, in RSS and Atom, quite easily.\n\nSee the :doc:`syndication documentation </ref/contrib/syndication>`.\n\nOther add-ons\n=============\n\nIf you have an idea for functionality to include in ``contrib``, let us know!\nCode it up, and post it to the |django-users| mailing list.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":94,"nodeType":"TextFile","repoName":null,"name":"fields.txt","path":"docs/ref/models","text":"=====================\nModel field reference\n=====================\n\n.. module:: django.db.models.fields\n   :synopsis: Built-in field types.\n\n.. currentmodule:: django.db.models\n\nThis document contains all the API references of :class:`Field` including the\n`field options`_ and `field types`_ Django offers.\n\n.. seealso::\n\n    If the built-in fields don't do the trick, you can try `django-localflavor\n    <https://github.com/django/django-localflavor>`_ (`documentation\n    <https://django-localflavor.readthedocs.io/>`_), which contains assorted\n    pieces of code that are useful for particular countries and cultures.\n\n    Also, you can easily :doc:`write your own custom model fields\n    </howto/custom-model-fields>`.\n\n.. note::\n\n    Technically, these models are defined in :mod:`django.db.models.fields`, but\n    for convenience they're imported into :mod:`django.db.models`; the standard\n    convention is to use ``from django.db import models`` and refer to fields as\n    ``models.<Foo>Field``.\n\n.. _common-model-field-options:\n\nField options\n=============\n\nThe following arguments are available to all field types. All are optional.\n\n``null``\n--------\n\n.. attribute:: Field.null\n\nIf ``True``, Django will store empty values as ``NULL`` in the database. Default\nis ``False``.\n\nAvoid using :attr:`~Field.null` on string-based fields such as\n:class:`CharField` and :class:`TextField`. If a string-based field has\n``null=True``, that means it has two possible values for \"no data\": ``NULL``,\nand the empty string. In most cases, it's redundant to have two possible values\nfor \"no data;\" the Django convention is to use the empty string, not\n``NULL``. One exception is when a :class:`CharField` has both ``unique=True``\nand ``blank=True`` set. In this situation, ``null=True`` is required to avoid\nunique constraint violations when saving multiple objects with blank values.\n\nFor both string-based and non-string-based fields, you will also need to\nset ``blank=True`` if you wish to permit empty values in forms, as the\n:attr:`~Field.null` parameter only affects database storage\n(see :attr:`~Field.blank`).\n\n.. note::\n\n    When using the Oracle database backend, the value ``NULL`` will be stored to\n    denote the empty string regardless of this attribute.\n\n``blank``\n---------\n\n.. attribute:: Field.blank\n\nIf ``True``, the field is allowed to be blank. Default is ``False``.\n\nNote that this is different than :attr:`~Field.null`. :attr:`~Field.null` is\npurely database-related, whereas :attr:`~Field.blank` is validation-related. If\na field has ``blank=True``, form validation will allow entry of an empty value.\nIf a field has ``blank=False``, the field will be required.\n\n.. _field-choices:\n\n``choices``\n-----------\n\n.. attribute:: Field.choices\n\nA :term:`sequence` consisting itself of iterables of exactly two items (e.g.\n``[(A, B), (A, B) ...]``) to use as choices for this field. If choices are\ngiven, they're enforced by :ref:`model validation <validating-objects>` and the\ndefault form widget will be a select box with these choices instead of the\nstandard text field.\n\nThe first element in each tuple is the actual value to be set on the model,\nand the second element is the human-readable name. For example::\n\n    YEAR_IN_SCHOOL_CHOICES = [\n        ('FR', 'Freshman'),\n        ('SO', 'Sophomore'),\n        ('JR', 'Junior'),\n        ('SR', 'Senior'),\n        ('GR', 'Graduate'),\n    ]\n\nGenerally, it's best to define choices inside a model class, and to\ndefine a suitably-named constant for each value::\n\n    from django.db import models\n\n    class Student(models.Model):\n        FRESHMAN = 'FR'\n        SOPHOMORE = 'SO'\n        JUNIOR = 'JR'\n        SENIOR = 'SR'\n        GRADUATE = 'GR'\n        YEAR_IN_SCHOOL_CHOICES = [\n            (FRESHMAN, 'Freshman'),\n            (SOPHOMORE, 'Sophomore'),\n            (JUNIOR, 'Junior'),\n            (SENIOR, 'Senior'),\n            (GRADUATE, 'Graduate'),\n        ]\n        year_in_school = models.CharField(\n            max_length=2,\n            choices=YEAR_IN_SCHOOL_CHOICES,\n            default=FRESHMAN,\n        )\n\n        def is_upperclass(self):\n            return self.year_in_school in {self.JUNIOR, self.SENIOR}\n\nThough you can define a choices list outside of a model class and then\nrefer to it, defining the choices and names for each choice inside the\nmodel class keeps all of that information with the class that uses it,\nand helps reference the choices (e.g, ``Student.SOPHOMORE``\nwill work anywhere that the ``Student`` model has been imported).\n\n.. _field-choices-named-groups:\n\nYou can also collect your available choices into named groups that can\nbe used for organizational purposes::\n\n    MEDIA_CHOICES = [\n        ('Audio', (\n                ('vinyl', 'Vinyl'),\n                ('cd', 'CD'),\n            )\n        ),\n        ('Video', (\n                ('vhs', 'VHS Tape'),\n                ('dvd', 'DVD'),\n            )\n        ),\n        ('unknown', 'Unknown'),\n    ]\n\nThe first element in each tuple is the name to apply to the group. The\nsecond element is an iterable of 2-tuples, with each 2-tuple containing\na value and a human-readable name for an option. Grouped options may be\ncombined with ungrouped options within a single list (such as the\n``'unknown'`` option in this example).\n\nFor each model field that has :attr:`~Field.choices` set, Django will add a\nmethod to retrieve the human-readable name for the field's current value. See\n:meth:`~django.db.models.Model.get_FOO_display` in the database API\ndocumentation.\n\nNote that choices can be any sequence object -- not necessarily a list or\ntuple. This lets you construct choices dynamically. But if you find yourself\nhacking :attr:`~Field.choices` to be dynamic, you're probably better off using\na proper database table with a :class:`ForeignKey`. :attr:`~Field.choices` is\nmeant for static data that doesn't change much, if ever.\n\n.. note::\n    A new migration is created each time the order of ``choices`` changes.\n\n.. _field-choices-blank-label:\n\nUnless :attr:`blank=False<Field.blank>` is set on the field along with a\n:attr:`~Field.default` then a label containing ``\"---------\"`` will be rendered\nwith the select box. To override this behavior, add a tuple to ``choices``\ncontaining ``None``; e.g. ``(None, 'Your String For Display')``.\nAlternatively, you can use an empty string instead of ``None`` where this makes\nsense - such as on a :class:`~django.db.models.CharField`.\n\n.. _field-choices-enum-types:\n\nEnumeration types\n~~~~~~~~~~~~~~~~~\n\nIn addition, Django provides enumeration types that you can subclass to define\nchoices in a concise way::\n\n    from django.utils.translation import gettext_lazy as _\n\n    class Student(models.Model):\n\n        class YearInSchool(models.TextChoices):\n            FRESHMAN = 'FR', _('Freshman')\n            SOPHOMORE = 'SO', _('Sophomore')\n            JUNIOR = 'JR', _('Junior')\n            SENIOR = 'SR', _('Senior')\n            GRADUATE = 'GR', _('Graduate')\n\n        year_in_school = models.CharField(\n            max_length=2,\n            choices=YearInSchool.choices,\n            default=YearInSchool.FRESHMAN,\n        )\n\n        def is_upperclass(self):\n            return self.year_in_school in {\n                self.YearInSchool.JUNIOR,\n                self.YearInSchool.SENIOR,\n            }\n\nThese work similar to :mod:`enum` from Python's standard library, but with some\nmodifications:\n\n* Enum member values are a tuple of arguments to use when constructing the\n  concrete data type. Django supports adding an extra string value to the end\n  of this tuple to be used as the human-readable name, or ``label``. The\n  ``label`` can be a lazy translatable string. Thus, in most cases, the member\n  value will be a ``(value, label)`` two-tuple. See below for :ref:`an example\n  of subclassing choices <field-choices-enum-subclassing>` using a more complex\n  data type. If a tuple is not provided, or the last item is not a (lazy)\n  string, the ``label`` is :ref:`automatically generated\n  <field-choices-enum-auto-label>` from the member name.\n* A ``.label`` property is added on values, to return the human-readable name.\n* A number of custom properties are added to the enumeration classes --\n  ``.choices``, ``.labels``, ``.values``, and ``.names`` -- to make it easier\n  to access lists of those separate parts of the enumeration. Use ``.choices``\n  as a suitable value to pass to :attr:`~Field.choices` in a field definition.\n* The use of :func:`enum.unique()` is enforced to ensure that values cannot be\n  defined multiple times. This is unlikely to be expected in choices for a\n  field.\n\nNote that using ``YearInSchool.SENIOR``, ``YearInSchool['SENIOR']``, or\n``YearInSchool('SR')`` to access or lookup enum members work as expected, as do\nthe ``.name`` and ``.value`` properties on the members.\n\n.. _field-choices-enum-auto-label:\n\nIf you don't need to have the human-readable names translated, you can have\nthem inferred from the member name (replacing underscores with spaces and using\ntitle-case)::\n\n    >>> class Vehicle(models.TextChoices):\n    ...     CAR = 'C'\n    ...     TRUCK = 'T'\n    ...     JET_SKI = 'J'\n    ...\n    >>> Vehicle.JET_SKI.label\n    'Jet Ski'\n\nSince the case where the enum values need to be integers is extremely common,\nDjango provides an ``IntegerChoices`` class. For example::\n\n    class Card(models.Model):\n\n        class Suit(models.IntegerChoices):\n            DIAMOND = 1\n            SPADE = 2\n            HEART = 3\n            CLUB = 4\n\n        suit = models.IntegerField(choices=Suit.choices)\n\nIt is also possible to make use of the `Enum Functional API\n<https://docs.python.org/3/library/enum.html#functional-api>`_ with the caveat\nthat labels are automatically generated as highlighted above::\n\n    >>> MedalType = models.TextChoices('MedalType', 'GOLD SILVER BRONZE')\n    >>> MedalType.choices\n    [('GOLD', 'Gold'), ('SILVER', 'Silver'), ('BRONZE', 'Bronze')]\n    >>> Place = models.IntegerChoices('Place', 'FIRST SECOND THIRD')\n    >>> Place.choices\n    [(1, 'First'), (2, 'Second'), (3, 'Third')]\n\n.. _field-choices-enum-subclassing:\n\nIf you require support for a concrete data type other than ``int`` or ``str``,\nyou can subclass ``Choices`` and the required concrete data type, e.g.\n:class:`~datetime.date` for use with :class:`~django.db.models.DateField`::\n\n    class MoonLandings(datetime.date, models.Choices):\n        APOLLO_11 = 1969, 7, 20, 'Apollo 11 (Eagle)'\n        APOLLO_12 = 1969, 11, 19, 'Apollo 12 (Intrepid)'\n        APOLLO_14 = 1971, 2, 5, 'Apollo 14 (Antares)'\n        APOLLO_15 = 1971, 7, 30, 'Apollo 15 (Falcon)'\n        APOLLO_16 = 1972, 4, 21, 'Apollo 16 (Orion)'\n        APOLLO_17 = 1972, 12, 11, 'Apollo 17 (Challenger)'\n\nThere are some additional caveats to be aware of:\n\n- Enumeration types do not support :ref:`named groups\n  <field-choices-named-groups>`.\n- Because an enumeration with a concrete data type requires all values to match\n  the type, overriding the :ref:`blank label <field-choices-blank-label>`\n  cannot be achieved by creating a member with a value of ``None``. Instead,\n  set the ``__empty__`` attribute on the class::\n\n    class Answer(models.IntegerChoices):\n        NO = 0, _('No')\n        YES = 1, _('Yes')\n\n        __empty__ = _('(Unknown)')\n\n``db_column``\n-------------\n\n.. attribute:: Field.db_column\n\nThe name of the database column to use for this field. If this isn't given,\nDjango will use the field's name.\n\nIf your database column name is an SQL reserved word, or contains\ncharacters that aren't allowed in Python variable names -- notably, the\nhyphen -- that's OK. Django quotes column and table names behind the\nscenes.\n\n``db_index``\n------------\n\n.. attribute:: Field.db_index\n\nIf ``True``, a database index will be created for this field.\n\n``db_tablespace``\n-----------------\n\n.. attribute:: Field.db_tablespace\n\nThe name of the :doc:`database tablespace </topics/db/tablespaces>` to use for\nthis field's index, if this field is indexed. The default is the project's\n:setting:`DEFAULT_INDEX_TABLESPACE` setting, if set, or the\n:attr:`~Options.db_tablespace` of the model, if any. If the backend doesn't\nsupport tablespaces for indexes, this option is ignored.\n\n``default``\n-----------\n\n.. attribute:: Field.default\n\nThe default value for the field. This can be a value or a callable object. If\ncallable it will be called every time a new object is created.\n\nThe default can't be a mutable object (model instance, ``list``, ``set``, etc.),\nas a reference to the same instance of that object would be used as the default\nvalue in all new model instances. Instead, wrap the desired default in a\ncallable. For example, if you want to specify a default ``dict`` for\n:class:`~django.db.models.JSONField`, use a function::\n\n    def contact_default():\n        return {\"email\": \"to1@example.com\"}\n\n    contact_info = JSONField(\"ContactInfo\", default=contact_default)\n\n``lambda``\\s can't be used for field options like ``default`` because they\ncan't be :ref:`serialized by migrations <migration-serializing>`. See that\ndocumentation for other caveats.\n\nFor fields like :class:`ForeignKey` that map to model instances, defaults\nshould be the value of the field they reference (``pk`` unless\n:attr:`~ForeignKey.to_field` is set) instead of model instances.\n\nThe default value is used when new model instances are created and a value\nisn't provided for the field. When the field is a primary key, the default is\nalso used when the field is set to ``None``.\n\n``editable``\n------------\n\n.. attribute:: Field.editable\n\nIf ``False``, the field will not be displayed in the admin or any other\n:class:`~django.forms.ModelForm`. They are also skipped during :ref:`model\nvalidation <validating-objects>`. Default is ``True``.\n\n``error_messages``\n------------------\n\n.. attribute:: Field.error_messages\n\nThe ``error_messages`` argument lets you override the default messages that the\nfield will raise. Pass in a dictionary with keys matching the error messages you\nwant to override.\n\nError message keys include ``null``, ``blank``, ``invalid``, ``invalid_choice``,\n``unique``, and ``unique_for_date``. Additional error message keys are\nspecified for each field in the `Field types`_ section below.\n\nThese error messages often don't propagate to forms. See\n:ref:`considerations-regarding-model-errormessages`.\n\n``help_text``\n-------------\n\n.. attribute:: Field.help_text\n\nExtra \"help\" text to be displayed with the form widget. It's useful for\ndocumentation even if your field isn't used on a form.\n\nNote that this value is *not* HTML-escaped in automatically-generated\nforms. This lets you include HTML in :attr:`~Field.help_text` if you so\ndesire. For example::\n\n    help_text=\"Please use the following format: <em>YYYY-MM-DD</em>.\"\n\nAlternatively you can use plain text and\n:func:`django.utils.html.escape` to escape any HTML special characters. Ensure\nthat you escape any help text that may come from untrusted users to avoid a\ncross-site scripting attack.\n\n``primary_key``\n---------------\n\n.. attribute:: Field.primary_key\n\nIf ``True``, this field is the primary key for the model.\n\nIf you don't specify ``primary_key=True`` for any field in your model, Django\nwill automatically add an :class:`AutoField` to hold the primary key, so you\ndon't need to set ``primary_key=True`` on any of your fields unless you want to\noverride the default primary-key behavior. For more, see\n:ref:`automatic-primary-key-fields`.\n\n``primary_key=True`` implies :attr:`null=False <Field.null>` and\n:attr:`unique=True <Field.unique>`. Only one primary key is allowed on an\nobject.\n\nThe primary key field is read-only. If you change the value of the primary\nkey on an existing object and then save it, a new object will be created\nalongside the old one.\n\n``unique``\n----------\n\n.. attribute:: Field.unique\n\nIf ``True``, this field must be unique throughout the table.\n\nThis is enforced at the database level and by model validation. If\nyou try to save a model with a duplicate value in a :attr:`~Field.unique`\nfield, a :exc:`django.db.IntegrityError` will be raised by the model's\n:meth:`~django.db.models.Model.save` method.\n\nThis option is valid on all field types except :class:`ManyToManyField` and\n:class:`OneToOneField`.\n\nNote that when ``unique`` is ``True``, you don't need to specify\n:attr:`~Field.db_index`, because ``unique`` implies the creation of an index.\n\n``unique_for_date``\n-------------------\n\n.. attribute:: Field.unique_for_date\n\nSet this to the name of a :class:`DateField` or :class:`DateTimeField` to\nrequire that this field be unique for the value of the date field.\n\nFor example, if you have a field ``title`` that has\n``unique_for_date=\"pub_date\"``, then Django wouldn't allow the entry of two\nrecords with the same ``title`` and ``pub_date``.\n\nNote that if you set this to point to a :class:`DateTimeField`, only the date\nportion of the field will be considered. Besides, when :setting:`USE_TZ` is\n``True``, the check will be performed in the :ref:`current time zone\n<default-current-time-zone>` at the time the object gets saved.\n\nThis is enforced by :meth:`Model.validate_unique()` during model validation\nbut not at the database level. If any :attr:`~Field.unique_for_date` constraint\ninvolves fields that are not part of a :class:`~django.forms.ModelForm` (for\nexample, if one of the fields is listed in ``exclude`` or has\n:attr:`editable=False<Field.editable>`), :meth:`Model.validate_unique()` will\nskip validation for that particular constraint.\n\n``unique_for_month``\n--------------------\n\n.. attribute:: Field.unique_for_month\n\nLike :attr:`~Field.unique_for_date`, but requires the field to be unique with\nrespect to the month.\n\n``unique_for_year``\n-------------------\n\n.. attribute:: Field.unique_for_year\n\nLike :attr:`~Field.unique_for_date` and :attr:`~Field.unique_for_month`.\n\n``verbose_name``\n----------------\n\n.. attribute:: Field.verbose_name\n\nA human-readable name for the field. If the verbose name isn't given, Django\nwill automatically create it using the field's attribute name, converting\nunderscores to spaces. See :ref:`Verbose field names <verbose-field-names>`.\n\n``validators``\n--------------\n\n.. attribute:: Field.validators\n\nA list of validators to run for this field. See the :doc:`validators\ndocumentation </ref/validators>` for more information.\n\nRegistering and fetching lookups\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n``Field`` implements the :ref:`lookup registration API <lookup-registration-api>`.\nThe API can be used to customize which lookups are available for a field class, and\nhow lookups are fetched from a field.\n\n.. _model-field-types:\n\nField types\n===========\n\n.. currentmodule:: django.db.models\n\n``AutoField``\n-------------\n\n.. class:: AutoField(**options)\n\nAn :class:`IntegerField` that automatically increments\naccording to available IDs. You usually won't need to use this directly; a\nprimary key field will automatically be added to your model if you don't specify\notherwise. See :ref:`automatic-primary-key-fields`.\n\n``BigAutoField``\n----------------\n\n.. class:: BigAutoField(**options)\n\nA 64-bit integer, much like an :class:`AutoField` except that it is\nguaranteed to fit numbers from ``1`` to ``9223372036854775807``.\n\n``BigIntegerField``\n-------------------\n\n.. class:: BigIntegerField(**options)\n\nA 64-bit integer, much like an :class:`IntegerField` except that it is\nguaranteed to fit numbers from ``-9223372036854775808`` to\n``9223372036854775807``. The default form widget for this field is a\n:class:`~django.forms.NumberInput`.\n\n``BinaryField``\n---------------\n\n.. class:: BinaryField(max_length=None, **options)\n\nA field to store raw binary data. It can be assigned :class:`bytes`,\n:class:`bytearray`, or :class:`memoryview`.\n\nBy default, ``BinaryField`` sets :attr:`~Field.editable` to ``False``, in which\ncase it can't be included in a :class:`~django.forms.ModelForm`.\n\n``BinaryField`` has one extra optional argument:\n\n.. attribute:: BinaryField.max_length\n\n    The maximum length (in characters) of the field. The maximum length is\n    enforced in Django's validation using\n    :class:`~django.core.validators.MaxLengthValidator`.\n\n.. admonition:: Abusing ``BinaryField``\n\n    Although you might think about storing files in the database, consider that\n    it is bad design in 99% of the cases. This field is *not* a replacement for\n    proper :doc:`static files </howto/static-files/index>` handling.\n\n``BooleanField``\n----------------\n\n.. class:: BooleanField(**options)\n\nA true/false field.\n\nThe default form widget for this field is :class:`~django.forms.CheckboxInput`,\nor :class:`~django.forms.NullBooleanSelect` if :attr:`null=True <Field.null>`.\n\nThe default value of ``BooleanField`` is ``None`` when :attr:`Field.default`\nisn't defined.\n\n``CharField``\n-------------\n\n.. class:: CharField(max_length=None, **options)\n\nA string field, for small- to large-sized strings.\n\nFor large amounts of text, use :class:`~django.db.models.TextField`.\n\nThe default form widget for this field is a :class:`~django.forms.TextInput`.\n\n:class:`CharField` has one extra required argument:\n\n.. attribute:: CharField.max_length\n\n    The maximum length (in characters) of the field. The max_length is enforced\n    at the database level and in Django's validation using\n    :class:`~django.core.validators.MaxLengthValidator`.\n\n.. note::\n\n    If you are writing an application that must be portable to multiple\n    database backends, you should be aware that there are restrictions on\n    ``max_length`` for some backends. Refer to the :doc:`database backend\n    notes </ref/databases>` for details.\n\n``DateField``\n-------------\n\n.. class:: DateField(auto_now=False, auto_now_add=False, **options)\n\nA date, represented in Python by a ``datetime.date`` instance. Has a few extra,\noptional arguments:\n\n.. attribute:: DateField.auto_now\n\n    Automatically set the field to now every time the object is saved. Useful\n    for \"last-modified\" timestamps. Note that the current date is *always*\n    used; it's not just a default value that you can override.\n\n    The field is only automatically updated when calling :meth:`Model.save()\n    <django.db.models.Model.save>`. The field isn't updated when making updates\n    to other fields in other ways such as :meth:`QuerySet.update()\n    <django.db.models.query.QuerySet.update>`, though you can specify a custom\n    value for the field in an update like that.\n\n.. attribute:: DateField.auto_now_add\n\n    Automatically set the field to now when the object is first created. Useful\n    for creation of timestamps. Note that the current date is *always* used;\n    it's not just a default value that you can override. So even if you\n    set a value for this field when creating the object, it will be ignored.\n    If you want to be able to modify this field, set the following instead of\n    ``auto_now_add=True``:\n\n    * For :class:`DateField`: ``default=date.today`` - from\n      :meth:`datetime.date.today`\n    * For :class:`DateTimeField`: ``default=timezone.now`` - from\n      :func:`django.utils.timezone.now`\n\nThe default form widget for this field is a\n:class:`~django.forms.DateInput`. The admin adds a JavaScript calendar,\nand a shortcut for \"Today\". Includes an additional ``invalid_date`` error\nmessage key.\n\nThe options ``auto_now_add``, ``auto_now``, and ``default`` are mutually exclusive.\nAny combination of these options will result in an error.\n\n.. note::\n    As currently implemented, setting ``auto_now`` or ``auto_now_add`` to\n    ``True`` will cause the field to have ``editable=False`` and ``blank=True``\n    set.\n\n.. note::\n    The ``auto_now`` and ``auto_now_add`` options will always use the date in\n    the :ref:`default timezone <default-current-time-zone>` at the moment of\n    creation or update. If you need something different, you may want to\n    consider using your own callable default or overriding ``save()`` instead\n    of using ``auto_now`` or ``auto_now_add``; or using a ``DateTimeField``\n    instead of a ``DateField`` and deciding how to handle the conversion from\n    datetime to date at display time.\n\n``DateTimeField``\n-----------------\n\n.. class:: DateTimeField(auto_now=False, auto_now_add=False, **options)\n\nA date and time, represented in Python by a ``datetime.datetime`` instance.\nTakes the same extra arguments as :class:`DateField`.\n\nThe default form widget for this field is a single\n:class:`~django.forms.DateTimeInput`. The admin uses two separate\n:class:`~django.forms.TextInput` widgets with JavaScript shortcuts.\n\n``DecimalField``\n----------------\n\n.. class:: DecimalField(max_digits=None, decimal_places=None, **options)\n\nA fixed-precision decimal number, represented in Python by a\n:class:`~decimal.Decimal` instance. It validates the input using\n:class:`~django.core.validators.DecimalValidator`.\n\nHas two **required** arguments:\n\n.. attribute:: DecimalField.max_digits\n\n    The maximum number of digits allowed in the number. Note that this number\n    must be greater than or equal to ``decimal_places``.\n\n.. attribute:: DecimalField.decimal_places\n\n    The number of decimal places to store with the number.\n\nFor example, to store numbers up to ``999`` with a resolution of 2 decimal\nplaces, you'd use::\n\n    models.DecimalField(..., max_digits=5, decimal_places=2)\n\nAnd to store numbers up to approximately one billion with a resolution of 10\ndecimal places::\n\n    models.DecimalField(..., max_digits=19, decimal_places=10)\n\nThe default form widget for this field is a :class:`~django.forms.NumberInput`\nwhen :attr:`~django.forms.Field.localize` is ``False`` or\n:class:`~django.forms.TextInput` otherwise.\n\n.. note::\n\n    For more information about the differences between the\n    :class:`FloatField` and :class:`DecimalField` classes, please\n    see :ref:`FloatField vs. DecimalField <floatfield_vs_decimalfield>`. You\n    should also be aware of :ref:`SQLite limitations <sqlite-decimal-handling>`\n    of decimal fields.\n\n``DurationField``\n-----------------\n\n.. class:: DurationField(**options)\n\nA field for storing periods of time - modeled in Python by\n:class:`~python:datetime.timedelta`. When used on PostgreSQL, the data type\nused is an ``interval`` and on Oracle the data type is ``INTERVAL DAY(9) TO\nSECOND(6)``. Otherwise a ``bigint`` of microseconds is used.\n\n.. note::\n\n    Arithmetic with ``DurationField`` works in most cases. However on all\n    databases other than PostgreSQL, comparing the value of a ``DurationField``\n    to arithmetic on ``DateTimeField`` instances will not work as expected.\n\n``EmailField``\n--------------\n\n.. class:: EmailField(max_length=254, **options)\n\nA :class:`CharField` that checks that the value is a valid email address using\n:class:`~django.core.validators.EmailValidator`.\n\n``FileField``\n-------------\n\n.. class:: FileField(upload_to=None, max_length=100, **options)\n\nA file-upload field.\n\n.. note::\n    The ``primary_key`` argument isn't supported and will raise an error if\n    used.\n\nHas two optional arguments:\n\n.. attribute:: FileField.upload_to\n\n    This attribute provides a way of setting the upload directory and file name,\n    and can be set in two ways. In both cases, the value is passed to the\n    :meth:`Storage.save() <django.core.files.storage.Storage.save>` method.\n\n    If you specify a string value or a :class:`~pathlib.Path`, it may contain\n    :func:`~time.strftime` formatting, which will be replaced by the date/time\n    of the file upload (so that uploaded files don't fill up the given\n    directory). For example::\n\n        class MyModel(models.Model):\n            # file will be uploaded to MEDIA_ROOT/uploads\n            upload = models.FileField(upload_to='uploads/')\n            # or...\n            # file will be saved to MEDIA_ROOT/uploads/2015/01/30\n            upload = models.FileField(upload_to='uploads/%Y/%m/%d/')\n\n    If you are using the default\n    :class:`~django.core.files.storage.FileSystemStorage`, the string value\n    will be appended to your :setting:`MEDIA_ROOT` path to form the location on\n    the local filesystem where uploaded files will be stored. If you are using\n    a different storage, check that storage's documentation to see how it\n    handles ``upload_to``.\n\n    ``upload_to`` may also be a callable, such as a function. This will be\n    called to obtain the upload path, including the filename. This callable must\n    accept two arguments and return a Unix-style path (with forward slashes)\n    to be passed along to the storage system. The two arguments are:\n\n    ======================  ===============================================\n    Argument                Description\n    ======================  ===============================================\n    ``instance``            An instance of the model where the\n                            ``FileField`` is defined. More specifically,\n                            this is the particular instance where the\n                            current file is being attached.\n\n                            In most cases, this object will not have been\n                            saved to the database yet, so if it uses the\n                            default ``AutoField``, *it might not yet have a\n                            value for its primary key field*.\n\n    ``filename``            The filename that was originally given to the\n                            file. This may or may not be taken into account\n                            when determining the final destination path.\n    ======================  ===============================================\n\n    For example::\n\n        def user_directory_path(instance, filename):\n            # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>\n            return 'user_{0}/{1}'.format(instance.user.id, filename)\n\n        class MyModel(models.Model):\n            upload = models.FileField(upload_to=user_directory_path)\n\n.. attribute:: FileField.storage\n\n    A storage object, or a callable which returns a storage object. This\n    handles the storage and retrieval of your files. See :doc:`/topics/files`\n    for details on how to provide this object.\n\n    .. versionchanged:: 3.1\n\n        The ability to provide a callable was added.\n\nThe default form widget for this field is a\n:class:`~django.forms.ClearableFileInput`.\n\nUsing a :class:`FileField` or an :class:`ImageField` (see below) in a model\ntakes a few steps:\n\n#. In your settings file, you'll need to define :setting:`MEDIA_ROOT` as the\n   full path to a directory where you'd like Django to store uploaded files.\n   (For performance, these files are not stored in the database.) Define\n   :setting:`MEDIA_URL` as the base public URL of that directory. Make sure\n   that this directory is writable by the Web server's user account.\n\n#. Add the :class:`FileField` or :class:`ImageField` to your model, defining\n   the :attr:`~FileField.upload_to` option to specify a subdirectory of\n   :setting:`MEDIA_ROOT` to use for uploaded files.\n\n#. All that will be stored in your database is a path to the file\n   (relative to :setting:`MEDIA_ROOT`). You'll most likely want to use the\n   convenience :attr:`~django.db.models.fields.files.FieldFile.url` attribute\n   provided by Django. For example, if your :class:`ImageField` is called\n   ``mug_shot``, you can get the absolute path to your image in a template with\n   ``{{ object.mug_shot.url }}``.\n\nFor example, say your :setting:`MEDIA_ROOT` is set to ``'/home/media'``, and\n:attr:`~FileField.upload_to` is set to ``'photos/%Y/%m/%d'``. The ``'%Y/%m/%d'``\npart of :attr:`~FileField.upload_to` is :func:`~time.strftime` formatting;\n``'%Y'`` is the four-digit year, ``'%m'`` is the two-digit month and ``'%d'`` is\nthe two-digit day. If you upload a file on Jan. 15, 2007, it will be saved in\nthe directory ``/home/media/photos/2007/01/15``.\n\nIf you wanted to retrieve the uploaded file's on-disk filename, or the file's\nsize, you could use the :attr:`~django.core.files.File.name` and\n:attr:`~django.core.files.File.size` attributes respectively; for more\ninformation on the available attributes and methods, see the\n:class:`~django.core.files.File` class reference and the :doc:`/topics/files`\ntopic guide.\n\n.. note::\n    The file is saved as part of saving the model in the database, so the actual\n    file name used on disk cannot be relied on until after the model has been\n    saved.\n\nThe uploaded file's relative URL can be obtained using the\n:attr:`~django.db.models.fields.files.FieldFile.url` attribute. Internally,\nthis calls the :meth:`~django.core.files.storage.Storage.url` method of the\nunderlying :class:`~django.core.files.storage.Storage` class.\n\n.. _file-upload-security:\n\nNote that whenever you deal with uploaded files, you should pay close attention\nto where you're uploading them and what type of files they are, to avoid\nsecurity holes. *Validate all uploaded files* so that you're sure the files are\nwhat you think they are. For example, if you blindly let somebody upload files,\nwithout validation, to a directory that's within your Web server's document\nroot, then somebody could upload a CGI or PHP script and execute that script by\nvisiting its URL on your site. Don't allow that.\n\nAlso note that even an uploaded HTML file, since it can be executed by the\nbrowser (though not by the server), can pose security threats that are\nequivalent to XSS or CSRF attacks.\n\n:class:`FileField` instances are created in your database as ``varchar``\ncolumns with a default max length of 100 characters. As with other fields, you\ncan change the maximum length using the :attr:`~CharField.max_length` argument.\n\n``FileField`` and ``FieldFile``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. currentmodule:: django.db.models.fields.files\n\n.. class:: FieldFile\n\nWhen you access a :class:`~django.db.models.FileField` on a model, you are\ngiven an instance of :class:`FieldFile` as a proxy for accessing the underlying\nfile.\n\nThe API of :class:`FieldFile` mirrors that of :class:`~django.core.files.File`,\nwith one key difference: *The object wrapped by the class is not necessarily a\nwrapper around Python's built-in file object.* Instead, it is a wrapper around\nthe result of the :attr:`Storage.open()<django.core.files.storage.Storage.open>`\nmethod, which may be a :class:`~django.core.files.File` object, or it may be a\ncustom storage's implementation of the :class:`~django.core.files.File` API.\n\nIn addition to the API inherited from :class:`~django.core.files.File` such as\n``read()`` and ``write()``, :class:`FieldFile` includes several methods that\ncan be used to interact with the underlying file:\n\n.. warning::\n\n    Two methods of this class, :meth:`~FieldFile.save` and\n    :meth:`~FieldFile.delete`, default to saving the model object of the\n    associated ``FieldFile`` in the database.\n\n.. attribute:: FieldFile.name\n\nThe name of the file including the relative path from the root of the\n:class:`~django.core.files.storage.Storage` of the associated\n:class:`~django.db.models.FileField`.\n\n.. attribute:: FieldFile.size\n\nThe result of the underlying :attr:`Storage.size()\n<django.core.files.storage.Storage.size>` method.\n\n.. attribute:: FieldFile.url\n\nA read-only property to access the file's relative URL by calling the\n:meth:`~django.core.files.storage.Storage.url` method of the underlying\n:class:`~django.core.files.storage.Storage` class.\n\n.. method:: FieldFile.open(mode='rb')\n\nOpens or reopens the file associated with this instance in the specified\n``mode``. Unlike the standard Python ``open()`` method, it doesn't return a\nfile descriptor.\n\nSince the underlying file is opened implicitly when accessing it, it may be\nunnecessary to call this method except to reset the pointer to the underlying\nfile or to change the ``mode``.\n\n.. method:: FieldFile.close()\n\nBehaves like the standard Python ``file.close()`` method and closes the file\nassociated with this instance.\n\n.. method:: FieldFile.save(name, content, save=True)\n\nThis method takes a filename and file contents and passes them to the storage\nclass for the field, then associates the stored file with the model field.\nIf you want to manually associate file data with\n:class:`~django.db.models.FileField` instances on your model, the ``save()``\nmethod is used to persist that file data.\n\nTakes two required arguments: ``name`` which is the name of the file, and\n``content`` which is an object containing the file's contents.  The\noptional ``save`` argument controls whether or not the model instance is\nsaved after the file associated with this field has been altered. Defaults to\n``True``.\n\nNote that the ``content`` argument should be an instance of\n:class:`django.core.files.File`, not Python's built-in file object.\nYou can construct a :class:`~django.core.files.File` from an existing\nPython file object like this::\n\n    from django.core.files import File\n    # Open an existing file using Python's built-in open()\n    f = open('/path/to/hello.world')\n    myfile = File(f)\n\nOr you can construct one from a Python string like this::\n\n    from django.core.files.base import ContentFile\n    myfile = ContentFile(\"hello world\")\n\nFor more information, see :doc:`/topics/files`.\n\n.. method:: FieldFile.delete(save=True)\n\nDeletes the file associated with this instance and clears all attributes on\nthe field. Note: This method will close the file if it happens to be open when\n``delete()`` is called.\n\nThe optional ``save`` argument controls whether or not the model instance is\nsaved after the file associated with this field has been deleted. Defaults to\n``True``.\n\nNote that when a model is deleted, related files are not deleted. If you need\nto cleanup orphaned files, you'll need to handle it yourself (for instance,\nwith a custom management command that can be run manually or scheduled to run\nperiodically via e.g. cron).\n\n.. currentmodule:: django.db.models\n\n``FilePathField``\n-----------------\n\n.. class:: FilePathField(path='', match=None, recursive=False, allow_files=True, allow_folders=False, max_length=100, **options)\n\nA :class:`CharField` whose choices are limited to the filenames in a certain\ndirectory on the filesystem. Has some special arguments, of which the first is\n**required**:\n\n.. attribute:: FilePathField.path\n\n    Required. The absolute filesystem path to a directory from which this\n    :class:`FilePathField` should get its choices. Example: ``\"/home/images\"``.\n\n    ``path`` may also be a callable, such as a function to dynamically set the\n    path at runtime. Example::\n\n        import os\n        from django.conf import settings\n        from django.db import models\n\n        def images_path():\n            return os.path.join(settings.LOCAL_FILE_DIR, 'images')\n\n        class MyModel(models.Model):\n            file = models.FilePathField(path=images_path)\n\n.. attribute:: FilePathField.match\n\n    Optional. A regular expression, as a string, that :class:`FilePathField`\n    will use to filter filenames. Note that the regex will be applied to the\n    base filename, not the full path. Example: ``\"foo.*\\.txt$\"``, which will\n    match a file called ``foo23.txt`` but not ``bar.txt`` or ``foo23.png``.\n\n.. attribute:: FilePathField.recursive\n\n    Optional. Either ``True`` or ``False``. Default is ``False``. Specifies\n    whether all subdirectories of :attr:`~FilePathField.path` should be included\n\n.. attribute:: FilePathField.allow_files\n\n    Optional.  Either ``True`` or ``False``.  Default is ``True``.  Specifies\n    whether files in the specified location should be included.  Either this or\n    :attr:`~FilePathField.allow_folders` must be ``True``.\n\n.. attribute:: FilePathField.allow_folders\n\n    Optional.  Either ``True`` or ``False``.  Default is ``False``.  Specifies\n    whether folders in the specified location should be included.  Either this\n    or :attr:`~FilePathField.allow_files` must be ``True``.\n\nThe one potential gotcha is that :attr:`~FilePathField.match` applies to the\nbase filename, not the full path. So, this example::\n\n    FilePathField(path=\"/home/images\", match=\"foo.*\", recursive=True)\n\n...will match ``/home/images/foo.png`` but not ``/home/images/foo/bar.png``\nbecause the :attr:`~FilePathField.match` applies to the base filename\n(``foo.png`` and ``bar.png``).\n\n:class:`FilePathField` instances are created in your database as ``varchar``\ncolumns with a default max length of 100 characters. As with other fields, you\ncan change the maximum length using the :attr:`~CharField.max_length` argument.\n\n``FloatField``\n--------------\n\n.. class:: FloatField(**options)\n\nA floating-point number represented in Python by a ``float`` instance.\n\nThe default form widget for this field is a :class:`~django.forms.NumberInput`\nwhen :attr:`~django.forms.Field.localize` is ``False`` or\n:class:`~django.forms.TextInput` otherwise.\n\n.. _floatfield_vs_decimalfield:\n\n.. admonition:: ``FloatField`` vs. ``DecimalField``\n\n    The :class:`FloatField` class is sometimes mixed up with the\n    :class:`DecimalField` class. Although they both represent real numbers, they\n    represent those numbers differently. ``FloatField`` uses Python's ``float``\n    type internally, while ``DecimalField`` uses Python's ``Decimal`` type. For\n    information on the difference between the two, see Python's documentation\n    for the :mod:`decimal` module.\n\n``ImageField``\n--------------\n\n.. class:: ImageField(upload_to=None, height_field=None, width_field=None, max_length=100, **options)\n\nInherits all attributes and methods from :class:`FileField`, but also\nvalidates that the uploaded object is a valid image.\n\nIn addition to the special attributes that are available for :class:`FileField`,\nan :class:`ImageField` also has ``height`` and ``width`` attributes.\n\nTo facilitate querying on those attributes, :class:`ImageField` has two extra\noptional arguments:\n\n.. attribute:: ImageField.height_field\n\n    Name of a model field which will be auto-populated with the height of the\n    image each time the model instance is saved.\n\n.. attribute:: ImageField.width_field\n\n    Name of a model field which will be auto-populated with the width of the\n    image each time the model instance is saved.\n\nRequires the `Pillow`_ library.\n\n.. _Pillow: https://pillow.readthedocs.io/en/latest/\n\n:class:`ImageField` instances are created in your database as ``varchar``\ncolumns with a default max length of 100 characters. As with other fields, you\ncan change the maximum length using the :attr:`~CharField.max_length` argument.\n\nThe default form widget for this field is a\n:class:`~django.forms.ClearableFileInput`.\n\n``IntegerField``\n----------------\n\n.. class:: IntegerField(**options)\n\nAn integer. Values from ``-2147483648`` to ``2147483647`` are safe in all\ndatabases supported by Django.\n\nIt uses :class:`~django.core.validators.MinValueValidator` and\n:class:`~django.core.validators.MaxValueValidator` to validate the input based\non the values that the default database supports.\n\nThe default form widget for this field is a :class:`~django.forms.NumberInput`\nwhen :attr:`~django.forms.Field.localize` is ``False`` or\n:class:`~django.forms.TextInput` otherwise.\n\n``GenericIPAddressField``\n-------------------------\n\n.. class:: GenericIPAddressField(protocol='both', unpack_ipv4=False, **options)\n\nAn IPv4 or IPv6 address, in string format (e.g. ``192.0.2.30`` or\n``2a02:42fe::4``). The default form widget for this field is a\n:class:`~django.forms.TextInput`.\n\nThe IPv6 address normalization follows :rfc:`4291#section-2.2` section 2.2,\nincluding using the IPv4 format suggested in paragraph 3 of that section, like\n``::ffff:192.0.2.0``. For example, ``2001:0::0:01`` would be normalized to\n``2001::1``, and ``::ffff:0a0a:0a0a`` to ``::ffff:10.10.10.10``. All characters\nare converted to lowercase.\n\n.. attribute:: GenericIPAddressField.protocol\n\n    Limits valid inputs to the specified protocol.\n    Accepted values are ``'both'`` (default), ``'IPv4'``\n    or ``'IPv6'``. Matching is case insensitive.\n\n.. attribute:: GenericIPAddressField.unpack_ipv4\n\n    Unpacks IPv4 mapped addresses like ``::ffff:192.0.2.1``.\n    If this option is enabled that address would be unpacked to\n    ``192.0.2.1``. Default is disabled. Can only be used\n    when ``protocol`` is set to ``'both'``.\n\nIf you allow for blank values, you have to allow for null values since blank\nvalues are stored as null.\n\n``JSONField``\n-------------\n\n.. class:: JSONField(encoder=None, decoder=None, **options)\n\n.. versionadded:: 3.1\n\nA field for storing JSON encoded data. In Python the data is represented in its\nPython native format: dictionaries, lists, strings, numbers, booleans and\n``None``.\n\n``JSONField`` is supported on MariaDB 10.2.7+, MySQL 5.7.8+, Oracle,\nPostgreSQL, and SQLite 3.9.0+ (with the :ref:`JSON1 extension enabled\n<sqlite-json1>`).\n\n.. attribute:: JSONField.encoder\n\n    An optional :py:class:`json.JSONEncoder` subclass to serialize data types\n    not supported by the standard JSON serializer (e.g. ``datetime.datetime``\n    or :class:`~python:uuid.UUID`). For example, you can use the\n    :class:`~django.core.serializers.json.DjangoJSONEncoder` class.\n\n    Defaults to ``json.JSONEncoder``.\n\n.. attribute:: JSONField.decoder\n\n    An optional :py:class:`json.JSONDecoder` subclass to deserialize the value\n    retrieved from the database. The value will be in the format chosen by the\n    custom encoder (most often a string). Your deserialization may need to\n    account for the fact that you can't be certain of the input type. For\n    example, you run the risk of returning a ``datetime`` that was actually a\n    string that just happened to be in the same format chosen for\n    ``datetime``\\s.\n\n    Defaults to ``json.JSONDecoder``.\n\nIf you give the field a :attr:`~django.db.models.Field.default`, ensure it's an\nimmutable object, such as a ``str``, or a callable object that returns a fresh\nmutable object each time, such as ``dict`` or a function. Providing a mutable\ndefault object like ``default={}`` or ``default=[]`` shares the one object\nbetween all model instances.\n\nTo query ``JSONField`` in the database, see :ref:`querying-jsonfield`.\n\n.. admonition:: Indexing\n\n    :class:`~django.db.models.Index` and :attr:`.Field.db_index` both create a\n    B-tree index, which isn't particularly helpful when querying ``JSONField``.\n    On PostgreSQL only, you can use\n    :class:`~django.contrib.postgres.indexes.GinIndex` that is better suited.\n\n.. admonition:: PostgreSQL users\n\n    PostgreSQL has two native JSON based data types: ``json`` and ``jsonb``.\n    The main difference between them is how they are stored and how they can be\n    queried. PostgreSQL's ``json`` field is stored as the original string\n    representation of the JSON and must be decoded on the fly when queried\n    based on keys. The ``jsonb`` field is stored based on the actual structure\n    of the JSON which allows indexing. The trade-off is a small additional cost\n    on writing to the ``jsonb`` field. ``JSONField`` uses ``jsonb``.\n\n.. admonition:: Oracle users\n\n    Oracle Database does not support storing JSON scalar values. Only JSON\n    objects and arrays (represented in Python using :py:class:`dict` and\n    :py:class:`list`) are supported.\n\n``NullBooleanField``\n--------------------\n\n.. class:: NullBooleanField(**options)\n\nLike :class:`BooleanField` with ``null=True``.\n\n.. deprecated:: 3.1\n\n    ``NullBooleanField`` is deprecated in favor of ``BooleanField(null=True)``.\n\n``PositiveBigIntegerField``\n---------------------------\n\n.. class:: PositiveBigIntegerField(**options)\n\n.. versionadded:: 3.1\n\nLike a :class:`PositiveIntegerField`, but only allows values under a certain\n(database-dependent) point. Values from ``0`` to ``9223372036854775807`` are\nsafe in all databases supported by Django.\n\n``PositiveIntegerField``\n------------------------\n\n.. class:: PositiveIntegerField(**options)\n\nLike an :class:`IntegerField`, but must be either positive or zero (``0``).\nValues from ``0`` to ``2147483647`` are safe in all databases supported by\nDjango. The value ``0`` is accepted for backward compatibility reasons.\n\n``PositiveSmallIntegerField``\n-----------------------------\n\n.. class:: PositiveSmallIntegerField(**options)\n\nLike a :class:`PositiveIntegerField`, but only allows values under a certain\n(database-dependent) point. Values from ``0`` to ``32767`` are safe in all\ndatabases supported by Django.\n\n``SlugField``\n-------------\n\n.. class:: SlugField(max_length=50, **options)\n\n:term:`Slug <slug>` is a newspaper term. A slug is a short label for something,\ncontaining only letters, numbers, underscores or hyphens. They're generally used\nin URLs.\n\nLike a CharField, you can specify :attr:`~CharField.max_length` (read the note\nabout database portability and :attr:`~CharField.max_length` in that section,\ntoo). If :attr:`~CharField.max_length` is not specified, Django will use a\ndefault length of 50.\n\nImplies setting :attr:`Field.db_index` to ``True``.\n\nIt is often useful to automatically prepopulate a SlugField based on the value\nof some other value.  You can do this automatically in the admin using\n:attr:`~django.contrib.admin.ModelAdmin.prepopulated_fields`.\n\nIt uses :class:`~django.core.validators.validate_slug` or\n:class:`~django.core.validators.validate_unicode_slug` for validation.\n\n.. attribute:: SlugField.allow_unicode\n\n    If ``True``, the field accepts Unicode letters in addition to ASCII\n    letters. Defaults to ``False``.\n\n``SmallAutoField``\n------------------\n\n.. class:: SmallAutoField(**options)\n\nLike an :class:`AutoField`, but only allows values under a certain\n(database-dependent) limit. Values from ``1`` to ``32767`` are safe in all\ndatabases supported by Django.\n\n``SmallIntegerField``\n---------------------\n\n.. class:: SmallIntegerField(**options)\n\nLike an :class:`IntegerField`, but only allows values under a certain\n(database-dependent) point. Values from ``-32768`` to ``32767`` are safe in all\ndatabases supported by Django.\n\n``TextField``\n-------------\n\n.. class:: TextField(**options)\n\nA large text field. The default form widget for this field is a\n:class:`~django.forms.Textarea`.\n\nIf you specify a ``max_length`` attribute, it will be reflected in the\n:class:`~django.forms.Textarea` widget of the auto-generated form field.\nHowever it is not enforced at the model or database level. Use a\n:class:`CharField` for that.\n\n``TimeField``\n-------------\n\n.. class:: TimeField(auto_now=False, auto_now_add=False, **options)\n\nA time, represented in Python by a ``datetime.time`` instance. Accepts the same\nauto-population options as :class:`DateField`.\n\nThe default form widget for this field is a :class:`~django.forms.TimeInput`.\nThe admin adds some JavaScript shortcuts.\n\n``URLField``\n------------\n\n.. class:: URLField(max_length=200, **options)\n\nA :class:`CharField` for a URL, validated by\n:class:`~django.core.validators.URLValidator`.\n\nThe default form widget for this field is a :class:`~django.forms.URLInput`.\n\nLike all :class:`CharField` subclasses, :class:`URLField` takes the optional\n:attr:`~CharField.max_length` argument. If you don't specify\n:attr:`~CharField.max_length`, a default of 200 is used.\n\n``UUIDField``\n-------------\n\n.. class:: UUIDField(**options)\n\nA field for storing universally unique identifiers. Uses Python's\n:class:`~python:uuid.UUID` class. When used on PostgreSQL, this stores in a\n``uuid`` datatype, otherwise in a ``char(32)``.\n\nUniversally unique identifiers are a good alternative to :class:`AutoField` for\n:attr:`~Field.primary_key`. The database will not generate the UUID for you, so\nit is recommended to use :attr:`~Field.default`::\n\n    import uuid\n    from django.db import models\n\n    class MyUUIDModel(models.Model):\n        id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n        # other fields\n\nNote that a callable (with the parentheses omitted) is passed to ``default``,\nnot an instance of ``UUID``.\n\n.. admonition:: Lookups on PostgreSQL\n\n    Using :lookup:`iexact`, :lookup:`contains`, :lookup:`icontains`,\n    :lookup:`startswith`, :lookup:`istartswith`, :lookup:`endswith`, or\n    :lookup:`iendswith` lookups on PostgreSQL don't work for values without\n    hyphens, because PostgreSQL stores them in a hyphenated uuid datatype type.\n\nRelationship fields\n===================\n\n.. module:: django.db.models.fields.related\n   :synopsis: Related field types\n\n.. currentmodule:: django.db.models\n\nDjango also defines a set of fields that represent relations.\n\n.. _ref-foreignkey:\n\n``ForeignKey``\n--------------\n\n.. class:: ForeignKey(to, on_delete, **options)\n\nA many-to-one relationship. Requires two positional arguments: the class to\nwhich the model is related and the :attr:`~ForeignKey.on_delete` option.\n\n.. _recursive-relationships:\n\nTo create a recursive relationship -- an object that has a many-to-one\nrelationship with itself -- use ``models.ForeignKey('self',\non_delete=models.CASCADE)``.\n\n.. _lazy-relationships:\n\nIf you need to create a relationship on a model that has not yet been defined,\nyou can use the name of the model, rather than the model object itself::\n\n    from django.db import models\n\n    class Car(models.Model):\n        manufacturer = models.ForeignKey(\n            'Manufacturer',\n            on_delete=models.CASCADE,\n        )\n        # ...\n\n    class Manufacturer(models.Model):\n        # ...\n        pass\n\nRelationships defined this way on :ref:`abstract models\n<abstract-base-classes>` are resolved when the model is subclassed as a\nconcrete model and are not relative to the abstract model's ``app_label``:\n\n.. code-block:: python\n    :caption: products/models.py\n\n    from django.db import models\n\n    class AbstractCar(models.Model):\n        manufacturer = models.ForeignKey('Manufacturer', on_delete=models.CASCADE)\n\n        class Meta:\n            abstract = True\n\n.. code-block:: python\n    :caption: production/models.py\n\n    from django.db import models\n    from products.models import AbstractCar\n\n    class Manufacturer(models.Model):\n        pass\n\n    class Car(AbstractCar):\n        pass\n\n    # Car.manufacturer will point to `production.Manufacturer` here.\n\nTo refer to models defined in another application, you can explicitly specify\na model with the full application label. For example, if the ``Manufacturer``\nmodel above is defined in another application called ``production``, you'd\nneed to use::\n\n    class Car(models.Model):\n        manufacturer = models.ForeignKey(\n            'production.Manufacturer',\n            on_delete=models.CASCADE,\n        )\n\nThis sort of reference, called a lazy relationship, can be useful when\nresolving circular import dependencies between two applications.\n\nA database index is automatically created on the ``ForeignKey``. You can\ndisable this by setting :attr:`~Field.db_index` to ``False``.  You may want to\navoid the overhead of an index if you are creating a foreign key for\nconsistency rather than joins, or if you will be creating an alternative index\nlike a partial or multiple column index.\n\nDatabase Representation\n~~~~~~~~~~~~~~~~~~~~~~~\n\nBehind the scenes, Django appends ``\"_id\"`` to the field name to create its\ndatabase column name. In the above example, the database table for the ``Car``\nmodel will have a ``manufacturer_id`` column. (You can change this explicitly by\nspecifying :attr:`~Field.db_column`) However, your code should never have to\ndeal with the database column name, unless you write custom SQL. You'll always\ndeal with the field names of your model object.\n\n.. _foreign-key-arguments:\n\nArguments\n~~~~~~~~~\n\n:class:`ForeignKey` accepts other arguments that define the details of how the\nrelation works.\n\n.. attribute:: ForeignKey.on_delete\n\n    When an object referenced by a :class:`ForeignKey` is deleted, Django will\n    emulate the behavior of the SQL constraint specified by the\n    :attr:`on_delete` argument. For example, if you have a nullable\n    :class:`ForeignKey` and you want it to be set null when the referenced\n    object is deleted::\n\n        user = models.ForeignKey(\n            User,\n            models.SET_NULL,\n            blank=True,\n            null=True,\n        )\n\n    ``on_delete`` doesn't create an SQL constraint in the database. Support for\n    database-level cascade options :ticket:`may be implemented later <21961>`.\n\nThe possible values for :attr:`~ForeignKey.on_delete` are found in\n:mod:`django.db.models`:\n\n* .. attribute:: CASCADE\n\n    Cascade deletes. Django emulates the behavior of the SQL constraint ON\n    DELETE CASCADE and also deletes the object containing the ForeignKey.\n\n    :meth:`.Model.delete` isn't called on related models, but the\n    :data:`~django.db.models.signals.pre_delete` and\n    :data:`~django.db.models.signals.post_delete` signals are sent for all\n    deleted objects.\n\n* .. attribute:: PROTECT\n\n    Prevent deletion of the referenced object by raising\n    :exc:`~django.db.models.ProtectedError`, a subclass of\n    :exc:`django.db.IntegrityError`.\n\n* .. attribute:: RESTRICT\n\n    .. versionadded:: 3.1\n\n    Prevent deletion of the referenced object by raising\n    :exc:`~django.db.models.RestrictedError` (a subclass of\n    :exc:`django.db.IntegrityError`). Unlike :attr:`PROTECT`, deletion of the\n    referenced object is allowed if it also references a different object\n    that is being deleted in the same operation, but via a :attr:`CASCADE`\n    relationship.\n\n    Consider this set of models::\n\n        class Artist(models.Model):\n            name = models.CharField(max_length=10)\n\n        class Album(models.Model):\n            artist = models.ForeignKey(Artist, on_delete=models.CASCADE)\n\n        class Song(models.Model):\n            artist = models.ForeignKey(Artist, on_delete=models.CASCADE)\n            album = models.ForeignKey(Album, on_delete=models.RESTRICT)\n\n    ``Artist`` can be deleted even if that implies deleting an ``Album``\n    which is referenced by a ``Song``, because ``Song`` also references\n    ``Artist`` itself through a cascading relationship. For example::\n\n        >>> artist_one = Artist.objects.create(name='artist one')\n        >>> artist_two = Artist.objects.create(name='artist two')\n        >>> album_one = Album.objects.create(artist=artist_one)\n        >>> album_two = Album.objects.create(artist=artist_two)\n        >>> song_one = Song.objects.create(artist=artist_one, album=album_one)\n        >>> song_two = Song.objects.create(artist=artist_one, album=album_two)\n        >>> album_one.delete()\n        # Raises RestrictedError.\n        >>> artist_two.delete()\n        # Raises RestrictedError.\n        >>> artist_one.delete()\n        (4, {'Song': 2, 'Album': 1, 'Artist': 1})\n\n* .. attribute:: SET_NULL\n\n    Set the :class:`ForeignKey` null; this is only possible if\n    :attr:`~Field.null` is ``True``.\n\n* .. attribute:: SET_DEFAULT\n\n    Set the :class:`ForeignKey` to its default value; a default for the\n    :class:`ForeignKey` must be set.\n\n* .. function:: SET()\n\n    Set the :class:`ForeignKey` to the value passed to\n    :func:`~django.db.models.SET()`, or if a callable is passed in,\n    the result of calling it. In most cases, passing a callable will be\n    necessary to avoid executing queries at the time your models.py is\n    imported::\n\n        from django.conf import settings\n        from django.contrib.auth import get_user_model\n        from django.db import models\n\n        def get_sentinel_user():\n            return get_user_model().objects.get_or_create(username='deleted')[0]\n\n        class MyModel(models.Model):\n            user = models.ForeignKey(\n                settings.AUTH_USER_MODEL,\n                on_delete=models.SET(get_sentinel_user),\n            )\n\n* .. attribute:: DO_NOTHING\n\n    Take no action. If your database backend enforces referential\n    integrity, this will cause an :exc:`~django.db.IntegrityError` unless\n    you manually add an SQL ``ON DELETE`` constraint to the database field.\n\n.. attribute:: ForeignKey.limit_choices_to\n\n    Sets a limit to the available choices for this field when this field is\n    rendered using a ``ModelForm`` or the admin (by default, all objects\n    in the queryset are available to choose). Either a dictionary, a\n    :class:`~django.db.models.Q` object, or a callable returning a\n    dictionary or :class:`~django.db.models.Q` object can be used.\n\n    For example::\n\n        staff_member = models.ForeignKey(\n            User,\n            on_delete=models.CASCADE,\n            limit_choices_to={'is_staff': True},\n        )\n\n    causes the corresponding field on the ``ModelForm`` to list only ``Users``\n    that have ``is_staff=True``. This may be helpful in the Django admin.\n\n    The callable form can be helpful, for instance, when used in conjunction\n    with the Python ``datetime`` module to limit selections by date range. For\n    example::\n\n        def limit_pub_date_choices():\n            return {'pub_date__lte': datetime.date.utcnow()}\n\n        limit_choices_to = limit_pub_date_choices\n\n    If ``limit_choices_to`` is or returns a :class:`Q object\n    <django.db.models.Q>`, which is useful for :ref:`complex queries\n    <complex-lookups-with-q>`, then it will only have an effect on the choices\n    available in the admin when the field is not listed in\n    :attr:`~django.contrib.admin.ModelAdmin.raw_id_fields` in the\n    ``ModelAdmin`` for the model.\n\n    .. note::\n\n        If a callable is used for ``limit_choices_to``, it will be invoked\n        every time a new form is instantiated. It may also be invoked when a\n        model is validated, for example by management commands or the admin.\n        The admin constructs querysets to validate its form inputs in various\n        edge cases multiple times, so there is a possibility your callable may\n        be invoked several times.\n\n.. attribute:: ForeignKey.related_name\n\n    The name to use for the relation from the related object back to this one.\n    It's also the default value for :attr:`related_query_name` (the name to use\n    for the reverse filter name from the target model). See the :ref:`related\n    objects documentation <backwards-related-objects>` for a full explanation\n    and example. Note that you must set this value when defining relations on\n    :ref:`abstract models <abstract-base-classes>`; and when you do so\n    :ref:`some special syntax <abstract-related-name>` is available.\n\n    If you'd prefer Django not to create a backwards relation, set\n    ``related_name`` to ``'+'`` or end it with ``'+'``. For example, this will\n    ensure that the ``User`` model won't have a backwards relation to this\n    model::\n\n        user = models.ForeignKey(\n            User,\n            on_delete=models.CASCADE,\n            related_name='+',\n        )\n\n.. attribute:: ForeignKey.related_query_name\n\n    The name to use for the reverse filter name from the target model. It\n    defaults to the value of :attr:`related_name` or\n    :attr:`~django.db.models.Options.default_related_name` if set, otherwise it\n    defaults to the name of the model::\n\n        # Declare the ForeignKey with related_query_name\n        class Tag(models.Model):\n            article = models.ForeignKey(\n                Article,\n                on_delete=models.CASCADE,\n                related_name=\"tags\",\n                related_query_name=\"tag\",\n            )\n            name = models.CharField(max_length=255)\n\n        # That's now the name of the reverse filter\n        Article.objects.filter(tag__name=\"important\")\n\n    Like :attr:`related_name`, ``related_query_name`` supports app label and\n    class interpolation via :ref:`some special syntax <abstract-related-name>`.\n\n.. attribute:: ForeignKey.to_field\n\n    The field on the related object that the relation is to. By default, Django\n    uses the primary key of the related object. If you reference a different\n    field, that field must have ``unique=True``.\n\n.. attribute:: ForeignKey.db_constraint\n\n    Controls whether or not a constraint should be created in the database for\n    this foreign key. The default is ``True``, and that's almost certainly what\n    you want; setting this to ``False`` can be very bad for data integrity.\n    That said, here are some scenarios where you might want to do this:\n\n    * You have legacy data that is not valid.\n    * You're sharding your database.\n\n    If this is set to ``False``, accessing a related object that doesn't exist\n    will raise its ``DoesNotExist`` exception.\n\n.. attribute:: ForeignKey.swappable\n\n    Controls the migration framework's reaction if this :class:`ForeignKey`\n    is pointing at a swappable model. If it is ``True`` - the default -\n    then if the :class:`ForeignKey` is pointing at a model which matches\n    the current value of ``settings.AUTH_USER_MODEL`` (or another swappable\n    model setting) the relationship will be stored in the migration using\n    a reference to the setting, not to the model directly.\n\n    You only want to override this to be ``False`` if you are sure your\n    model should always point towards the swapped-in model - for example,\n    if it is a profile model designed specifically for your custom user model.\n\n    Setting it to ``False`` does not mean you can reference a swappable model\n    even if it is swapped out - ``False`` means that the migrations made\n    with this ForeignKey will always reference the exact model you specify\n    (so it will fail hard if the user tries to run with a User model you don't\n    support, for example).\n\n    If in doubt, leave it to its default of ``True``.\n\n``ManyToManyField``\n-------------------\n\n.. class:: ManyToManyField(to, **options)\n\nA many-to-many relationship. Requires a positional argument: the class to\nwhich the model is related, which works exactly the same as it does for\n:class:`ForeignKey`, including :ref:`recursive <recursive-relationships>` and\n:ref:`lazy <lazy-relationships>` relationships.\n\nRelated objects can be added, removed, or created with the field's\n:class:`~django.db.models.fields.related.RelatedManager`.\n\nDatabase Representation\n~~~~~~~~~~~~~~~~~~~~~~~\n\nBehind the scenes, Django creates an intermediary join table to represent the\nmany-to-many relationship. By default, this table name is generated using the\nname of the many-to-many field and the name of the table for the model that\ncontains it. Since some databases don't support table names above a certain\nlength, these table names will be automatically truncated and a uniqueness hash\nwill be used, e.g. ``author_books_9cdf``. You can manually provide the name of\nthe join table using the :attr:`~ManyToManyField.db_table` option.\n\n.. _manytomany-arguments:\n\nArguments\n~~~~~~~~~\n\n:class:`ManyToManyField` accepts an extra set of arguments -- all optional --\nthat control how the relationship functions.\n\n.. attribute:: ManyToManyField.related_name\n\n    Same as :attr:`ForeignKey.related_name`.\n\n.. attribute:: ManyToManyField.related_query_name\n\n    Same as :attr:`ForeignKey.related_query_name`.\n\n.. attribute:: ManyToManyField.limit_choices_to\n\n    Same as :attr:`ForeignKey.limit_choices_to`.\n\n    ``limit_choices_to`` has no effect when used on a ``ManyToManyField`` with a\n    custom intermediate table specified using the\n    :attr:`~ManyToManyField.through` parameter.\n\n.. attribute:: ManyToManyField.symmetrical\n\n    Only used in the definition of ManyToManyFields on self. Consider the\n    following model::\n\n        from django.db import models\n\n        class Person(models.Model):\n            friends = models.ManyToManyField(\"self\")\n\n    When Django processes this model, it identifies that it has a\n    :class:`ManyToManyField` on itself, and as a result, it doesn't add a\n    ``person_set`` attribute to the ``Person`` class. Instead, the\n    :class:`ManyToManyField` is assumed to be symmetrical -- that is, if I am\n    your friend, then you are my friend.\n\n    If you do not want symmetry in many-to-many relationships with ``self``, set\n    :attr:`~ManyToManyField.symmetrical` to ``False``. This will force Django to\n    add the descriptor for the reverse relationship, allowing\n    :class:`ManyToManyField` relationships to be non-symmetrical.\n\n.. attribute:: ManyToManyField.through\n\n    Django will automatically generate a table to manage many-to-many\n    relationships. However, if you want to manually specify the intermediary\n    table, you can use the :attr:`~ManyToManyField.through` option to specify\n    the Django model that represents the intermediate table that you want to\n    use.\n\n    The most common use for this option is when you want to associate\n    :ref:`extra data with a many-to-many relationship\n    <intermediary-manytomany>`.\n\n    .. note::\n\n        Recursive relationships using an intermediary model and defined as\n        symmetrical (that is, with :attr:`symmetrical=True\n        <ManyToManyField.symmetrical>`, which is the default) can't determine\n        the reverse accessors names, as they would be the same. You need to set\n        a :attr:`~ForeignKey.related_name` to at least one of them. If you'd\n        prefer Django not to create a backwards relation, set ``related_name``\n        to ``'+'``.\n\n    If you don't specify an explicit ``through`` model, there is still an\n    implicit ``through`` model class you can use to directly access the table\n    created to hold the association. It has three fields to link the models.\n\n    If the source and target models differ, the following fields are\n    generated:\n\n    * ``id``: the primary key of the relation.\n    * ``<containing_model>_id``: the ``id`` of the model that declares the\n      ``ManyToManyField``.\n    * ``<other_model>_id``: the ``id`` of the model that the\n      ``ManyToManyField`` points to.\n\n    If the ``ManyToManyField`` points from and to the same model, the following\n    fields are generated:\n\n    * ``id``: the primary key of the relation.\n    * ``from_<model>_id``: the ``id`` of the instance which points at the\n      model (i.e. the source instance).\n    * ``to_<model>_id``: the ``id`` of the instance to which the relationship\n      points (i.e. the target model instance).\n\n    This class can be used to query associated records for a given model\n    instance like a normal model.\n\n.. attribute:: ManyToManyField.through_fields\n\n    Only used when a custom intermediary model is specified. Django will\n    normally determine which fields of the intermediary model to use in order\n    to establish a many-to-many relationship automatically. However,\n    consider the following models::\n\n        from django.db import models\n\n        class Person(models.Model):\n            name = models.CharField(max_length=50)\n\n        class Group(models.Model):\n            name = models.CharField(max_length=128)\n            members = models.ManyToManyField(\n                Person,\n                through='Membership',\n                through_fields=('group', 'person'),\n            )\n\n        class Membership(models.Model):\n            group = models.ForeignKey(Group, on_delete=models.CASCADE)\n            person = models.ForeignKey(Person, on_delete=models.CASCADE)\n            inviter = models.ForeignKey(\n                Person,\n                on_delete=models.CASCADE,\n                related_name=\"membership_invites\",\n            )\n            invite_reason = models.CharField(max_length=64)\n\n    ``Membership`` has *two* foreign keys to ``Person`` (``person`` and\n    ``inviter``), which makes the relationship ambiguous and Django can't know\n    which one to use. In this case, you must explicitly specify which\n    foreign keys Django should use using ``through_fields``, as in the example\n    above.\n\n    ``through_fields`` accepts a 2-tuple ``('field1', 'field2')``, where\n    ``field1`` is the name of the foreign key to the model the\n    :class:`ManyToManyField` is defined on (``group`` in this case), and\n    ``field2`` the name of the foreign key to the target model (``person``\n    in this case).\n\n    When you have more than one foreign key on an intermediary model to any\n    (or even both) of the models participating in a many-to-many relationship,\n    you *must* specify ``through_fields``. This also applies to\n    :ref:`recursive relationships <recursive-relationships>`\n    when an intermediary model is used and there are more than two\n    foreign keys to the model, or you want to explicitly specify which two\n    Django should use.\n\n.. attribute:: ManyToManyField.db_table\n\n    The name of the table to create for storing the many-to-many data. If this\n    is not provided, Django will assume a default name based upon the names of:\n    the table for the model defining the relationship and the name of the field\n    itself.\n\n.. attribute:: ManyToManyField.db_constraint\n\n    Controls whether or not constraints should be created in the database for\n    the foreign keys in the intermediary table. The default is ``True``, and\n    that's almost certainly what you want; setting this to ``False`` can be\n    very bad for data integrity. That said, here are some scenarios where you\n    might want to do this:\n\n    * You have legacy data that is not valid.\n    * You're sharding your database.\n\n    It is an error to pass both ``db_constraint`` and ``through``.\n\n.. attribute:: ManyToManyField.swappable\n\n    Controls the migration framework's reaction if this :class:`ManyToManyField`\n    is pointing at a swappable model. If it is ``True`` - the default -\n    then if the :class:`ManyToManyField` is pointing at a model which matches\n    the current value of ``settings.AUTH_USER_MODEL`` (or another swappable\n    model setting) the relationship will be stored in the migration using\n    a reference to the setting, not to the model directly.\n\n    You only want to override this to be ``False`` if you are sure your\n    model should always point towards the swapped-in model - for example,\n    if it is a profile model designed specifically for your custom user model.\n\n    If in doubt, leave it to its default of ``True``.\n\n:class:`ManyToManyField` does not support :attr:`~Field.validators`.\n\n:attr:`~Field.null` has no effect since there is no way to require a\nrelationship at the database level.\n\n``OneToOneField``\n-----------------\n\n.. class:: OneToOneField(to, on_delete, parent_link=False, **options)\n\nA one-to-one relationship. Conceptually, this is similar to a\n:class:`ForeignKey` with :attr:`unique=True <Field.unique>`, but the\n\"reverse\" side of the relation will directly return a single object.\n\nThis is most useful as the primary key of a model which \"extends\"\nanother model in some way; :ref:`multi-table-inheritance` is\nimplemented by adding an implicit one-to-one relation from the child\nmodel to the parent model, for example.\n\nOne positional argument is required: the class to which the model will be\nrelated. This works exactly the same as it does for :class:`ForeignKey`,\nincluding all the options regarding :ref:`recursive <recursive-relationships>`\nand :ref:`lazy <lazy-relationships>` relationships.\n\nIf you do not specify the :attr:`~ForeignKey.related_name` argument for the\n``OneToOneField``, Django will use the lowercase name of the current model as\ndefault value.\n\nWith the following example::\n\n    from django.conf import settings\n    from django.db import models\n\n    class MySpecialUser(models.Model):\n        user = models.OneToOneField(\n            settings.AUTH_USER_MODEL,\n            on_delete=models.CASCADE,\n        )\n        supervisor = models.OneToOneField(\n            settings.AUTH_USER_MODEL,\n            on_delete=models.CASCADE,\n            related_name='supervisor_of',\n        )\n\nyour resulting ``User`` model will have the following attributes::\n\n    >>> user = User.objects.get(pk=1)\n    >>> hasattr(user, 'myspecialuser')\n    True\n    >>> hasattr(user, 'supervisor_of')\n    True\n\nA ``DoesNotExist`` exception is raised when accessing the reverse relationship\nif an entry in the related table doesn't exist. For example, if a user doesn't\nhave a supervisor designated by ``MySpecialUser``::\n\n    >>> user.supervisor_of\n    Traceback (most recent call last):\n        ...\n    DoesNotExist: User matching query does not exist.\n\n.. _onetoone-arguments:\n\nAdditionally, ``OneToOneField`` accepts all of the extra arguments\naccepted by :class:`ForeignKey`, plus one extra argument:\n\n.. attribute:: OneToOneField.parent_link\n\n    When ``True`` and used in a model which inherits from another\n    :term:`concrete model`, indicates that this field should be used as the\n    link back to the parent class, rather than the extra\n    ``OneToOneField`` which would normally be implicitly created by\n    subclassing.\n\nSee :doc:`One-to-one relationships </topics/db/examples/one_to_one>` for usage\nexamples of ``OneToOneField``.\n\nField API reference\n===================\n\n.. class:: Field\n\n    ``Field`` is an abstract class that represents a database table column.\n    Django uses fields to create the database table (:meth:`db_type`), to map\n    Python types to database (:meth:`get_prep_value`) and vice-versa\n    (:meth:`from_db_value`).\n\n    A field is thus a fundamental piece in different Django APIs, notably,\n    :class:`models <django.db.models.Model>` and :class:`querysets\n    <django.db.models.query.QuerySet>`.\n\n    In models, a field is instantiated as a class attribute and represents a\n    particular table column, see :doc:`/topics/db/models`. It has attributes\n    such as :attr:`null` and :attr:`unique`, and methods that Django uses to\n    map the field value to database-specific values.\n\n    A ``Field`` is a subclass of\n    :class:`~django.db.models.lookups.RegisterLookupMixin` and thus both\n    :class:`~django.db.models.Transform` and\n    :class:`~django.db.models.Lookup` can be registered on it to be used\n    in ``QuerySet``\\s (e.g. ``field_name__exact=\"foo\"``). All :ref:`built-in\n    lookups <field-lookups>` are registered by default.\n\n    All of Django's built-in fields, such as :class:`CharField`, are particular\n    implementations of ``Field``. If you need a custom field, you can either\n    subclass any of the built-in fields or write a ``Field`` from scratch. In\n    either case, see :doc:`/howto/custom-model-fields`.\n\n    .. attribute:: description\n\n        A verbose description of the field, e.g. for the\n        :mod:`django.contrib.admindocs` application.\n\n        The description can be of the form::\n\n            description = _(\"String (up to %(max_length)s)\")\n\n        where the arguments are interpolated from the field's ``__dict__``.\n\n    .. attribute:: descriptor_class\n\n        A class implementing the :py:ref:`descriptor protocol <descriptors>`\n        that is instantiated and assigned to the model instance attribute. The\n        constructor must accept a single argument, the ``Field`` instance.\n        Overriding this class attribute allows for customizing the get and set\n        behavior.\n\n    To map a ``Field`` to a database-specific type, Django exposes several\n    methods:\n\n    .. method:: get_internal_type()\n\n        Returns a string naming this field for backend specific purposes.\n        By default, it returns the class name.\n\n        See :ref:`emulating-built-in-field-types` for usage in custom fields.\n\n    .. method:: db_type(connection)\n\n        Returns the database column data type for the :class:`Field`, taking\n        into account the ``connection``.\n\n        See :ref:`custom-database-types` for usage in custom fields.\n\n    .. method:: rel_db_type(connection)\n\n        Returns the database column data type for fields such as ``ForeignKey``\n        and ``OneToOneField`` that point to the :class:`Field`, taking\n        into account the ``connection``.\n\n        See :ref:`custom-database-types` for usage in custom fields.\n\n    There are three main situations where Django needs to interact with the\n    database backend and fields:\n\n    * when it queries the database (Python value -> database backend value)\n    * when it loads data from the database (database backend value -> Python\n      value)\n    * when it saves to the database (Python value -> database backend value)\n\n    When querying, :meth:`get_db_prep_value` and :meth:`get_prep_value` are used:\n\n    .. method:: get_prep_value(value)\n\n        ``value`` is the current value of the model's attribute, and the method\n        should return data in a format that has been prepared for use as a\n        parameter in a query.\n\n        See :ref:`converting-python-objects-to-query-values` for usage.\n\n    .. method:: get_db_prep_value(value, connection, prepared=False)\n\n        Converts ``value`` to a backend-specific value. By default it returns\n        ``value`` if ``prepared=True`` and :meth:`~Field.get_prep_value` if is\n        ``False``.\n\n        See :ref:`converting-query-values-to-database-values` for usage.\n\n    When loading data, :meth:`from_db_value` is used:\n\n    .. method:: from_db_value(value, expression, connection)\n\n        Converts a value as returned by the database to a Python object. It is\n        the reverse of :meth:`get_prep_value`.\n\n        This method is not used for most built-in fields as the database\n        backend already returns the correct Python type, or the backend itself\n        does the conversion.\n\n        ``expression`` is the same as ``self``.\n\n        See :ref:`converting-values-to-python-objects` for usage.\n\n        .. note::\n\n            For performance reasons, ``from_db_value`` is not implemented as a\n            no-op on fields which do not require it (all Django fields).\n            Consequently you may not call ``super`` in your definition.\n\n    When saving, :meth:`pre_save` and :meth:`get_db_prep_save` are used:\n\n    .. method:: get_db_prep_save(value, connection)\n\n        Same as the :meth:`get_db_prep_value`, but called when the field value\n        must be *saved* to the database. By default returns\n        :meth:`get_db_prep_value`.\n\n    .. method:: pre_save(model_instance, add)\n\n        Method called prior to :meth:`get_db_prep_save` to prepare the value\n        before being saved (e.g. for :attr:`DateField.auto_now`).\n\n        ``model_instance`` is the instance this field belongs to and ``add``\n        is whether the instance is being saved to the database for the first\n        time.\n\n        It should return the value of the appropriate attribute from\n        ``model_instance`` for this field. The attribute name is in\n        ``self.attname`` (this is set up by :class:`~django.db.models.Field`).\n\n        See :ref:`preprocessing-values-before-saving` for usage.\n\n    Fields often receive their values as a different type, either from\n    serialization or from forms.\n\n    .. method:: to_python(value)\n\n        Converts the value into the correct Python object. It acts as the\n        reverse of :meth:`value_to_string`, and is also called in\n        :meth:`~django.db.models.Model.clean`.\n\n        See :ref:`converting-values-to-python-objects` for usage.\n\n    Besides saving to the database, the field also needs to know how to\n    serialize its value:\n\n    .. method:: value_from_object(obj)\n\n        Returns the field's value for the given model instance.\n\n        This method is often used by :meth:`value_to_string`.\n\n    .. method:: value_to_string(obj)\n\n        Converts ``obj`` to a string. Used to serialize the value of the field.\n\n        See :ref:`converting-model-field-to-serialization` for usage.\n\n    When using :class:`model forms <django.forms.ModelForm>`, the ``Field``\n    needs to know which form field it should be represented by:\n\n    .. method:: formfield(form_class=None, choices_form_class=None, **kwargs)\n\n        Returns the default :class:`django.forms.Field` of this field for\n        :class:`~django.forms.ModelForm`.\n\n        By default, if both ``form_class`` and ``choices_form_class`` are\n        ``None``, it uses :class:`~django.forms.CharField`. If the field has\n        :attr:`~django.db.models.Field.choices` and ``choices_form_class``\n        isn't specified, it uses :class:`~django.forms.TypedChoiceField`.\n\n        See :ref:`specifying-form-field-for-model-field` for usage.\n\n    .. method:: deconstruct()\n\n        Returns a 4-tuple with enough information to recreate the field:\n\n        1. The name of the field on the model.\n        2. The import path of the field (e.g. ``\"django.db.models.IntegerField\"``).\n           This should be the most portable version, so less specific may be better.\n        3. A list of positional arguments.\n        4. A dict of keyword arguments.\n\n        This method must be added to fields prior to 1.7 to migrate its data\n        using :doc:`/topics/migrations`.\n\n.. _model-field-attributes:\n\n=========================\nField attribute reference\n=========================\n\nEvery ``Field`` instance contains several attributes that allow\nintrospecting its behavior. Use these attributes instead of ``isinstance``\nchecks when you need to write code that depends on a field's functionality.\nThese attributes can be used together with the :ref:`Model._meta API\n<model-meta-field-api>` to narrow down a search for specific field types.\nCustom model fields should implement these flags.\n\nAttributes for fields\n=====================\n\n.. attribute:: Field.auto_created\n\n     Boolean flag that indicates if the field was automatically created, such\n     as the ``OneToOneField`` used by model inheritance.\n\n.. attribute:: Field.concrete\n\n    Boolean flag that indicates if the field has a database column associated\n    with it.\n\n.. attribute:: Field.hidden\n\n    Boolean flag that indicates if a field is used to back another non-hidden\n    field's functionality (e.g. the ``content_type`` and ``object_id`` fields\n    that make up a ``GenericForeignKey``). The ``hidden`` flag is used to\n    distinguish what constitutes the public subset of fields on the model from\n    all the fields on the model.\n\n    .. note::\n\n        :meth:`Options.get_fields()\n        <django.db.models.options.Options.get_fields()>`\n        excludes hidden fields by default. Pass in ``include_hidden=True`` to\n        return hidden fields in the results.\n\n.. attribute:: Field.is_relation\n\n    Boolean flag that indicates if a field contains references to one or\n    more other models for its functionality (e.g. ``ForeignKey``,\n    ``ManyToManyField``, ``OneToOneField``, etc.).\n\n.. attribute:: Field.model\n\n    Returns the model on which the field is defined. If a field is defined on\n    a superclass of a model, ``model`` will refer to the superclass, not the\n    class of the instance.\n\nAttributes for fields with relations\n====================================\n\nThese attributes are used to query for the cardinality and other details of a\nrelation. These attribute are present on all fields; however, they will only\nhave boolean values (rather than ``None``) if the field is a relation type\n(:attr:`Field.is_relation=True <Field.is_relation>`).\n\n.. attribute:: Field.many_to_many\n\n    Boolean flag that is ``True`` if the field has a many-to-many relation;\n    ``False`` otherwise. The only field included with Django where this is\n    ``True`` is ``ManyToManyField``.\n\n.. attribute:: Field.many_to_one\n\n    Boolean flag that is ``True`` if the field has a many-to-one relation, such\n    as a ``ForeignKey``; ``False`` otherwise.\n\n.. attribute:: Field.one_to_many\n\n    Boolean flag that is ``True`` if the field has a one-to-many relation, such\n    as a ``GenericRelation`` or the reverse of a ``ForeignKey``; ``False``\n    otherwise.\n\n.. attribute:: Field.one_to_one\n\n    Boolean flag that is ``True`` if the field has a one-to-one relation, such\n    as a ``OneToOneField``; ``False`` otherwise.\n\n.. attribute:: Field.related_model\n\n    Points to the model the field relates to. For example, ``Author`` in\n    ``ForeignKey(Author, on_delete=models.CASCADE)``. The ``related_model`` for\n    a ``GenericForeignKey`` is always ``None``.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":95,"nodeType":"TextFile","repoName":null,"name":"indexes.txt","path":"docs/ref/models","text":"=====================\nModel index reference\n=====================\n\n.. module:: django.db.models.indexes\n\n.. currentmodule:: django.db.models\n\nIndex classes ease creating database indexes. They can be added using the\n:attr:`Meta.indexes <django.db.models.Options.indexes>` option. This document\nexplains the API references of :class:`Index` which includes the `index\noptions`_.\n\n.. admonition:: Referencing built-in indexes\n\n    Indexes are defined in ``django.db.models.indexes``, but for convenience\n    they're imported into :mod:`django.db.models`. The standard convention is\n    to use ``from django.db import models`` and refer to the indexes as\n    ``models.<IndexClass>``.\n\n``Index`` options\n=================\n\n.. class:: Index(fields=(), name=None, db_tablespace=None, opclasses=(), condition=None)\n\n    Creates an index (B-Tree) in the database.\n\n``fields``\n----------\n\n.. attribute:: Index.fields\n\nA list or tuple of the name of the fields on which the index is desired.\n\nBy default, indexes are created with an ascending order for each column. To\ndefine an index with a descending order for a column, add a hyphen before the\nfield's name.\n\nFor example ``Index(fields=['headline', '-pub_date'])`` would create SQL with\n``(headline, pub_date DESC)``. Index ordering isn't supported on MySQL. In that\ncase, a descending index is created as a normal index.\n\n``name``\n--------\n\n.. attribute:: Index.name\n\nThe name of the index. If ``name`` isn't provided Django will auto-generate a\nname. For compatibility with different databases, index names cannot be longer\nthan 30 characters and shouldn't start with a number (0-9) or underscore (_).\n\n.. admonition:: Partial indexes in abstract base classes\n\n    You must always specify a unique name for an index. As such, you\n    cannot normally specify a partial index on an abstract base class, since\n    the :attr:`Meta.indexes <django.db.models.Options.indexes>` option is\n    inherited by subclasses, with exactly the same values for the attributes\n    (including ``name``) each time. To work around name collisions, part of the\n    name may contain ``'%(app_label)s'`` and ``'%(class)s'``, which are\n    replaced, respectively, by the lowercased app label and class name of the\n    concrete model. For example ``Index(fields=['title'],\n    name='%(app_label)s_%(class)s_title_index')``.\n\n``db_tablespace``\n-----------------\n\n.. attribute:: Index.db_tablespace\n\nThe name of the :doc:`database tablespace </topics/db/tablespaces>` to use for\nthis index. For single field indexes, if ``db_tablespace`` isn't provided, the\nindex is created in the ``db_tablespace`` of the field.\n\nIf :attr:`.Field.db_tablespace` isn't specified (or if the index uses multiple\nfields), the index is created in tablespace specified in the\n:attr:`~django.db.models.Options.db_tablespace` option inside the model's\n``class Meta``. If neither of those tablespaces are set, the index is created\nin the same tablespace as the table.\n\n.. seealso::\n\n    For a list of PostgreSQL-specific indexes, see\n    :mod:`django.contrib.postgres.indexes`.\n\n``opclasses``\n-------------\n\n.. attribute:: Index.opclasses\n\nThe names of the `PostgreSQL operator classes\n<https://www.postgresql.org/docs/current/indexes-opclass.html>`_ to use for\nthis index. If you require a custom operator class, you must provide one for\neach field in the index.\n\nFor example, ``GinIndex(name='json_index', fields=['jsonfield'],\nopclasses=['jsonb_path_ops'])`` creates a gin index on ``jsonfield`` using\n``jsonb_path_ops``.\n\n``opclasses`` are ignored for databases besides PostgreSQL.\n\n:attr:`Index.name` is required when using ``opclasses``.\n\n``condition``\n-------------\n\n.. attribute:: Index.condition\n\nIf the table is very large and your queries mostly target a subset of rows,\nit may be useful to restrict an index to that subset. Specify a condition as a\n:class:`~django.db.models.Q`. For example, ``condition=Q(pages__gt=400)``\nindexes records with more than 400 pages.\n\n:attr:`Index.name` is required when using ``condition``.\n\n.. admonition:: Restrictions on PostgreSQL\n\n    PostgreSQL requires functions referenced in the condition to be marked as\n    IMMUTABLE. Django doesn't validate this but PostgreSQL will error. This\n    means that functions such as :ref:`date-functions` and\n    :class:`~django.db.models.functions.Concat` aren't accepted. If you store\n    dates in :class:`~django.db.models.DateTimeField`, comparison to\n    :class:`~datetime.datetime` objects may require the ``tzinfo`` argument\n    to be provided because otherwise the comparison could result in a mutable\n    function due to the casting Django does for :ref:`lookups <field-lookups>`.\n\n.. admonition:: Restrictions on SQLite\n\n    SQLite `imposes restrictions <https://www.sqlite.org/partialindex.html>`_\n    on how a partial index can be constructed.\n\n.. admonition:: Oracle\n\n    Oracle does not support partial indexes. Instead, partial indexes can be\n    emulated using functional indexes. Use a :doc:`migration\n    </topics/migrations>` to add the index using :class:`.RunSQL`.\n\n.. admonition:: MySQL and MariaDB\n\n    The ``condition`` argument is ignored with MySQL and MariaDB as neither\n    supports conditional indexes.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":96,"nodeType":"TextFile","repoName":null,"name":"redirects.txt","path":"docs/ref/contrib","text":"=================\nThe redirects app\n=================\n\n.. module:: django.contrib.redirects\n   :synopsis: A framework for managing redirects.\n\nDjango comes with an optional redirects application. It lets you store\nredirects in a database and handles the redirecting for you. It uses the HTTP\nresponse status code ``301 Moved Permanently`` by default.\n\nInstallation\n============\n\nTo install the redirects app, follow these steps:\n\n#. Ensure that the ``django.contrib.sites`` framework\n   :ref:`is installed <enabling-the-sites-framework>`.\n#. Add ``'django.contrib.redirects'`` to your :setting:`INSTALLED_APPS` setting.\n#. Add ``'django.contrib.redirects.middleware.RedirectFallbackMiddleware'``\n   to your :setting:`MIDDLEWARE` setting.\n#. Run the command :djadmin:`manage.py migrate <migrate>`.\n\nHow it works\n============\n\n``manage.py migrate`` creates a ``django_redirect`` table in your database. This\nis a lookup table with ``site_id``, ``old_path`` and ``new_path`` fields.\n\nThe :class:`~django.contrib.redirects.middleware.RedirectFallbackMiddleware`\ndoes all of the work. Each time any Django application raises a 404\nerror, this middleware checks the redirects database for the requested\nURL as a last resort. Specifically, it checks for a redirect with the\ngiven ``old_path`` with a site ID that corresponds to the\n:setting:`SITE_ID` setting.\n\n* If it finds a match, and ``new_path`` is not empty, it redirects to\n  ``new_path`` using a 301 (\"Moved Permanently\") redirect. You can subclass\n  :class:`~django.contrib.redirects.middleware.RedirectFallbackMiddleware`\n  and set\n  :attr:`~django.contrib.redirects.middleware.RedirectFallbackMiddleware.response_redirect_class`\n  to :class:`django.http.HttpResponseRedirect` to use a\n  ``302 Moved Temporarily`` redirect instead.\n* If it finds a match, and ``new_path`` is empty, it sends a 410 (\"Gone\")\n  HTTP header and empty (content-less) response.\n* If it doesn't find a match, the request continues to be processed as\n  usual.\n\nThe middleware only gets activated for 404s -- not for 500s or responses of any\nother status code.\n\nNote that the order of :setting:`MIDDLEWARE` matters. Generally, you can put\n:class:`~django.contrib.redirects.middleware.RedirectFallbackMiddleware` at the\nend of the list, because it's a last resort.\n\nFor more on middleware, read the :doc:`middleware docs\n</topics/http/middleware>`.\n\nHow to add, change and delete redirects\n=======================================\n\nVia the admin interface\n-----------------------\n\nIf you've activated the automatic Django admin interface, you should see a\n\"Redirects\" section on the admin index page. Edit redirects as you edit any\nother object in the system.\n\nVia the Python API\n------------------\n\n.. class:: models.Redirect\n\n    Redirects are represented by a standard :doc:`Django model </topics/db/models>`,\n    which lives in :source:`django/contrib/redirects/models.py`. You can access\n    redirect objects via the :doc:`Django database API </topics/db/queries>`.\n\nMiddleware\n==========\n\n.. class:: middleware.RedirectFallbackMiddleware\n\n    You can change the :class:`~django.http.HttpResponse` classes used\n    by the middleware by creating a subclass of\n    :class:`~django.contrib.redirects.middleware.RedirectFallbackMiddleware`\n    and overriding ``response_gone_class`` and/or ``response_redirect_class``.\n\n    .. attribute:: response_gone_class\n\n        The :class:`~django.http.HttpResponse` class used when a\n        :class:`~django.contrib.redirects.models.Redirect` is not found for the\n        requested path or has a blank ``new_path`` value.\n\n        Defaults to :class:`~django.http.HttpResponseGone`.\n\n    .. attribute:: response_redirect_class\n\n        The :class:`~django.http.HttpResponse` class that handles the redirect.\n\n        Defaults to :class:`~django.http.HttpResponsePermanentRedirect`.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":97,"nodeType":"TextFile","repoName":null,"name":"expressions.txt","path":"docs/ref/models","text":"=================\nQuery Expressions\n=================\n\n.. currentmodule:: django.db.models\n\nQuery expressions describe a value or a computation that can be used as part of\nan update, create, filter, order by, annotation, or aggregate. When an\nexpression outputs a boolean value, it may be used directly in filters. There\nare a number of built-in expressions (documented below) that can be used to\nhelp you write queries. Expressions can be combined, or in some cases nested,\nto form more complex computations.\n\nSupported arithmetic\n====================\n\nDjango supports negation, addition, subtraction, multiplication, division,\nmodulo arithmetic, and the power operator on query expressions, using Python\nconstants, variables, and even other expressions.\n\nSome examples\n=============\n\n.. code-block:: python\n\n    from django.db.models import Count, F, Value\n    from django.db.models.functions import Length, Upper\n\n    # Find companies that have more employees than chairs.\n    Company.objects.filter(num_employees__gt=F('num_chairs'))\n\n    # Find companies that have at least twice as many employees\n    # as chairs. Both the querysets below are equivalent.\n    Company.objects.filter(num_employees__gt=F('num_chairs') * 2)\n    Company.objects.filter(\n        num_employees__gt=F('num_chairs') + F('num_chairs'))\n\n    # How many chairs are needed for each company to seat all employees?\n    >>> company = Company.objects.filter(\n    ...    num_employees__gt=F('num_chairs')).annotate(\n    ...    chairs_needed=F('num_employees') - F('num_chairs')).first()\n    >>> company.num_employees\n    120\n    >>> company.num_chairs\n    50\n    >>> company.chairs_needed\n    70\n\n    # Create a new company using expressions.\n    >>> company = Company.objects.create(name='Google', ticker=Upper(Value('goog')))\n    # Be sure to refresh it if you need to access the field.\n    >>> company.refresh_from_db()\n    >>> company.ticker\n    'GOOG'\n\n    # Annotate models with an aggregated value. Both forms\n    # below are equivalent.\n    Company.objects.annotate(num_products=Count('products'))\n    Company.objects.annotate(num_products=Count(F('products')))\n\n    # Aggregates can contain complex computations also\n    Company.objects.annotate(num_offerings=Count(F('products') + F('services')))\n\n    # Expressions can also be used in order_by(), either directly\n    Company.objects.order_by(Length('name').asc())\n    Company.objects.order_by(Length('name').desc())\n    # or using the double underscore lookup syntax.\n    from django.db.models import CharField\n    from django.db.models.functions import Length\n    CharField.register_lookup(Length)\n    Company.objects.order_by('name__length')\n\n    # Boolean expression can be used directly in filters.\n    from django.db.models import Exists\n    Company.objects.filter(\n        Exists(Employee.objects.filter(company=OuterRef('pk'), salary__gt=10))\n    )\n\nBuilt-in Expressions\n====================\n\n.. note::\n\n    These expressions are defined in ``django.db.models.expressions`` and\n    ``django.db.models.aggregates``, but for convenience they're available and\n    usually imported from :mod:`django.db.models`.\n\n``F()`` expressions\n-------------------\n\n.. class:: F\n\nAn ``F()`` object represents the value of a model field or annotated column. It\nmakes it possible to refer to model field values and perform  database\noperations using them without actually having to pull them out of the  database\ninto Python memory.\n\nInstead, Django uses the ``F()`` object to generate an SQL expression that\ndescribes the required operation at the database level.\n\nLet's try this with an example. Normally, one might do something like this::\n\n    # Tintin filed a news story!\n    reporter = Reporters.objects.get(name='Tintin')\n    reporter.stories_filed += 1\n    reporter.save()\n\nHere, we have pulled the value of ``reporter.stories_filed`` from the database\ninto memory and manipulated it using familiar Python operators, and then saved\nthe object back to the database. But instead we could also have done::\n\n    from django.db.models import F\n\n    reporter = Reporters.objects.get(name='Tintin')\n    reporter.stories_filed = F('stories_filed') + 1\n    reporter.save()\n\nAlthough ``reporter.stories_filed = F('stories_filed') + 1`` looks like a\nnormal Python assignment of value to an instance attribute, in fact it's an SQL\nconstruct describing an operation on the database.\n\nWhen Django encounters an instance of ``F()``, it overrides the standard Python\noperators to create an encapsulated SQL expression; in this case, one which\ninstructs the database to increment the database field represented by\n``reporter.stories_filed``.\n\nWhatever value is or was on ``reporter.stories_filed``, Python never gets to\nknow about it - it is dealt with entirely by the database. All Python does,\nthrough Django's ``F()`` class, is create the SQL syntax to refer to the field\nand describe the operation.\n\nTo access the new value saved this way, the object must be reloaded::\n\n   reporter = Reporters.objects.get(pk=reporter.pk)\n   # Or, more succinctly:\n   reporter.refresh_from_db()\n\nAs well as being used in operations on single instances as above, ``F()`` can\nbe used on ``QuerySets`` of object instances, with ``update()``. This reduces\nthe two queries we were using above - the ``get()`` and the\n:meth:`~Model.save()` - to just one::\n\n    reporter = Reporters.objects.filter(name='Tintin')\n    reporter.update(stories_filed=F('stories_filed') + 1)\n\nWe can also use :meth:`~django.db.models.query.QuerySet.update()` to increment\nthe field value on multiple objects - which could be very much faster than\npulling them all into Python from the database, looping over them, incrementing\nthe field value of each one, and saving each one back to the database::\n\n    Reporter.objects.all().update(stories_filed=F('stories_filed') + 1)\n\n``F()`` therefore can offer performance advantages by:\n\n* getting the database, rather than Python, to do work\n* reducing the number of queries some operations require\n\n.. _avoiding-race-conditions-using-f:\n\nAvoiding race conditions using ``F()``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nAnother useful benefit of ``F()`` is that having the database - rather than\nPython - update a field's value avoids a *race condition*.\n\nIf two Python threads execute the code in the first example above, one thread\ncould retrieve, increment, and save a field's value after the other has\nretrieved it from the database. The value that the second thread saves will be\nbased on the original value; the work of the first thread will be lost.\n\nIf the database is responsible for updating the field, the process is more\nrobust: it will only ever update the field based on the value of the field in\nthe database when the :meth:`~Model.save()` or ``update()`` is executed, rather\nthan based on its value when the instance was retrieved.\n\n``F()`` assignments persist after ``Model.save()``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n``F()`` objects assigned to model fields persist after saving the model\ninstance and will be applied on each :meth:`~Model.save()`. For example::\n\n    reporter = Reporters.objects.get(name='Tintin')\n    reporter.stories_filed = F('stories_filed') + 1\n    reporter.save()\n\n    reporter.name = 'Tintin Jr.'\n    reporter.save()\n\n``stories_filed`` will be updated twice in this case. If it's initially ``1``,\nthe final value will be ``3``. This persistence can be avoided by reloading the\nmodel object after saving it, for example, by using\n:meth:`~Model.refresh_from_db()`.\n\nUsing ``F()`` in filters\n~~~~~~~~~~~~~~~~~~~~~~~~\n\n``F()`` is also very useful in ``QuerySet`` filters, where they make it\npossible to filter a set of objects against criteria based on their field\nvalues, rather than on Python values.\n\nThis is documented in :ref:`using F() expressions in queries\n<using-f-expressions-in-filters>`.\n\n.. _using-f-with-annotations:\n\nUsing ``F()`` with annotations\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n``F()`` can be used to create dynamic fields on your models by combining\ndifferent fields with arithmetic::\n\n    company = Company.objects.annotate(\n        chairs_needed=F('num_employees') - F('num_chairs'))\n\nIf the fields that you're combining are of different types you'll need\nto tell Django what kind of field will be returned. Since ``F()`` does not\ndirectly support ``output_field`` you will need to wrap the expression with\n:class:`ExpressionWrapper`::\n\n    from django.db.models import DateTimeField, ExpressionWrapper, F\n\n    Ticket.objects.annotate(\n        expires=ExpressionWrapper(\n            F('active_at') + F('duration'), output_field=DateTimeField()))\n\nWhen referencing relational fields such as ``ForeignKey``, ``F()`` returns the\nprimary key value rather than a model instance::\n\n    >> car = Company.objects.annotate(built_by=F('manufacturer'))[0]\n    >> car.manufacturer\n    <Manufacturer: Toyota>\n    >> car.built_by\n    3\n\n.. _using-f-to-sort-null-values:\n\nUsing ``F()`` to sort null values\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nUse ``F()`` and the ``nulls_first`` or ``nulls_last`` keyword argument to\n:meth:`.Expression.asc` or :meth:`~.Expression.desc` to control the ordering of\na field's null values. By default, the ordering depends on your database.\n\nFor example, to sort companies that haven't been contacted (``last_contacted``\nis null) after companies that have been contacted::\n\n    from django.db.models import F\n    Company.objects.order_by(F('last_contacted').desc(nulls_last=True))\n\n.. _func-expressions:\n\n``Func()`` expressions\n----------------------\n\n``Func()`` expressions are the base type of all expressions that involve\ndatabase functions like ``COALESCE`` and ``LOWER``, or aggregates like ``SUM``.\nThey can be used directly::\n\n    from django.db.models import F, Func\n\n    queryset.annotate(field_lower=Func(F('field'), function='LOWER'))\n\nor they can be used to build a library of database functions::\n\n    class Lower(Func):\n        function = 'LOWER'\n\n    queryset.annotate(field_lower=Lower('field'))\n\nBut both cases will result in a queryset where each model is annotated with an\nextra attribute ``field_lower`` produced, roughly, from the following SQL:\n\n.. code-block:: sql\n\n    SELECT\n        ...\n        LOWER(\"db_table\".\"field\") as \"field_lower\"\n\nSee :doc:`database-functions` for a list of built-in database functions.\n\nThe ``Func`` API is as follows:\n\n.. class:: Func(*expressions, **extra)\n\n    .. attribute:: function\n\n        A class attribute describing the function that will be generated.\n        Specifically, the ``function`` will be interpolated as the ``function``\n        placeholder within :attr:`template`. Defaults to ``None``.\n\n    .. attribute:: template\n\n        A class attribute, as a format string, that describes the SQL that is\n        generated for this function. Defaults to\n        ``'%(function)s(%(expressions)s)'``.\n\n        If you're constructing SQL like ``strftime('%W', 'date')`` and need a\n        literal ``%`` character in the query, quadruple it (``%%%%``) in the\n        ``template`` attribute because the string is interpolated twice: once\n        during the template interpolation in ``as_sql()`` and once in the SQL\n        interpolation with the query parameters in the database cursor.\n\n    .. attribute:: arg_joiner\n\n        A class attribute that denotes the character used to join the list of\n        ``expressions`` together. Defaults to ``', '``.\n\n    .. attribute:: arity\n\n        A class attribute that denotes the number of arguments the function\n        accepts. If this attribute is set and the function is called with a\n        different number of expressions, ``TypeError`` will be raised. Defaults\n        to ``None``.\n\n    .. method:: as_sql(compiler, connection, function=None, template=None, arg_joiner=None, **extra_context)\n\n        Generates the SQL fragment for the database function. Returns a tuple\n        ``(sql, params)``, where ``sql`` is the SQL string, and ``params`` is\n        the list or tuple of query parameters.\n\n        The ``as_vendor()`` methods should use the ``function``, ``template``,\n        ``arg_joiner``, and any other ``**extra_context`` parameters to\n        customize the SQL as needed. For example:\n\n        .. code-block:: python\n            :caption: django/db/models/functions.py\n\n            class ConcatPair(Func):\n                ...\n                function = 'CONCAT'\n                ...\n\n                def as_mysql(self, compiler, connection, **extra_context):\n                    return super().as_sql(\n                        compiler, connection,\n                        function='CONCAT_WS',\n                        template=\"%(function)s('', %(expressions)s)\",\n                        **extra_context\n                    )\n\n        To avoid an SQL injection vulnerability, ``extra_context`` :ref:`must\n        not contain untrusted user input <avoiding-sql-injection-in-query-expressions>`\n        as these values are interpolated into the SQL string rather than passed\n        as query parameters, where the database driver would escape them.\n\nThe ``*expressions`` argument is a list of positional expressions that the\nfunction will be applied to. The expressions will be converted to strings,\njoined together with ``arg_joiner``, and then interpolated into the ``template``\nas the ``expressions`` placeholder.\n\nPositional arguments can be expressions or Python values. Strings are\nassumed to be column references and will be wrapped in ``F()`` expressions\nwhile other values will be wrapped in ``Value()`` expressions.\n\nThe ``**extra`` kwargs are ``key=value`` pairs that can be interpolated\ninto the ``template`` attribute. To avoid an SQL injection vulnerability,\n``extra`` :ref:`must not contain untrusted user input\n<avoiding-sql-injection-in-query-expressions>` as these values are interpolated\ninto the SQL string rather than passed as query parameters, where the database\ndriver would escape them.\n\nThe ``function``, ``template``, and ``arg_joiner`` keywords can be used to\nreplace the attributes of the same name without having to define your own\nclass. ``output_field`` can be used to define the expected return type.\n\n``Aggregate()`` expressions\n---------------------------\n\nAn aggregate expression is a special case of a :ref:`Func() expression\n<func-expressions>` that informs the query that a ``GROUP BY`` clause\nis required. All of the :ref:`aggregate functions <aggregation-functions>`,\nlike ``Sum()`` and ``Count()``, inherit from ``Aggregate()``.\n\nSince ``Aggregate``\\s are expressions and wrap expressions, you can represent\nsome complex computations::\n\n    from django.db.models import Count\n\n    Company.objects.annotate(\n        managers_required=(Count('num_employees') / 4) + Count('num_managers'))\n\nThe ``Aggregate`` API is as follows:\n\n.. class:: Aggregate(*expressions, output_field=None, distinct=False, filter=None, **extra)\n\n    .. attribute:: template\n\n        A class attribute, as a format string, that describes the SQL that is\n        generated for this aggregate. Defaults to\n        ``'%(function)s(%(distinct)s%(expressions)s)'``.\n\n    .. attribute:: function\n\n        A class attribute describing the aggregate function that will be\n        generated. Specifically, the ``function`` will be interpolated as the\n        ``function`` placeholder within :attr:`template`. Defaults to ``None``.\n\n    .. attribute:: window_compatible\n\n        Defaults to ``True`` since most aggregate functions can be used as the\n        source expression in :class:`~django.db.models.expressions.Window`.\n\n    .. attribute:: allow_distinct\n\n        A class attribute determining whether or not this aggregate function\n        allows passing a ``distinct`` keyword argument. If set to ``False``\n        (default), ``TypeError`` is raised if ``distinct=True`` is passed.\n\nThe ``expressions`` positional arguments can include expressions or the names\nof model fields. They will be converted to a string and used as the\n``expressions`` placeholder within the ``template``.\n\nThe ``output_field`` argument requires a model field instance, like\n``IntegerField()`` or ``BooleanField()``, into which Django will load the value\nafter it's retrieved from the database. Usually no arguments are needed when\ninstantiating the model field as any arguments relating to data validation\n(``max_length``, ``max_digits``, etc.) will not be enforced on the expression's\noutput value.\n\nNote that ``output_field`` is only required when Django is unable to determine\nwhat field type the result should be. Complex expressions that mix field types\nshould define the desired ``output_field``. For example, adding an\n``IntegerField()`` and a ``FloatField()`` together should probably have\n``output_field=FloatField()`` defined.\n\nThe ``distinct`` argument determines whether or not the aggregate function\nshould be invoked for each distinct value of ``expressions`` (or set of\nvalues, for multiple ``expressions``). The argument is only supported on\naggregates that have :attr:`~Aggregate.allow_distinct` set to ``True``.\n\nThe ``filter`` argument takes a :class:`Q object <django.db.models.Q>` that's\nused to filter the rows that are aggregated. See :ref:`conditional-aggregation`\nand :ref:`filtering-on-annotations` for example usage.\n\nThe ``**extra`` kwargs are ``key=value`` pairs that can be interpolated\ninto the ``template`` attribute.\n\nCreating your own Aggregate Functions\n-------------------------------------\n\nYou can create your own aggregate functions, too. At a minimum, you need to\ndefine ``function``, but you can also completely customize the SQL that is\ngenerated. Here's a brief example::\n\n    from django.db.models import Aggregate\n\n    class Sum(Aggregate):\n        # Supports SUM(ALL field).\n        function = 'SUM'\n        template = '%(function)s(%(all_values)s%(expressions)s)'\n        allow_distinct = False\n\n        def __init__(self, expression, all_values=False, **extra):\n            super().__init__(\n                expression,\n                all_values='ALL ' if all_values else '',\n                **extra\n            )\n\n``Value()`` expressions\n-----------------------\n\n.. class:: Value(value, output_field=None)\n\n\nA ``Value()`` object represents the smallest possible component of an\nexpression: a simple value. When you need to represent the value of an integer,\nboolean, or string within an expression, you can wrap that value within a\n``Value()``.\n\nYou will rarely need to use ``Value()`` directly. When you write the expression\n``F('field') + 1``, Django implicitly wraps the ``1`` in a ``Value()``,\nallowing simple values to be used in more complex expressions. You will need to\nuse ``Value()`` when you want to pass a string to an expression. Most\nexpressions interpret a string argument as the name of a field, like\n``Lower('name')``.\n\nThe ``value`` argument describes the value to be included in the expression,\nsuch as ``1``, ``True``, or ``None``. Django knows how to convert these Python\nvalues into their corresponding database type.\n\nThe ``output_field`` argument should be a model field instance, like\n``IntegerField()`` or ``BooleanField()``, into which Django will load the value\nafter it's retrieved from the database. Usually no arguments are needed when\ninstantiating the model field as any arguments relating to data validation\n(``max_length``, ``max_digits``, etc.) will not be enforced on the expression's\noutput value.\n\n``ExpressionWrapper()`` expressions\n-----------------------------------\n\n.. class:: ExpressionWrapper(expression, output_field)\n\n``ExpressionWrapper`` surrounds another expression and provides access to\nproperties, such as ``output_field``, that may not be available on other\nexpressions. ``ExpressionWrapper`` is necessary when using arithmetic on\n``F()`` expressions with different types as described in\n:ref:`using-f-with-annotations`.\n\nConditional expressions\n-----------------------\n\nConditional expressions allow you to use :keyword:`if` ... :keyword:`elif` ...\n:keyword:`else` logic in queries. Django natively supports SQL ``CASE``\nexpressions. For more details see :doc:`conditional-expressions`.\n\n``Subquery()`` expressions\n--------------------------\n\n.. class:: Subquery(queryset, output_field=None)\n\nYou can add an explicit subquery to a ``QuerySet`` using the ``Subquery``\nexpression.\n\nFor example, to annotate each post with the email address of the author of the\nnewest comment on that post::\n\n    >>> from django.db.models import OuterRef, Subquery\n    >>> newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at')\n    >>> Post.objects.annotate(newest_commenter_email=Subquery(newest.values('email')[:1]))\n\nOn PostgreSQL, the SQL looks like:\n\n.. code-block:: sql\n\n    SELECT \"post\".\"id\", (\n        SELECT U0.\"email\"\n        FROM \"comment\" U0\n        WHERE U0.\"post_id\" = (\"post\".\"id\")\n        ORDER BY U0.\"created_at\" DESC LIMIT 1\n    ) AS \"newest_commenter_email\" FROM \"post\"\n\n.. note::\n\n    The examples in this section are designed to show how to force\n    Django to execute a subquery. In some cases it may be possible to\n    write an equivalent queryset that performs the same task more\n    clearly or efficiently.\n\nReferencing columns from the outer queryset\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. class:: OuterRef(field)\n\nUse ``OuterRef`` when a queryset in a ``Subquery`` needs to refer to a field\nfrom the outer query. It acts like an :class:`F` expression except that the\ncheck to see if it refers to a valid field isn't made until the outer queryset\nis resolved.\n\nInstances of ``OuterRef`` may be used in conjunction with nested instances\nof ``Subquery`` to refer to a containing queryset that isn't the immediate\nparent. For example, this queryset would need to be within a nested pair of\n``Subquery`` instances to resolve correctly::\n\n    >>> Book.objects.filter(author=OuterRef(OuterRef('pk')))\n\nLimiting a subquery to a single column\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThere are times when a single column must be returned from a ``Subquery``, for\ninstance, to use a ``Subquery`` as the target of an ``__in`` lookup. To return\nall comments for posts published within the last day::\n\n    >>> from datetime import timedelta\n    >>> from django.utils import timezone\n    >>> one_day_ago = timezone.now() - timedelta(days=1)\n    >>> posts = Post.objects.filter(published_at__gte=one_day_ago)\n    >>> Comment.objects.filter(post__in=Subquery(posts.values('pk')))\n\nIn this case, the subquery must use :meth:`~.QuerySet.values`\nto return only a single column: the primary key of the post.\n\nLimiting the subquery to a single row\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nTo prevent a subquery from returning multiple rows, a slice (``[:1]``) of the\nqueryset is used::\n\n    >>> subquery = Subquery(newest.values('email')[:1])\n    >>> Post.objects.annotate(newest_commenter_email=subquery)\n\nIn this case, the subquery must only return a single column *and* a single\nrow: the email address of the most recently created comment.\n\n(Using :meth:`~.QuerySet.get` instead of a slice would fail because the\n``OuterRef`` cannot be resolved until the queryset is used within a\n``Subquery``.)\n\n``Exists()`` subqueries\n~~~~~~~~~~~~~~~~~~~~~~~\n\n.. class:: Exists(queryset)\n\n``Exists`` is a ``Subquery`` subclass that uses an SQL ``EXISTS`` statement. In\nmany cases it will perform better than a subquery since the database is able to\nstop evaluation of the subquery when a first matching row is found.\n\nFor example, to annotate each post with whether or not it has a comment from\nwithin the last day::\n\n    >>> from django.db.models import Exists, OuterRef\n    >>> from datetime import timedelta\n    >>> from django.utils import timezone\n    >>> one_day_ago = timezone.now() - timedelta(days=1)\n    >>> recent_comments = Comment.objects.filter(\n    ...     post=OuterRef('pk'),\n    ...     created_at__gte=one_day_ago,\n    ... )\n    >>> Post.objects.annotate(recent_comment=Exists(recent_comments))\n\nOn PostgreSQL, the SQL looks like:\n\n.. code-block:: sql\n\n    SELECT \"post\".\"id\", \"post\".\"published_at\", EXISTS(\n        SELECT U0.\"id\", U0.\"post_id\", U0.\"email\", U0.\"created_at\"\n        FROM \"comment\" U0\n        WHERE (\n            U0.\"created_at\" >= YYYY-MM-DD HH:MM:SS AND\n            U0.\"post_id\" = (\"post\".\"id\")\n        )\n    ) AS \"recent_comment\" FROM \"post\"\n\nIt's unnecessary to force ``Exists`` to refer to a single column, since the\ncolumns are discarded and a boolean result is returned. Similarly, since\nordering is unimportant within an SQL ``EXISTS`` subquery and would only\ndegrade performance, it's automatically removed.\n\nYou can query using ``NOT EXISTS`` with ``~Exists()``.\n\nFiltering on a ``Subquery()`` or ``Exists()`` expressions\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n``Subquery()`` that returns a boolean value and ``Exists()`` may be used as a\n``condition`` in :class:`~django.db.models.expressions.When` expressions, or to\ndirectly filter a queryset::\n\n    >>> recent_comments = Comment.objects.filter(...)  # From above\n    >>> Post.objects.filter(Exists(recent_comments))\n\nThis will ensure that the subquery will not be added to the ``SELECT`` columns,\nwhich may result in a better performance.\n\nUsing aggregates within a ``Subquery`` expression\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nAggregates may be used within a ``Subquery``, but they require a specific\ncombination of :meth:`~.QuerySet.filter`, :meth:`~.QuerySet.values`, and\n:meth:`~.QuerySet.annotate` to get the subquery grouping correct.\n\nAssuming both models have a ``length`` field, to find posts where the post\nlength is greater than the total length of all combined comments::\n\n    >>> from django.db.models import OuterRef, Subquery, Sum\n    >>> comments = Comment.objects.filter(post=OuterRef('pk')).order_by().values('post')\n    >>> total_comments = comments.annotate(total=Sum('length')).values('total')\n    >>> Post.objects.filter(length__gt=Subquery(total_comments))\n\nThe initial ``filter(...)`` limits the subquery to the relevant parameters.\n``order_by()`` removes the default :attr:`~django.db.models.Options.ordering`\n(if any) on the ``Comment`` model. ``values('post')`` aggregates comments by\n``Post``. Finally, ``annotate(...)`` performs the aggregation. The order in\nwhich these queryset methods are applied is important. In this case, since the\nsubquery must be limited to a single column, ``values('total')`` is required.\n\nThis is the only way to perform an aggregation within a ``Subquery``, as\nusing :meth:`~.QuerySet.aggregate` attempts to evaluate the queryset (and if\nthere is an ``OuterRef``, this will not be possible to resolve).\n\nRaw SQL expressions\n-------------------\n\n.. currentmodule:: django.db.models.expressions\n\n.. class:: RawSQL(sql, params, output_field=None)\n\nSometimes database expressions can't easily express a complex ``WHERE`` clause.\nIn these edge cases, use the ``RawSQL`` expression. For example::\n\n    >>> from django.db.models.expressions import RawSQL\n    >>> queryset.annotate(val=RawSQL(\"select col from sometable where othercol = %s\", (someparam,)))\n\nThese extra lookups may not be portable to different database engines (because\nyou're explicitly writing SQL code) and violate the DRY principle, so you\nshould avoid them if possible.\n\n.. warning::\n\n    To protect against `SQL injection attacks\n    <https://en.wikipedia.org/wiki/SQL_injection>`_, you must escape any\n    parameters that the user can control by using ``params``. ``params`` is a\n    required argument to force you to acknowledge that you're not interpolating\n    your SQL with user-provided data.\n\n    You also must not quote placeholders in the SQL string. This example is\n    vulnerable to SQL injection because of the quotes around ``%s``::\n\n        RawSQL(\"select col from sometable where othercol = '%s'\")  # unsafe!\n\n    You can read more about how Django's :ref:`SQL injection protection\n    <sql-injection-protection>` works.\n\nWindow functions\n----------------\n\nWindow functions provide a way to apply functions on partitions. Unlike a\nnormal aggregation function which computes a final result for each set defined\nby the group by, window functions operate on :ref:`frames <window-frames>` and\npartitions, and compute the result for each row.\n\nYou can specify multiple windows in the same query which in Django ORM would be\nequivalent to including multiple expressions in a :doc:`QuerySet.annotate()\n</topics/db/aggregation>` call. The ORM doesn't make use of named windows,\ninstead they are part of the selected columns.\n\n.. class:: Window(expression, partition_by=None, order_by=None, frame=None, output_field=None)\n\n    .. attribute:: filterable\n\n        Defaults to ``False``. The SQL standard disallows referencing window\n        functions in the ``WHERE`` clause and Django raises an exception when\n        constructing a ``QuerySet`` that would do that.\n\n    .. attribute:: template\n\n        Defaults to ``%(expression)s OVER (%(window)s)'``. If only the\n        ``expression`` argument is provided, the window clause will be blank.\n\nThe ``Window`` class is the main expression for an ``OVER`` clause.\n\nThe ``expression`` argument is either a :ref:`window function\n<window-functions>`, an :ref:`aggregate function <aggregation-functions>`, or\nan expression that's compatible in a window clause.\n\nThe ``partition_by`` argument is a list of expressions (column names should be\nwrapped in an ``F``-object) that control the partitioning of the rows.\nPartitioning narrows which rows are used to compute the result set.\n\nThe ``output_field`` is specified either as an argument or by the expression.\n\nThe ``order_by`` argument accepts a sequence of expressions on which you can\ncall :meth:`~django.db.models.Expression.asc` and\n:meth:`~django.db.models.Expression.desc`. The ordering controls the order in\nwhich the expression is applied. For example, if you sum over the rows in a\npartition, the first result is the value of the first row, the second is the\nsum of first and second row.\n\nThe ``frame`` parameter specifies which other rows that should be used in the\ncomputation. See :ref:`window-frames` for details.\n\nFor example, to annotate each movie with the average rating for the movies by\nthe same studio in the same genre and release year::\n\n    >>> from django.db.models import Avg, F, Window\n    >>> from django.db.models.functions import ExtractYear\n    >>> Movie.objects.annotate(\n    >>>     avg_rating=Window(\n    >>>         expression=Avg('rating'),\n    >>>         partition_by=[F('studio'), F('genre')],\n    >>>         order_by=ExtractYear('released').asc(),\n    >>>     ),\n    >>> )\n\nThis allows you to check if a movie is rated better or worse than its peers.\n\nYou may want to apply multiple expressions over the same window, i.e., the\nsame partition and frame. For example, you could modify the previous example\nto also include the best and worst rating in each movie's group (same studio,\ngenre, and release year) by using three window functions in the same query. The\npartition and ordering from the previous example is extracted into a dictionary\nto reduce repetition::\n\n    >>> from django.db.models import Avg, F, Max, Min, Window\n    >>> from django.db.models.functions import ExtractYear\n    >>> window = {\n    >>>    'partition_by': [F('studio'), F('genre')],\n    >>>    'order_by': ExtractYear('released').asc(),\n    >>> }\n    >>> Movie.objects.annotate(\n    >>>     avg_rating=Window(\n    >>>         expression=Avg('rating'), **window,\n    >>>     ),\n    >>>     best=Window(\n    >>>         expression=Max('rating'), **window,\n    >>>     ),\n    >>>     worst=Window(\n    >>>         expression=Min('rating'), **window,\n    >>>     ),\n    >>> )\n\nAmong Django's built-in database backends, MySQL 8.0.2+, PostgreSQL, and Oracle\nsupport window expressions. Support for different window expression features\nvaries among the different databases. For example, the options in\n:meth:`~django.db.models.Expression.asc` and\n:meth:`~django.db.models.Expression.desc` may not be supported. Consult the\ndocumentation for your database as needed.\n\n.. _window-frames:\n\nFrames\n~~~~~~\n\nFor a window frame, you can choose either a range-based sequence of rows or an\nordinary sequence of rows.\n\n.. class:: ValueRange(start=None, end=None)\n\n    .. attribute:: frame_type\n\n        This attribute is set to ``'RANGE'``.\n\n    PostgreSQL has limited support for ``ValueRange`` and only supports use of\n    the standard start and end points, such as ``CURRENT ROW`` and ``UNBOUNDED\n    FOLLOWING``.\n\n.. class:: RowRange(start=None, end=None)\n\n    .. attribute:: frame_type\n\n        This attribute is set to ``'ROWS'``.\n\nBoth classes return SQL with the template::\n\n    %(frame_type)s BETWEEN %(start)s AND %(end)s\n\nFrames narrow the rows that are used for computing the result. They shift from\nsome start point to some specified end point. Frames can be used with and\nwithout partitions, but it's often a good idea to specify an ordering of the\nwindow to ensure a deterministic result. In a frame, a peer in a frame is a row\nwith an equivalent value, or all rows if an ordering clause isn't present.\n\nThe default starting point for a frame is ``UNBOUNDED PRECEDING`` which is the\nfirst row of the partition. The end point is always explicitly included in the\nSQL generated by the ORM and is by default ``UNBOUNDED FOLLOWING``. The default\nframe includes all rows from the partition to the last row in the set.\n\nThe accepted values for the ``start`` and ``end`` arguments are ``None``, an\ninteger, or zero. A negative integer for ``start`` results in ``N preceding``,\nwhile ``None`` yields ``UNBOUNDED PRECEDING``. For both ``start`` and ``end``,\nzero will return ``CURRENT ROW``. Positive integers are accepted for ``end``.\n\nThere's a difference in what ``CURRENT ROW`` includes. When specified in\n``ROWS`` mode, the frame starts or ends with the current row. When specified in\n``RANGE`` mode, the frame starts or ends at the first or last peer according to\nthe ordering clause. Thus, ``RANGE CURRENT ROW`` evaluates the expression for\nrows which have the same value specified by the ordering. Because the template\nincludes both the ``start`` and ``end`` points, this may be expressed with::\n\n    ValueRange(start=0, end=0)\n\nIf a movie's \"peers\" are described as movies released by the same studio in the\nsame genre in the same year, this ``RowRange`` example annotates each movie\nwith the average rating of a movie's two prior and two following peers::\n\n    >>> from django.db.models import Avg, F, RowRange, Window\n    >>> from django.db.models.functions import ExtractYear\n    >>> Movie.objects.annotate(\n    >>>     avg_rating=Window(\n    >>>         expression=Avg('rating'),\n    >>>         partition_by=[F('studio'), F('genre')],\n    >>>         order_by=ExtractYear('released').asc(),\n    >>>         frame=RowRange(start=-2, end=2),\n    >>>     ),\n    >>> )\n\nIf the database supports it, you can specify the start and end points based on\nvalues of an expression in the partition. If the ``released`` field of the\n``Movie`` model stores the release month of each movies, this ``ValueRange``\nexample annotates each movie with the average rating of a movie's peers\nreleased between twelve months before and twelve months after the each movie.\n\n    >>> from django.db.models import Avg, ExpressionList, F, ValueRange, Window\n    >>> Movie.objects.annotate(\n    >>>     avg_rating=Window(\n    >>>         expression=Avg('rating'),\n    >>>         partition_by=[F('studio'), F('genre')],\n    >>>         order_by=F('released').asc(),\n    >>>         frame=ValueRange(start=-12, end=12),\n    >>>     ),\n    >>> )\n\n.. currentmodule:: django.db.models\n\nTechnical Information\n=====================\n\nBelow you'll find technical implementation details that may be useful to\nlibrary authors. The technical API and examples below will help with\ncreating generic query expressions that can extend the built-in functionality\nthat Django provides.\n\nExpression API\n--------------\n\nQuery expressions implement the :ref:`query expression API <query-expression>`,\nbut also expose a number of extra methods and attributes listed below. All\nquery expressions must inherit from ``Expression()`` or a relevant\nsubclass.\n\nWhen a query expression wraps another expression, it is responsible for\ncalling the appropriate methods on the wrapped expression.\n\n.. class:: Expression\n\n    .. attribute:: contains_aggregate\n\n        Tells Django that this expression contains an aggregate and that a\n        ``GROUP BY`` clause needs to be added to the query.\n\n    .. attribute:: contains_over_clause\n\n        Tells Django that this expression contains a\n        :class:`~django.db.models.expressions.Window` expression. It's used,\n        for example, to disallow window function expressions in queries that\n        modify data.\n\n    .. attribute:: filterable\n\n        Tells Django that this expression can be referenced in\n        :meth:`.QuerySet.filter`. Defaults to ``True``.\n\n    .. attribute:: window_compatible\n\n        Tells Django that this expression can be used as the source expression\n        in :class:`~django.db.models.expressions.Window`. Defaults to\n        ``False``.\n\n    .. method:: resolve_expression(query=None, allow_joins=True, reuse=None, summarize=False, for_save=False)\n\n        Provides the chance to do any pre-processing or validation of\n        the expression before it's added to the query. ``resolve_expression()``\n        must also be called on any nested expressions. A ``copy()`` of ``self``\n        should be returned with any necessary transformations.\n\n        ``query`` is the backend query implementation.\n\n        ``allow_joins`` is a boolean that allows or denies the use of\n        joins in the query.\n\n        ``reuse`` is a set of reusable joins for multi-join scenarios.\n\n        ``summarize`` is a boolean that, when ``True``, signals that the\n        query being computed is a terminal aggregate query.\n\n        ``for_save`` is a boolean that, when ``True``, signals that the query\n        being executed is performing a create or update.\n\n    .. method:: get_source_expressions()\n\n        Returns an ordered list of inner expressions. For example::\n\n          >>> Sum(F('foo')).get_source_expressions()\n          [F('foo')]\n\n    .. method:: set_source_expressions(expressions)\n\n        Takes a list of expressions and stores them such that\n        ``get_source_expressions()`` can return them.\n\n    .. method:: relabeled_clone(change_map)\n\n        Returns a clone (copy) of ``self``, with any column aliases relabeled.\n        Column aliases are renamed when subqueries are created.\n        ``relabeled_clone()`` should also be called on any nested expressions\n        and assigned to the clone.\n\n        ``change_map`` is a dictionary mapping old aliases to new aliases.\n\n        Example::\n\n          def relabeled_clone(self, change_map):\n              clone = copy.copy(self)\n              clone.expression = self.expression.relabeled_clone(change_map)\n              return clone\n\n    .. method:: convert_value(value, expression, connection)\n\n        A hook allowing the expression to coerce ``value`` into a more\n        appropriate type.\n\n        ``expression`` is the same as ``self``.\n\n    .. method:: get_group_by_cols(alias=None)\n\n        Responsible for returning the list of columns references by\n        this expression. ``get_group_by_cols()`` should be called on any\n        nested expressions. ``F()`` objects, in particular, hold a reference\n        to a column. The ``alias`` parameter will be ``None`` unless the\n        expression has been annotated and is used for grouping.\n\n    .. method:: asc(nulls_first=False, nulls_last=False)\n\n        Returns the expression ready to be sorted in ascending order.\n\n        ``nulls_first`` and ``nulls_last`` define how null values are sorted.\n        See :ref:`using-f-to-sort-null-values` for example usage.\n\n    .. method:: desc(nulls_first=False, nulls_last=False)\n\n        Returns the expression ready to be sorted in descending order.\n\n        ``nulls_first`` and ``nulls_last`` define how null values are sorted.\n        See :ref:`using-f-to-sort-null-values` for example usage.\n\n    .. method:: reverse_ordering()\n\n        Returns ``self`` with any modifications required to reverse the sort\n        order within an ``order_by`` call. As an example, an expression\n        implementing ``NULLS LAST`` would change its value to be\n        ``NULLS FIRST``. Modifications are only required for expressions that\n        implement sort order like ``OrderBy``. This method is called when\n        :meth:`~django.db.models.query.QuerySet.reverse()` is called on a\n        queryset.\n\nWriting your own Query Expressions\n----------------------------------\n\nYou can write your own query expression classes that use, and can integrate\nwith, other query expressions. Let's step through an example by writing an\nimplementation of the ``COALESCE`` SQL function, without using the built-in\n:ref:`Func() expressions <func-expressions>`.\n\nThe ``COALESCE`` SQL function is defined as taking a list of columns or\nvalues. It will return the first column or value that isn't ``NULL``.\n\nWe'll start by defining the template to be used for SQL generation and\nan ``__init__()`` method to set some attributes::\n\n  import copy\n  from django.db.models import Expression\n\n  class Coalesce(Expression):\n      template = 'COALESCE( %(expressions)s )'\n\n      def __init__(self, expressions, output_field):\n        super().__init__(output_field=output_field)\n        if len(expressions) < 2:\n            raise ValueError('expressions must have at least 2 elements')\n        for expression in expressions:\n            if not hasattr(expression, 'resolve_expression'):\n                raise TypeError('%r is not an Expression' % expression)\n        self.expressions = expressions\n\nWe do some basic validation on the parameters, including requiring at least\n2 columns or values, and ensuring they are expressions. We are requiring\n``output_field`` here so that Django knows what kind of model field to assign\nthe eventual result to.\n\nNow we implement the pre-processing and validation. Since we do not have\nany of our own validation at this point, we delegate to the nested\nexpressions::\n\n    def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):\n        c = self.copy()\n        c.is_summary = summarize\n        for pos, expression in enumerate(self.expressions):\n            c.expressions[pos] = expression.resolve_expression(query, allow_joins, reuse, summarize, for_save)\n        return c\n\nNext, we write the method responsible for generating the SQL::\n\n    def as_sql(self, compiler, connection, template=None):\n        sql_expressions, sql_params = [], []\n        for expression in self.expressions:\n            sql, params = compiler.compile(expression)\n            sql_expressions.append(sql)\n            sql_params.extend(params)\n        template = template or self.template\n        data = {'expressions': ','.join(sql_expressions)}\n        return template % data, sql_params\n\n    def as_oracle(self, compiler, connection):\n        \"\"\"\n        Example of vendor specific handling (Oracle in this case).\n        Let's make the function name lowercase.\n        \"\"\"\n        return self.as_sql(compiler, connection, template='coalesce( %(expressions)s )')\n\n``as_sql()`` methods can support custom keyword arguments, allowing\n``as_vendorname()`` methods to override data used to generate the SQL string.\nUsing ``as_sql()`` keyword arguments for customization is preferable to\nmutating ``self`` within ``as_vendorname()`` methods as the latter can lead to\nerrors when running on different database backends. If your class relies on\nclass attributes to define data, consider allowing overrides in your\n``as_sql()`` method.\n\nWe generate the SQL for each of the ``expressions`` by using the\n``compiler.compile()`` method, and join the result together with commas.\nThen the template is filled out with our data and the SQL and parameters\nare returned.\n\nWe've also defined a custom implementation that is specific to the Oracle\nbackend. The ``as_oracle()`` function will be called instead of ``as_sql()``\nif the Oracle backend is in use.\n\nFinally, we implement the rest of the methods that allow our query expression\nto play nice with other query expressions::\n\n    def get_source_expressions(self):\n        return self.expressions\n\n    def set_source_expressions(self, expressions):\n        self.expressions = expressions\n\nLet's see how it works::\n\n    >>> from django.db.models import F, Value, CharField\n    >>> qs = Company.objects.annotate(\n    ...    tagline=Coalesce([\n    ...        F('motto'),\n    ...        F('ticker_name'),\n    ...        F('description'),\n    ...        Value('No Tagline')\n    ...        ], output_field=CharField()))\n    >>> for c in qs:\n    ...     print(\"%s: %s\" % (c.name, c.tagline))\n    ...\n    Google: Do No Evil\n    Apple: AAPL\n    Yahoo: Internet Company\n    Django Software Foundation: No Tagline\n\n.. _avoiding-sql-injection-in-query-expressions:\n\nAvoiding SQL injection\n~~~~~~~~~~~~~~~~~~~~~~\n\nSince a ``Func``'s keyword arguments for ``__init__()``  (``**extra``) and\n``as_sql()`` (``**extra_context``) are interpolated into the SQL string rather\nthan passed as query parameters (where the database driver would escape them),\nthey must not contain untrusted user input.\n\nFor example, if ``substring`` is user-provided, this function is vulnerable to\nSQL injection::\n\n    from django.db.models import Func\n\n    class Position(Func):\n        function = 'POSITION'\n        template = \"%(function)s('%(substring)s' in %(expressions)s)\"\n\n        def __init__(self, expression, substring):\n            # substring=substring is an SQL injection vulnerability!\n            super().__init__(expression, substring=substring)\n\nThis function generates an SQL string without any parameters. Since\n``substring`` is passed to ``super().__init__()`` as a keyword argument, it's\ninterpolated into the SQL string before the query is sent to the database.\n\nHere's a corrected rewrite::\n\n    class Position(Func):\n        function = 'POSITION'\n        arg_joiner = ' IN '\n\n        def __init__(self, expression, substring):\n            super().__init__(substring, expression)\n\nWith ``substring`` instead passed as a positional argument, it'll be passed as\na parameter in the database query.\n\nAdding support in third-party database backends\n-----------------------------------------------\n\nIf you're using a database backend that uses a different SQL syntax for a\ncertain function, you can add support for it by monkey patching a new method\nonto the function's class.\n\nLet's say we're writing a backend for Microsoft's SQL Server which uses the SQL\n``LEN`` instead of ``LENGTH`` for the :class:`~functions.Length` function.\nWe'll monkey patch a new method called ``as_sqlserver()`` onto the ``Length``\nclass::\n\n    from django.db.models.functions import Length\n\n    def sqlserver_length(self, compiler, connection):\n        return self.as_sql(compiler, connection, function='LEN')\n\n    Length.as_sqlserver = sqlserver_length\n\nYou can also customize the SQL using the ``template`` parameter of ``as_sql()``.\n\nWe use ``as_sqlserver()`` because ``django.db.connection.vendor`` returns\n``sqlserver`` for the backend.\n\nThird-party backends can register their functions in the top level\n``__init__.py`` file of the backend package or in a top level ``expressions.py``\nfile (or package) that is imported from the top level ``__init__.py``.\n\nFor user projects wishing to patch the backend that they're using, this code\nshould live in an :meth:`AppConfig.ready()<django.apps.AppConfig.ready>` method.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":98,"nodeType":"TextFile","repoName":null,"name":"lookups.txt","path":"docs/ref/models","text":"====================\nLookup API reference\n====================\n\n.. module:: django.db.models.lookups\n   :synopsis: Lookups API\n\n.. currentmodule:: django.db.models\n\nThis document has the API references of lookups, the Django API for building\nthe ``WHERE`` clause of a database query. To learn how to *use* lookups, see\n:doc:`/topics/db/queries`; to learn how to *create* new lookups, see\n:doc:`/howto/custom-lookups`.\n\nThe lookup API has two components: a :class:`~lookups.RegisterLookupMixin` class\nthat registers lookups, and the :ref:`Query Expression API <query-expression>`, a\nset of methods that a class has to implement to be registrable as a lookup.\n\nDjango has two base classes that follow the query expression API and from where\nall Django builtin lookups are derived:\n\n* :class:`Lookup`: to lookup a field (e.g. the ``exact`` of ``field_name__exact``)\n* :class:`Transform`: to transform a field\n\nA lookup expression consists of three parts:\n\n* Fields part (e.g. ``Book.objects.filter(author__best_friends__first_name...``);\n* Transforms part (may be omitted) (e.g. ``__lower__first3chars__reversed``);\n* A lookup (e.g. ``__icontains``) that, if omitted, defaults to ``__exact``.\n\n.. _lookup-registration-api:\n\nRegistration API\n================\n\nDjango uses :class:`~lookups.RegisterLookupMixin` to give a class the interface to\nregister lookups on itself. The two prominent examples are\n:class:`~django.db.models.Field`, the base class of all model fields, and\n:class:`Transform`, the base class of all Django transforms.\n\n.. class:: lookups.RegisterLookupMixin\n\n    A mixin that implements the lookup API on a class.\n\n    .. classmethod:: register_lookup(lookup, lookup_name=None)\n\n        Registers a new lookup in the class. For example\n        ``DateField.register_lookup(YearExact)`` will register ``YearExact``\n        lookup on ``DateField``. It overrides a lookup that already exists with\n        the same name. ``lookup_name`` will be used for this lookup if\n        provided, otherwise ``lookup.lookup_name`` will be used.\n\n    .. method:: get_lookup(lookup_name)\n\n        Returns the :class:`Lookup` named ``lookup_name`` registered in the class.\n        The default implementation looks recursively on all parent classes\n        and checks if any has a registered lookup named ``lookup_name``, returning\n        the first match.\n\n    .. method:: get_lookups()\n\n        Returns a dictionary of each lookup name registered in the class mapped\n        to the :class:`Lookup` class.\n\n    .. method:: get_transform(transform_name)\n\n        Returns a :class:`Transform` named ``transform_name``. The default\n        implementation looks recursively on all parent classes to check if any\n        has the registered transform named ``transform_name``, returning the first\n        match.\n\nFor a class to be a lookup, it must follow the :ref:`Query Expression API\n<query-expression>`. :class:`~Lookup` and :class:`~Transform` naturally\nfollow this API.\n\n.. _query-expression:\n\nThe Query Expression API\n========================\n\nThe query expression API is a common set of methods that classes define to be\nusable in query expressions to translate themselves into SQL expressions. Direct\nfield references, aggregates, and ``Transform`` are examples that follow this\nAPI. A class is said to follow the query expression API when it implements the\nfollowing methods:\n\n.. method:: as_sql(compiler, connection)\n\n    Generates the SQL fragment for the expression. Returns a tuple\n    ``(sql, params)``, where ``sql`` is the SQL string, and ``params`` is the\n    list or tuple of query parameters. The ``compiler`` is an ``SQLCompiler``\n    object, which has a ``compile()`` method that can be used to compile other\n    expressions. The ``connection`` is the connection used to execute the\n    query.\n\n    Calling ``expression.as_sql()`` is usually incorrect - instead\n    ``compiler.compile(expression)`` should be used. The ``compiler.compile()``\n    method will take care of calling vendor-specific methods of the expression.\n\n    Custom keyword arguments may be defined on this method if it's likely that\n    ``as_vendorname()`` methods or subclasses will need to supply data to\n    override the generation of the SQL string. See :meth:`Func.as_sql` for\n    example usage.\n\n.. method:: as_vendorname(compiler, connection)\n\n    Works like ``as_sql()`` method. When an expression is compiled by\n    ``compiler.compile()``, Django will first try to call ``as_vendorname()``,\n    where ``vendorname`` is the vendor name of the backend used for executing\n    the query. The ``vendorname`` is one of ``postgresql``, ``oracle``,\n    ``sqlite``, or ``mysql`` for Django's built-in backends.\n\n.. method:: get_lookup(lookup_name)\n\n    Must return the lookup named ``lookup_name``. For instance, by returning\n    ``self.output_field.get_lookup(lookup_name)``.\n\n.. method:: get_transform(transform_name)\n\n    Must return the lookup named ``transform_name``. For instance, by returning\n    ``self.output_field.get_transform(transform_name)``.\n\n.. attribute:: output_field\n\n    Defines the type of class returned by the ``get_lookup()`` method. It must\n    be a :class:`~django.db.models.Field` instance.\n\n``Transform`` reference\n=======================\n\n.. class:: Transform\n\n    A ``Transform`` is a generic class to implement field transformations. A\n    prominent example is ``__year`` that transforms a ``DateField`` into a\n    ``IntegerField``.\n\n    The notation to use a ``Transform`` in a lookup expression is\n    ``<expression>__<transformation>`` (e.g. ``date__year``).\n\n    This class follows the :ref:`Query Expression API <query-expression>`, which\n    implies that you can use ``<expression>__<transform1>__<transform2>``. It's\n    a specialized :ref:`Func() expression <func-expressions>` that only accepts\n    one argument.  It can also be used on the right hand side of a filter or\n    directly as an annotation.\n\n    .. attribute:: bilateral\n\n        A boolean indicating whether this transformation should apply to both\n        ``lhs`` and ``rhs``. Bilateral transformations will be applied to ``rhs`` in\n        the same order as they appear in the lookup expression. By default it is set\n        to ``False``. For example usage, see :doc:`/howto/custom-lookups`.\n\n    .. attribute:: lhs\n\n        The left-hand side - what is being transformed. It must follow the\n        :ref:`Query Expression API <query-expression>`.\n\n    .. attribute:: lookup_name\n\n        The name of the lookup, used for identifying it on parsing query\n        expressions. It cannot contain the string ``\"__\"``.\n\n    .. attribute:: output_field\n\n        Defines the class this transformation outputs. It must be a\n        :class:`~django.db.models.Field` instance. By default is the same as\n        its ``lhs.output_field``.\n\n``Lookup`` reference\n====================\n\n.. class:: Lookup\n\n    A ``Lookup`` is a generic class to implement lookups. A lookup is a query\n    expression with a left-hand side, :attr:`lhs`; a right-hand side,\n    :attr:`rhs`; and a ``lookup_name`` that is used to produce a boolean\n    comparison between ``lhs`` and ``rhs`` such as ``lhs in rhs`` or\n    ``lhs > rhs``.\n\n    The notation to use a lookup in an expression is\n    ``<lhs>__<lookup_name>=<rhs>``.\n\n    This class doesn't follow the :ref:`Query Expression API <query-expression>`\n    since it has ``=<rhs>`` on its construction: lookups are always the end of\n    a lookup expression.\n\n    .. attribute:: lhs\n\n        The left-hand side - what is being looked up. The object must follow\n        the :ref:`Query Expression API <query-expression>`.\n\n    .. attribute:: rhs\n\n        The right-hand side - what ``lhs`` is being compared against. It can be\n        a plain value, or something that compiles into SQL, typically an\n        ``F()`` object or a ``QuerySet``.\n\n    .. attribute:: lookup_name\n\n        The name of this lookup, used to identify it on parsing query\n        expressions. It cannot contain the string ``\"__\"``.\n\n    .. method:: process_lhs(compiler, connection, lhs=None)\n\n        Returns a tuple ``(lhs_string, lhs_params)``, as returned by\n        ``compiler.compile(lhs)``. This method can be overridden to tune how\n        the ``lhs`` is processed.\n\n        ``compiler`` is an ``SQLCompiler`` object, to be used like\n        ``compiler.compile(lhs)`` for compiling ``lhs``. The ``connection``\n        can be used for compiling vendor specific SQL. If ``lhs`` is not\n        ``None``, use it as the processed ``lhs`` instead of ``self.lhs``.\n\n    .. method:: process_rhs(compiler, connection)\n\n        Behaves the same way as :meth:`process_lhs`, for the right-hand side.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":99,"nodeType":"TextFile","repoName":null,"name":"flatpages.txt","path":"docs/ref/contrib","text":"=================\nThe flatpages app\n=================\n\n.. module:: django.contrib.flatpages\n   :synopsis: A framework for managing simple ?flat? HTML content in a database.\n\nDjango comes with an optional \"flatpages\" application. It lets you store \"flat\"\nHTML content in a database and handles the management for you via Django's\nadmin interface and a Python API.\n\nA flatpage is a object with a URL, title and content. Use it for one-off,\nspecial-case pages, such as \"About\" or \"Privacy Policy\" pages, that you want to\nstore in a database but for which you don't want to develop a custom Django\napplication.\n\nA flatpage can use a custom template or a default, systemwide flatpage\ntemplate. It can be associated with one, or multiple, sites.\n\nThe content field may optionally be left blank if you prefer to put your\ncontent in a custom template.\n\nInstallation\n============\n\nTo install the flatpages app, follow these steps:\n\n1. Install the :mod:`sites framework <django.contrib.sites>` by adding\n   ``'django.contrib.sites'`` to your :setting:`INSTALLED_APPS` setting,\n   if it's not already in there.\n\n   Also make sure you've correctly set :setting:`SITE_ID` to the ID of the\n   site the settings file represents. This will usually be ``1`` (i.e.\n   ``SITE_ID = 1``, but if you're using the sites framework to manage\n   multiple sites, it could be the ID of a different site.\n\n2. Add ``'django.contrib.flatpages'`` to your :setting:`INSTALLED_APPS`\n   setting.\n\nThen either:\n\n3. Add an entry in your URLconf. For example::\n\n    urlpatterns = [\n        path('pages/', include('django.contrib.flatpages.urls')),\n    ]\n\nor:\n\n3. Add ``'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware'``\n   to your :setting:`MIDDLEWARE` setting.\n\n4. Run the command :djadmin:`manage.py migrate <migrate>`.\n\n.. currentmodule:: django.contrib.flatpages.middleware\n\nHow it works\n============\n\n``manage.py migrate`` creates two tables in your database: ``django_flatpage``\nand ``django_flatpage_sites``. ``django_flatpage`` is a lookup table that maps\na URL to a title and bunch of text content. ``django_flatpage_sites``\nassociates a flatpage with a site.\n\nUsing the URLconf\n-----------------\n\nThere are several ways to include the flat pages in your URLconf. You can\ndedicate a particular path to flat pages::\n\n    urlpatterns = [\n        path('pages/', include('django.contrib.flatpages.urls')),\n    ]\n\nYou can also set it up as a \"catchall\" pattern. In this case, it is important\nto place the pattern at the end of the other urlpatterns::\n\n    from django.contrib.flatpages import views\n\n    # Your other patterns here\n    urlpatterns += [\n        re_path(r'^(?P<url>.*/)$', views.flatpage),\n    ]\n\n.. warning::\n\n    If you set :setting:`APPEND_SLASH` to ``False``, you must remove the slash\n    in the catchall pattern or flatpages without a trailing slash will not be\n    matched.\n\nAnother common setup is to use flat pages for a limited set of known pages and\nto hard code the urls, so you can reference them with the :ttag:`url` template\ntag::\n\n    from django.contrib.flatpages import views\n\n    urlpatterns += [\n        path('about-us/', views.flatpage, {'url': '/about-us/'}, name='about'),\n        path('license/', views.flatpage, {'url': '/license/'}, name='license'),\n    ]\n\nUsing the middleware\n--------------------\n\nThe :class:`~django.contrib.flatpages.middleware.FlatpageFallbackMiddleware`\ncan do all of the work.\n\n.. class:: FlatpageFallbackMiddleware\n\n    Each time any Django application raises a 404 error, this middleware\n    checks the flatpages database for the requested URL as a last resort.\n    Specifically, it checks for a flatpage with the given URL with a site ID\n    that corresponds to the :setting:`SITE_ID` setting.\n\n    If it finds a match, it follows this algorithm:\n\n    * If the flatpage has a custom template, it loads that template.\n      Otherwise, it loads the template :file:`flatpages/default.html`.\n\n    * It passes that template a single context variable, ``flatpage``,\n      which is the flatpage object. It uses\n      :class:`~django.template.RequestContext` in rendering the\n      template.\n\n    The middleware will only add a trailing slash and redirect (by looking\n    at the :setting:`APPEND_SLASH` setting) if the resulting URL refers to\n    a valid flatpage. Redirects are permanent (301 status code).\n\n    If it doesn't find a match, the request continues to be processed as usual.\n\n    The middleware only gets activated for 404s -- not for 500s or responses\n    of any other status code.\n\n.. admonition:: Flatpages will not apply view middleware\n\n   Because the ``FlatpageFallbackMiddleware`` is applied only after\n   URL resolution has failed and produced a 404, the response it\n   returns will not apply any :ref:`view middleware <view-middleware>`\n   methods. Only requests which are successfully routed to a view via\n   normal URL resolution apply view middleware.\n\nNote that the order of :setting:`MIDDLEWARE` matters. Generally, you can put\n:class:`~django.contrib.flatpages.middleware.FlatpageFallbackMiddleware` at the\nend of the list. This means it will run first when processing the response, and\nensures that any other response-processing middleware see the real flatpage\nresponse rather than the 404.\n\nFor more on middleware, read the :doc:`middleware docs\n</topics/http/middleware>`.\n\n.. admonition:: Ensure that your 404 template works\n\n    Note that the\n    :class:`~django.contrib.flatpages.middleware.FlatpageFallbackMiddleware`\n    only steps in once another view has successfully produced a 404 response.\n    If another view or middleware class attempts to produce a 404 but ends up\n    raising an exception instead, the response will become an HTTP 500\n    (\"Internal Server Error\") and the\n    :class:`~django.contrib.flatpages.middleware.FlatpageFallbackMiddleware`\n    will not attempt to serve a flat page.\n\n.. currentmodule:: django.contrib.flatpages.models\n\nHow to add, change and delete flatpages\n=======================================\n\n.. _flatpages-admin:\n\nVia the admin interface\n-----------------------\n\nIf you've activated the automatic Django admin interface, you should see a\n\"Flatpages\" section on the admin index page. Edit flatpages as you edit any\nother object in the system.\n\nThe ``FlatPage`` model has an ``enable_comments`` field that isn't used by\n``contrib.flatpages``, but that could be useful for your project or third-party\napps. It doesn't appear in the admin interface, but you can add it by\nregistering a custom ``ModelAdmin`` for ``FlatPage``::\n\n    from django.contrib import admin\n    from django.contrib.flatpages.admin import FlatPageAdmin\n    from django.contrib.flatpages.models import FlatPage\n    from django.utils.translation import gettext_lazy as _\n\n    # Define a new FlatPageAdmin\n    class FlatPageAdmin(FlatPageAdmin):\n        fieldsets = (\n            (None, {'fields': ('url', 'title', 'content', 'sites')}),\n            (_('Advanced options'), {\n                'classes': ('collapse',),\n                'fields': (\n                    'enable_comments',\n                    'registration_required',\n                    'template_name',\n                ),\n            }),\n        )\n\n    # Re-register FlatPageAdmin\n    admin.site.unregister(FlatPage)\n    admin.site.register(FlatPage, FlatPageAdmin)\n\nVia the Python API\n------------------\n\n.. class:: FlatPage\n\n    Flatpages are represented by a standard\n    :doc:`Django model </topics/db/models>`,\n    which lives in :source:`django/contrib/flatpages/models.py`. You can access\n    flatpage objects via the :doc:`Django database API </topics/db/queries>`.\n\n.. currentmodule:: django.contrib.flatpages\n\n.. admonition:: Check for duplicate flatpage URLs.\n\n    If you add or modify flatpages via your own code, you will likely want to\n    check for duplicate flatpage URLs within the same site. The flatpage form\n    used in the admin performs this validation check, and can be imported from\n    ``django.contrib.flatpages.forms.FlatpageForm`` and used in your own\n    views.\n\nFlatpage templates\n==================\n\nBy default, flatpages are rendered via the template\n:file:`flatpages/default.html`, but you can override that for a\nparticular flatpage: in the admin, a collapsed fieldset titled\n\"Advanced options\" (clicking will expand it) contains a field for\nspecifying a template name. If you're creating a flat page via the\nPython API you can set the template name as the field ``template_name`` on the\n``FlatPage`` object.\n\nCreating the :file:`flatpages/default.html` template is your responsibility;\nin your template directory, create a :file:`flatpages` directory containing a\nfile :file:`default.html`.\n\nFlatpage templates are passed a single context variable, ``flatpage``,\nwhich is the flatpage object.\n\nHere's a sample :file:`flatpages/default.html` template:\n\n.. code-block:: html+django\n\n    <!DOCTYPE html>\n    <html>\n    <head>\n    <title>{{ flatpage.title }}</title>\n    </head>\n    <body>\n    {{ flatpage.content }}\n    </body>\n    </html>\n\nSince you're already entering raw HTML into the admin page for a flatpage,\nboth ``flatpage.title`` and ``flatpage.content`` are marked as **not**\nrequiring :ref:`automatic HTML escaping <automatic-html-escaping>` in the\ntemplate.\n\nGetting a list of :class:`~django.contrib.flatpages.models.FlatPage` objects in your templates\n==============================================================================================\n\nThe flatpages app provides a template tag that allows you to iterate\nover all of the available flatpages on the :ref:`current site\n<hooking-into-current-site-from-views>`.\n\nLike all custom template tags, you'll need to :ref:`load its custom\ntag library <loading-custom-template-libraries>` before you can use\nit. After loading the library, you can retrieve all current flatpages\nvia the :ttag:`get_flatpages` tag:\n\n.. code-block:: html+django\n\n    {% load flatpages %}\n    {% get_flatpages as flatpages %}\n    <ul>\n        {% for page in flatpages %}\n            <li><a href=\"{{ page.url }}\">{{ page.title }}</a></li>\n        {% endfor %}\n    </ul>\n\n.. templatetag:: get_flatpages\n\nDisplaying ``registration_required`` flatpages\n----------------------------------------------\n\nBy default, the :ttag:`get_flatpages` template tag will only show\nflatpages that are marked ``registration_required = False``. If you\nwant to display registration-protected flatpages, you need to specify\nan authenticated user using a ``for`` clause.\n\nFor example:\n\n.. code-block:: html+django\n\n    {% get_flatpages for someuser as about_pages %}\n\nIf you provide an anonymous user, :ttag:`get_flatpages` will behave\nthe same as if you hadn't provided a user -- i.e., it will only show you\npublic flatpages.\n\nLimiting flatpages by base URL\n------------------------------\n\nAn optional argument, ``starts_with``, can be applied to limit the\nreturned pages to those beginning with a particular base URL. This\nargument may be passed as a string, or as a variable to be resolved\nfrom the context.\n\nFor example:\n\n.. code-block:: html+django\n\n    {% get_flatpages '/about/' as about_pages %}\n    {% get_flatpages about_prefix as about_pages %}\n    {% get_flatpages '/about/' for someuser as about_pages %}\n\nIntegrating with :mod:`django.contrib.sitemaps`\n===============================================\n\n.. currentmodule:: django.contrib.flatpages.sitemaps\n\n.. class:: FlatPageSitemap\n\n    The :class:`sitemaps.FlatPageSitemap\n    <django.contrib.flatpages.sitemaps.FlatPageSitemap>` class looks at all\n    publicly visible :mod:`~django.contrib.flatpages` defined for the current\n    :setting:`SITE_ID` (see the :mod:`sites documentation\n    <django.contrib.sites>`) and creates an entry in the sitemap. These entries\n    include only the :attr:`~django.contrib.sitemaps.Sitemap.location`\n    attribute -- not :attr:`~django.contrib.sitemaps.Sitemap.lastmod`,\n    :attr:`~django.contrib.sitemaps.Sitemap.changefreq` or\n    :attr:`~django.contrib.sitemaps.Sitemap.priority`.\n\nExample\n-------\n\nHere's an example of a URLconf using :class:`FlatPageSitemap`::\n\n    from django.contrib.flatpages.sitemaps import FlatPageSitemap\n    from django.contrib.sitemaps.views import sitemap\n    from django.urls import path\n\n    urlpatterns = [\n        # ...\n\n        # the sitemap\n        path('sitemap.xml', sitemap,\n            {'sitemaps': {'flatpages': FlatPageSitemap}},\n            name='django.contrib.sitemaps.views.sitemap'),\n    ]\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":100,"nodeType":"TextFile","repoName":null,"name":".hgignore","path":"","text":"syntax:glob\n\n*.egg-info\n*.pot\n*.py[co]\n__pycache__\nMANIFEST\ndist/\ndocs/_build/\ndocs/locale/\nnode_modules/\ntests/coverage_html/\ntests/.coverage\nbuild/\ntests/report/\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":101,"nodeType":"TextFile","repoName":null,"name":"messages.txt","path":"docs/ref/contrib","text":"======================\nThe messages framework\n======================\n\n.. module:: django.contrib.messages\n   :synopsis: Provides cookie- and session-based temporary message storage.\n\nQuite commonly in web applications, you need to display a one-time\nnotification message (also known as \"flash message\") to the user after\nprocessing a form or some other types of user input.\n\nFor this, Django provides full support for cookie- and session-based\nmessaging, for both anonymous and authenticated users. The messages framework\nallows you to temporarily store messages in one request and retrieve them for\ndisplay in a subsequent request (usually the next one). Every message is\ntagged with a specific ``level`` that determines its priority (e.g., ``info``,\n``warning``, or ``error``).\n\nEnabling messages\n=================\n\nMessages are implemented through a :doc:`middleware </ref/middleware>`\nclass and corresponding :doc:`context processor </ref/templates/api>`.\n\nThe default ``settings.py`` created by ``django-admin startproject``\nalready contains all the settings required to enable message functionality:\n\n* ``'django.contrib.messages'`` is in :setting:`INSTALLED_APPS`.\n\n* :setting:`MIDDLEWARE` contains\n  ``'django.contrib.sessions.middleware.SessionMiddleware'`` and\n  ``'django.contrib.messages.middleware.MessageMiddleware'``.\n\n  The default :ref:`storage backend <message-storage-backends>` relies on\n  :doc:`sessions </topics/http/sessions>`. That's why ``SessionMiddleware``\n  must be enabled and appear before ``MessageMiddleware`` in\n  :setting:`MIDDLEWARE`.\n\n* The ``'context_processors'`` option of the ``DjangoTemplates`` backend\n  defined in your :setting:`TEMPLATES` setting contains\n  ``'django.contrib.messages.context_processors.messages'``.\n\nIf you don't want to use messages, you can remove\n``'django.contrib.messages'`` from your :setting:`INSTALLED_APPS`, the\n``MessageMiddleware`` line from :setting:`MIDDLEWARE`, and the ``messages``\ncontext processor from :setting:`TEMPLATES`.\n\nConfiguring the message engine\n==============================\n\n.. _message-storage-backends:\n\nStorage backends\n----------------\n\nThe messages framework can use different backends to store temporary messages.\n\nDjango provides three built-in storage classes in\n:mod:`django.contrib.messages`:\n\n.. class:: storage.session.SessionStorage\n\n    This class stores all messages inside of the request's session. Therefore\n    it requires Django's ``contrib.sessions`` application.\n\n.. class:: storage.cookie.CookieStorage\n\n    This class stores the message data in a cookie (signed with a secret hash\n    to prevent manipulation) to persist notifications across requests. Old\n    messages are dropped if the cookie data size would exceed 2048 bytes.\n\n.. class:: storage.fallback.FallbackStorage\n\n    This class first uses ``CookieStorage``, and falls back to using\n    ``SessionStorage`` for the messages that could not fit in a single cookie.\n    It also requires Django's ``contrib.sessions`` application.\n\n    This behavior avoids writing to the session whenever possible. It should\n    provide the best performance in the general case.\n\n:class:`~django.contrib.messages.storage.fallback.FallbackStorage` is the\ndefault storage class. If it isn't suitable to your needs, you can select\nanother storage class by setting :setting:`MESSAGE_STORAGE` to its full import\npath, for example::\n\n    MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'\n\n.. class:: storage.base.BaseStorage\n\nTo write your own storage class, subclass the ``BaseStorage`` class in\n``django.contrib.messages.storage.base`` and implement the ``_get`` and\n``_store`` methods.\n\n.. _message-level:\n\nMessage levels\n--------------\n\nThe messages framework is based on a configurable level architecture similar\nto that of the Python logging module. Message levels allow you to group\nmessages by type so they can be filtered or displayed differently in views and\ntemplates.\n\nThe built-in levels, which can be imported from ``django.contrib.messages``\ndirectly, are:\n\n=========== ========\nConstant    Purpose\n=========== ========\n``DEBUG``   Development-related messages that will be ignored (or removed) in a production deployment\n``INFO``    Informational messages for the user\n``SUCCESS`` An action was successful, e.g. \"Your profile was updated successfully\"\n``WARNING`` A failure did not occur but may be imminent\n``ERROR``   An action was **not** successful or some other failure occurred\n=========== ========\n\nThe :setting:`MESSAGE_LEVEL` setting can be used to change the minimum recorded level\n(or it can be `changed per request`_). Attempts to add messages of a level less\nthan this will be ignored.\n\n.. _`changed per request`: `Changing the minimum recorded level per-request`_\n\nMessage tags\n------------\n\nMessage tags are a string representation of the message level plus any\nextra tags that were added directly in the view (see\n`Adding extra message tags`_ below for more details). Tags are stored in a\nstring and are separated by spaces. Typically, message tags\nare used as CSS classes to customize message style based on message type. By\ndefault, each level has a single tag that's a lowercase version of its own\nconstant:\n\n==============  ===========\nLevel Constant  Tag\n==============  ===========\n``DEBUG``       ``debug``\n``INFO``        ``info``\n``SUCCESS``     ``success``\n``WARNING``     ``warning``\n``ERROR``       ``error``\n==============  ===========\n\nTo change the default tags for a message level (either built-in or custom),\nset the :setting:`MESSAGE_TAGS` setting to a dictionary containing the levels\nyou wish to change. As this extends the default tags, you only need to provide\ntags for the levels you wish to override::\n\n    from django.contrib.messages import constants as messages\n    MESSAGE_TAGS = {\n        messages.INFO: '',\n        50: 'critical',\n    }\n\nUsing messages in views and templates\n=====================================\n\n.. function:: add_message(request, level, message, extra_tags='', fail_silently=False)\n\nAdding a message\n----------------\n\nTo add a message, call::\n\n    from django.contrib import messages\n    messages.add_message(request, messages.INFO, 'Hello world.')\n\nSome shortcut methods provide a standard way to add messages with commonly\nused tags (which are usually represented as HTML classes for the message)::\n\n    messages.debug(request, '%s SQL statements were executed.' % count)\n    messages.info(request, 'Three credits remain in your account.')\n    messages.success(request, 'Profile details updated.')\n    messages.warning(request, 'Your account expires in three days.')\n    messages.error(request, 'Document deleted.')\n\n.. _message-displaying:\n\nDisplaying messages\n-------------------\n.. function:: get_messages(request)\n\n**In your template**, use something like::\n\n    {% if messages %}\n    <ul class=\"messages\">\n        {% for message in messages %}\n        <li{% if message.tags %} class=\"{{ message.tags }}\"{% endif %}>{{ message }}</li>\n        {% endfor %}\n    </ul>\n    {% endif %}\n\nIf you're using the context processor, your template should be rendered with a\n``RequestContext``. Otherwise, ensure ``messages`` is available to\nthe template context.\n\nEven if you know there is only one message, you should still iterate over the\n``messages`` sequence, because otherwise the message storage will not be\ncleared for the next request.\n\nThe context processor also provides a ``DEFAULT_MESSAGE_LEVELS`` variable which\nis a mapping of the message level names to their numeric value::\n\n    {% if messages %}\n    <ul class=\"messages\">\n        {% for message in messages %}\n        <li{% if message.tags %} class=\"{{ message.tags }}\"{% endif %}>\n            {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Important: {% endif %}\n            {{ message }}\n        </li>\n        {% endfor %}\n    </ul>\n    {% endif %}\n\n**Outside of templates**, you can use\n:func:`~django.contrib.messages.get_messages`::\n\n    from django.contrib.messages import get_messages\n\n    storage = get_messages(request)\n    for message in storage:\n        do_something_with_the_message(message)\n\nFor instance, you can fetch all the messages to return them in a\n:ref:`JSONResponseMixin <jsonresponsemixin-example>` instead of a\n:class:`~django.views.generic.base.TemplateResponseMixin`.\n\n:func:`~django.contrib.messages.get_messages` will return an\ninstance of the configured storage backend.\n\n\nThe ``Message`` class\n---------------------\n\n.. class:: storage.base.Message\n\n    When you loop over the list of messages in a template, what you get are\n    instances of the ``Message`` class. They have only a few attributes:\n\n    * ``message``: The actual text of the message.\n\n    * ``level``: An integer describing the type of the message (see the\n      `message levels`_ section above).\n\n    * ``tags``: A string combining all the message's tags (``extra_tags`` and\n      ``level_tag``) separated by spaces.\n\n    * ``extra_tags``: A string containing custom tags for this message,\n      separated by spaces. It's empty by default.\n\n    * ``level_tag``: The string representation of the level. By default, it's\n      the lowercase version of the name of the associated constant, but this\n      can be changed if you need by using the :setting:`MESSAGE_TAGS` setting.\n\nCreating custom message levels\n------------------------------\n\nMessages levels are nothing more than integers, so you can define your own\nlevel constants and use them to create more customized user feedback, e.g.::\n\n    CRITICAL = 50\n\n    def my_view(request):\n        messages.add_message(request, CRITICAL, 'A serious error occurred.')\n\nWhen creating custom message levels you should be careful to avoid overloading\nexisting levels. The values for the built-in levels are:\n\n.. _message-level-constants:\n\n==============  =====\nLevel Constant  Value\n==============  =====\n``DEBUG``       10\n``INFO``        20\n``SUCCESS``     25\n``WARNING``     30\n``ERROR``       40\n==============  =====\n\nIf you need to identify the custom levels in your HTML or CSS, you need to\nprovide a mapping via the :setting:`MESSAGE_TAGS` setting.\n\n.. note::\n   If you are creating a reusable application, it is recommended to use\n   only the built-in `message levels`_ and not rely on any custom levels.\n\nChanging the minimum recorded level per-request\n-----------------------------------------------\n\nThe minimum recorded level can be set per request via the ``set_level``\nmethod::\n\n    from django.contrib import messages\n\n    # Change the messages level to ensure the debug message is added.\n    messages.set_level(request, messages.DEBUG)\n    messages.debug(request, 'Test message...')\n\n    # In another request, record only messages with a level of WARNING and higher\n    messages.set_level(request, messages.WARNING)\n    messages.success(request, 'Your profile was updated.') # ignored\n    messages.warning(request, 'Your account is about to expire.') # recorded\n\n    # Set the messages level back to default.\n    messages.set_level(request, None)\n\nSimilarly, the current effective level can be retrieved with ``get_level``::\n\n    from django.contrib import messages\n    current_level = messages.get_level(request)\n\nFor more information on how the minimum recorded level functions, see\n`Message levels`_ above.\n\nAdding extra message tags\n-------------------------\n\nFor more direct control over message tags, you can optionally provide a string\ncontaining extra tags to any of the add methods::\n\n    messages.add_message(request, messages.INFO, 'Over 9000!', extra_tags='dragonball')\n    messages.error(request, 'Email box full', extra_tags='email')\n\nExtra tags are added before the default tag for that level and are space\nseparated.\n\nFailing silently when the message framework is disabled\n-------------------------------------------------------\n\nIf you're writing a reusable app (or other piece of code) and want to include\nmessaging functionality, but don't want to require your users to enable it\nif they don't want to, you may pass an additional keyword argument\n``fail_silently=True`` to any of the ``add_message`` family of methods. For\nexample::\n\n    messages.add_message(\n        request, messages.SUCCESS, 'Profile details updated.',\n        fail_silently=True,\n    )\n    messages.info(request, 'Hello world.', fail_silently=True)\n\n.. note::\n   Setting ``fail_silently=True`` only hides the ``MessageFailure`` that would\n   otherwise occur when the messages framework disabled and one attempts to\n   use one of the ``add_message`` family of methods. It does not hide failures\n   that may occur for other reasons.\n\nAdding messages in class-based views\n------------------------------------\n\n.. class:: views.SuccessMessageMixin\n\n    Adds a success message attribute to\n    :class:`~django.views.generic.edit.FormView` based classes\n\n    .. method:: get_success_message(cleaned_data)\n\n        ``cleaned_data`` is the cleaned data from the form which is used for\n        string formatting\n\n**Example views.py**::\n\n    from django.contrib.messages.views import SuccessMessageMixin\n    from django.views.generic.edit import CreateView\n    from myapp.models import Author\n\n    class AuthorCreate(SuccessMessageMixin, CreateView):\n        model = Author\n        success_url = '/success/'\n        success_message = \"%(name)s was created successfully\"\n\nThe cleaned data from the ``form`` is available for string interpolation using\nthe ``%(field_name)s`` syntax. For ModelForms, if you need access to fields\nfrom the saved ``object`` override the\n:meth:`~django.contrib.messages.views.SuccessMessageMixin.get_success_message`\nmethod.\n\n**Example views.py for ModelForms**::\n\n    from django.contrib.messages.views import SuccessMessageMixin\n    from django.views.generic.edit import CreateView\n    from myapp.models import ComplicatedModel\n\n    class ComplicatedCreate(SuccessMessageMixin, CreateView):\n        model = ComplicatedModel\n        success_url = '/success/'\n        success_message = \"%(calculated_field)s was created successfully\"\n\n        def get_success_message(self, cleaned_data):\n            return self.success_message % dict(\n                cleaned_data,\n                calculated_field=self.object.calculated_field,\n            )\n\nExpiration of messages\n======================\n\nThe messages are marked to be cleared when the storage instance is iterated\n(and cleared when the response is processed).\n\nTo avoid the messages being cleared, you can set the messages storage to\n``False`` after iterating::\n\n    storage = messages.get_messages(request)\n    for message in storage:\n        do_something_with(message)\n    storage.used = False\n\nBehavior of parallel requests\n=============================\n\nDue to the way cookies (and hence sessions) work, **the behavior of any\nbackends that make use of cookies or sessions is undefined when the same\nclient makes multiple requests that set or get messages in parallel**. For\nexample, if a client initiates a request that creates a message in one window\n(or tab) and then another that fetches any uniterated messages in another\nwindow, before the first window redirects, the message may appear in the\nsecond window instead of the first window where it may be expected.\n\nIn short, when multiple simultaneous requests from the same client are\ninvolved, messages are not guaranteed to be delivered to the same window that\ncreated them nor, in some cases, at all. Note that this is typically not a\nproblem in most applications and will become a non-issue in HTML5, where each\nwindow/tab will have its own browsing context.\n\nSettings\n========\n\nA few :ref:`settings<settings-messages>` give you control over message\nbehavior:\n\n* :setting:`MESSAGE_LEVEL`\n* :setting:`MESSAGE_STORAGE`\n* :setting:`MESSAGE_TAGS`\n\nFor backends that use cookies, the settings for the cookie are taken from\nthe session cookie settings:\n\n* :setting:`SESSION_COOKIE_DOMAIN`\n* :setting:`SESSION_COOKIE_SECURE`\n* :setting:`SESSION_COOKIE_HTTPONLY`\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":102,"nodeType":"TextFile","repoName":null,"name":"staticfiles.txt","path":"docs/ref/contrib","text":"=======================\nThe ``staticfiles`` app\n=======================\n\n.. module:: django.contrib.staticfiles\n   :synopsis: An app for handling static files.\n\n``django.contrib.staticfiles`` collects static files from each of your\napplications (and any other places you specify) into a single location that\ncan easily be served in production.\n\n.. seealso::\n\n    For an introduction to the static files app and some usage examples, see\n    :doc:`/howto/static-files/index`. For guidelines on deploying static files,\n    see :doc:`/howto/static-files/deployment`.\n\n.. _staticfiles-settings:\n\nSettings\n========\n\nSee :ref:`staticfiles settings <settings-staticfiles>` for details on the\nfollowing settings:\n\n* :setting:`STATIC_ROOT`\n* :setting:`STATIC_URL`\n* :setting:`STATICFILES_DIRS`\n* :setting:`STATICFILES_STORAGE`\n* :setting:`STATICFILES_FINDERS`\n\nManagement Commands\n===================\n\n``django.contrib.staticfiles`` exposes three management commands.\n\n``collectstatic``\n-----------------\n\n.. django-admin:: collectstatic\n\nCollects the static files into :setting:`STATIC_ROOT`.\n\nDuplicate file names are by default resolved in a similar way to how template\nresolution works: the file that is first found in one of the specified\nlocations will be used. If you're confused, the :djadmin:`findstatic` command\ncan help show you which files are found.\n\nOn subsequent ``collectstatic`` runs (if ``STATIC_ROOT`` isn't empty), files\nare copied only if they have a modified timestamp greater than the timestamp of\nthe file in ``STATIC_ROOT``. Therefore if you remove an application from\n:setting:`INSTALLED_APPS`, it's a good idea to use the :option:`collectstatic\n--clear` option in order to remove stale static files.\n\nFiles are searched by using the :setting:`enabled finders\n<STATICFILES_FINDERS>`. The default is to look in all locations defined in\n:setting:`STATICFILES_DIRS` and in the ``'static'`` directory of apps\nspecified by the :setting:`INSTALLED_APPS` setting.\n\nThe :djadmin:`collectstatic` management command calls the\n:meth:`~django.contrib.staticfiles.storage.StaticFilesStorage.post_process`\nmethod of the :setting:`STATICFILES_STORAGE` after each run and passes\na list of paths that have been found by the management command. It also\nreceives all command line options of :djadmin:`collectstatic`. This is used\nby the :class:`~django.contrib.staticfiles.storage.ManifestStaticFilesStorage`\nby default.\n\nBy default, collected files receive permissions from\n:setting:`FILE_UPLOAD_PERMISSIONS` and collected directories receive permissions\nfrom :setting:`FILE_UPLOAD_DIRECTORY_PERMISSIONS`. If you would like different\npermissions for these files and/or directories, you can subclass either of the\n:ref:`static files storage classes <staticfiles-storages>` and specify the\n``file_permissions_mode`` and/or ``directory_permissions_mode`` parameters,\nrespectively. For example::\n\n    from django.contrib.staticfiles import storage\n\n    class MyStaticFilesStorage(storage.StaticFilesStorage):\n        def __init__(self, *args, **kwargs):\n            kwargs['file_permissions_mode'] = 0o640\n            kwargs['directory_permissions_mode'] = 0o760\n            super().__init__(*args, **kwargs)\n\nThen set the :setting:`STATICFILES_STORAGE` setting to\n``'path.to.MyStaticFilesStorage'``.\n\nSome commonly used options are:\n\n.. django-admin-option:: --noinput, --no-input\n\n    Do NOT prompt the user for input of any kind.\n\n.. django-admin-option:: --ignore PATTERN, -i PATTERN\n\n    Ignore files, directories, or paths matching this glob-style pattern. Use\n    multiple times to ignore more. When specifying a path, always use forward\n    slashes, even on Windows.\n\n.. django-admin-option:: --dry-run, -n\n\n    Do everything except modify the filesystem.\n\n.. django-admin-option:: --clear, -c\n\n    Clear the existing files before trying to copy or link the original file.\n\n.. django-admin-option:: --link, -l\n\n    Create a symbolic link to each file instead of copying.\n\n.. django-admin-option:: --no-post-process\n\n    Don't call the\n    :meth:`~django.contrib.staticfiles.storage.StaticFilesStorage.post_process`\n    method of the configured :setting:`STATICFILES_STORAGE` storage backend.\n\n.. django-admin-option:: --no-default-ignore\n\n    Don't ignore the common private glob-style patterns ``'CVS'``, ``'.*'``\n    and ``'*~'``.\n\nFor a full list of options, refer to the commands own help by running:\n\n.. console::\n\n   $ python manage.py collectstatic --help\n\n.. _customize-staticfiles-ignore-patterns:\n\nCustomizing the ignored pattern list\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe default ignored pattern list, ``['CVS', '.*', '*~']``, can be customized in\na more persistent way than providing the ``--ignore`` command option at each\n``collectstatic`` invocation. Provide a custom :class:`~django.apps.AppConfig`\nclass, override the ``ignore_patterns`` attribute of this class and replace\n``'django.contrib.staticfiles'`` with that class path in your\n:setting:`INSTALLED_APPS` setting::\n\n    from django.contrib.staticfiles.apps import StaticFilesConfig\n\n    class MyStaticFilesConfig(StaticFilesConfig):\n        ignore_patterns = [...]  # your custom ignore list\n\n``findstatic``\n--------------\n\n.. django-admin:: findstatic staticfile [staticfile ...]\n\nSearches for one or more relative paths with the enabled finders.\n\nFor example:\n\n.. console::\n\n   $ python manage.py findstatic css/base.css admin/js/core.js\n   Found 'css/base.css' here:\n     /home/special.polls.com/core/static/css/base.css\n     /home/polls.com/core/static/css/base.css\n   Found 'admin/js/core.js' here:\n     /home/polls.com/src/django/contrib/admin/media/js/core.js\n\n.. django-admin-option:: findstatic --first\n\nBy default, all matching locations are found. To only return the first match\nfor each relative path, use the ``--first`` option:\n\n.. console::\n\n   $ python manage.py findstatic css/base.css --first\n   Found 'css/base.css' here:\n     /home/special.polls.com/core/static/css/base.css\n\nThis is a debugging aid; it'll show you exactly which static file will be\ncollected for a given path.\n\nBy setting the ``--verbosity`` flag to 0, you can suppress the extra output and\njust get the path names:\n\n.. console::\n\n   $ python manage.py findstatic css/base.css --verbosity 0\n   /home/special.polls.com/core/static/css/base.css\n   /home/polls.com/core/static/css/base.css\n\nOn the other hand, by setting the ``--verbosity`` flag to 2, you can get all\nthe directories which were searched:\n\n.. console::\n\n   $ python manage.py findstatic css/base.css --verbosity 2\n   Found 'css/base.css' here:\n     /home/special.polls.com/core/static/css/base.css\n     /home/polls.com/core/static/css/base.css\n   Looking in the following locations:\n     /home/special.polls.com/core/static\n     /home/polls.com/core/static\n     /some/other/path/static\n\n.. _staticfiles-runserver:\n\n``runserver``\n-------------\n\n.. django-admin:: runserver [addrport]\n    :noindex:\n\nOverrides the core :djadmin:`runserver` command if the ``staticfiles`` app\nis :setting:`installed<INSTALLED_APPS>` and adds automatic serving of static\nfiles. File serving doesn't run through :setting:`MIDDLEWARE`.\n\nThe command adds these options:\n\n.. django-admin-option:: --nostatic\n\nUse the ``--nostatic`` option to disable serving of static files with the\n:doc:`staticfiles </ref/contrib/staticfiles>` app entirely. This option is\nonly available if the :doc:`staticfiles </ref/contrib/staticfiles>` app is\nin your project's :setting:`INSTALLED_APPS` setting.\n\nExample usage:\n\n.. console::\n\n    $ django-admin runserver --nostatic\n\n.. django-admin-option:: --insecure\n\nUse the ``--insecure`` option to force serving of static files with the\n:doc:`staticfiles </ref/contrib/staticfiles>` app even if the :setting:`DEBUG`\nsetting is ``False``. By using this you acknowledge the fact that it's\n**grossly inefficient** and probably **insecure**. This is only intended for\nlocal development, should **never be used in production** and is only\navailable if the :doc:`staticfiles </ref/contrib/staticfiles>` app is\nin your project's :setting:`INSTALLED_APPS` setting.\n\n``--insecure`` doesn't work with :class:`~.storage.ManifestStaticFilesStorage`.\n\nExample usage:\n\n.. console::\n\n    $ django-admin runserver --insecure\n\n.. _staticfiles-storages:\n\nStorages\n========\n\n``StaticFilesStorage``\n----------------------\n\n.. class:: storage.StaticFilesStorage\n\nA subclass of the :class:`~django.core.files.storage.FileSystemStorage`\nstorage backend that uses the :setting:`STATIC_ROOT` setting as the base\nfile system location and the :setting:`STATIC_URL` setting respectively\nas the base URL.\n\n.. method:: storage.StaticFilesStorage.post_process(paths, **options)\n\nIf this method is defined on a storage, it's called by the\n:djadmin:`collectstatic` management command after each run and gets passed the\nlocal storages and paths of found files as a dictionary, as well as the command\nline options. It yields tuples of three values:\n``original_path, processed_path, processed``. The path values are strings and\n``processed`` is a boolean indicating whether or not the value was\npost-processed, or an exception if post-processing failed.\n\nThe :class:`~django.contrib.staticfiles.storage.ManifestStaticFilesStorage`\nuses this behind the scenes to replace the paths with their hashed\ncounterparts and update the cache appropriately.\n\n``ManifestStaticFilesStorage``\n------------------------------\n\n.. class:: storage.ManifestStaticFilesStorage\n\nA subclass of the :class:`~django.contrib.staticfiles.storage.StaticFilesStorage`\nstorage backend which stores the file names it handles by appending the MD5\nhash of the file's content to the filename. For example, the file\n``css/styles.css`` would also be saved as ``css/styles.55e7cbb9ba48.css``.\n\nThe purpose of this storage is to keep serving the old files in case some\npages still refer to those files, e.g. because they are cached by you or\na 3rd party proxy server. Additionally, it's very helpful if you want to\napply `far future Expires headers`_ to the deployed files to speed up the\nload time for subsequent page visits.\n\nThe storage backend automatically replaces the paths found in the saved\nfiles matching other saved files with the path of the cached copy (using\nthe :meth:`~django.contrib.staticfiles.storage.StaticFilesStorage.post_process`\nmethod). The regular expressions used to find those paths\n(``django.contrib.staticfiles.storage.HashedFilesMixin.patterns``)\nby default covers the `@import`_ rule and `url()`_ statement of `Cascading\nStyle Sheets`_. For example, the ``'css/styles.css'`` file with the\ncontent\n\n.. code-block:: css\n\n    @import url(\"../admin/css/base.css\");\n\nwould be replaced by calling the :meth:`~django.core.files.storage.Storage.url`\nmethod of the ``ManifestStaticFilesStorage`` storage backend, ultimately\nsaving a ``'css/styles.55e7cbb9ba48.css'`` file with the following\ncontent:\n\n.. code-block:: css\n\n    @import url(\"../admin/css/base.27e20196a850.css\");\n\n.. attribute:: storage.ManifestStaticFilesStorage.max_post_process_passes\n\nSince static files might reference other static files that need to have their\npaths replaced, multiple passes of replacing paths may be needed until the file\nhashes converge. To prevent an infinite loop due to hashes not converging (for\nexample, if ``'foo.css'`` references ``'bar.css'`` which references\n``'foo.css'``) there is a maximum number of passes before post-processing is\nabandoned. In cases with a large number of references, a higher number of\npasses might be needed. Increase the maximum number of passes by subclassing\n``ManifestStaticFilesStorage`` and setting the ``max_post_process_passes``\nattribute. It defaults to 5.\n\nTo enable the ``ManifestStaticFilesStorage`` you have to make sure the\nfollowing requirements are met:\n\n* the :setting:`STATICFILES_STORAGE` setting is set to\n  ``'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'``\n* the :setting:`DEBUG` setting is set to ``False``\n* you've collected all your static files by using the\n  :djadmin:`collectstatic` management command\n\nSince creating the MD5 hash can be a performance burden to your website\nduring runtime, ``staticfiles`` will automatically store the mapping with\nhashed names for all processed files in a file called ``staticfiles.json``.\nThis happens once when you run the :djadmin:`collectstatic` management\ncommand.\n\n.. attribute:: storage.ManifestStaticFilesStorage.manifest_strict\n\nIf a file isn't found in the ``staticfiles.json`` manifest at runtime, a\n``ValueError`` is raised. This behavior can be disabled by subclassing\n``ManifestStaticFilesStorage`` and setting the ``manifest_strict`` attribute to\n``False`` -- nonexistent paths will remain unchanged.\n\nDue to the requirement of running :djadmin:`collectstatic`, this storage\ntypically shouldn't be used when running tests as ``collectstatic`` isn't run\nas part of the normal test setup. During testing, ensure that the\n:setting:`STATICFILES_STORAGE` setting is set to something else like\n``'django.contrib.staticfiles.storage.StaticFilesStorage'`` (the default).\n\n.. method:: storage.ManifestStaticFilesStorage.file_hash(name, content=None)\n\nThe method that is used when creating the hashed name of a file.\nNeeds to return a hash for the given file name and content.\nBy default it calculates a MD5 hash from the content's chunks as\nmentioned above. Feel free to override this method to use your own\nhashing algorithm.\n\n.. _`far future Expires headers`: https://developer.yahoo.com/performance/rules.html#expires\n.. _`@import`: https://www.w3.org/TR/CSS2/cascade.html#at-import\n.. _`url()`: https://www.w3.org/TR/CSS2/syndata.html#uri\n.. _`Cascading Style Sheets`: https://www.w3.org/Style/CSS/\n\n``ManifestFilesMixin``\n----------------------\n\n.. class:: storage.ManifestFilesMixin\n\nUse this mixin with a custom storage to append the MD5 hash of the file's\ncontent to the filename as :class:`~storage.ManifestStaticFilesStorage` does.\n\nFinders Module\n==============\n\n``staticfiles`` finders has a ``searched_locations`` attribute which is a list\nof directory paths in which the finders searched. Example usage::\n\n    from django.contrib.staticfiles import finders\n\n    result = finders.find('css/base.css')\n    searched_locations = finders.searched_locations\n\nOther Helpers\n=============\n\nThere are a few other helpers outside of the\n:mod:`staticfiles <django.contrib.staticfiles>` app to work with static\nfiles:\n\n- The :func:`django.template.context_processors.static` context processor\n  which adds :setting:`STATIC_URL` to every template context rendered\n  with :class:`~django.template.RequestContext` contexts.\n\n- The builtin template tag :ttag:`static` which takes a path and urljoins it\n  with the static prefix :setting:`STATIC_URL`. If\n  ``django.contrib.staticfiles`` is installed, the tag uses the ``url()``\n  method of the :setting:`STATICFILES_STORAGE` instead.\n\n- The builtin template tag :ttag:`get_static_prefix` which populates a\n  template variable with the static prefix :setting:`STATIC_URL` to be\n  used as a variable or directly.\n\n- The similar template tag :ttag:`get_media_prefix` which works like\n  :ttag:`get_static_prefix` but uses :setting:`MEDIA_URL`.\n\n.. _staticfiles-development-view:\n\nStatic file development view\n----------------------------\n\n.. currentmodule:: django.contrib.staticfiles\n\nThe static files tools are mostly designed to help with getting static files\nsuccessfully deployed into production. This usually means a separate,\ndedicated static file server, which is a lot of overhead to mess with when\ndeveloping locally. Thus, the ``staticfiles`` app ships with a\n**quick and dirty helper view** that you can use to serve files locally in\ndevelopment.\n\n.. function:: views.serve(request, path)\n\nThis view function serves static files in development.\n\n.. warning::\n\n    This view will only work if :setting:`DEBUG` is ``True``.\n\n    That's because this view is **grossly inefficient** and probably\n    **insecure**. This is only intended for local development, and should\n    **never be used in production**.\n\n.. note::\n\n    To guess the served files' content types, this view relies on the\n    :py:mod:`mimetypes` module from the Python standard library, which itself\n    relies on the underlying platform's map files. If you find that this view\n    doesn't return proper content types for certain files, it is most likely\n    that the platform's map files need to be updated. This can be achieved, for\n    example, by installing or updating the ``mailcap`` package on a Red Hat\n    distribution, or ``mime-support`` on a Debian distribution.\n\nThis view is automatically enabled by :djadmin:`runserver` (with a\n:setting:`DEBUG` setting set to ``True``). To use the view with a different\nlocal development server, add the following snippet to the end of your\nprimary URL configuration::\n\n   from django.conf import settings\n   from django.contrib.staticfiles import views\n   from django.urls import re_path\n\n   if settings.DEBUG:\n       urlpatterns += [\n           re_path(r'^static/(?P<path>.*)$', views.serve),\n       ]\n\nNote, the beginning of the pattern (``r'^static/'``) should be your\n:setting:`STATIC_URL` setting.\n\nSince this is a bit finicky, there's also a helper function that'll do this for\nyou:\n\n.. function:: urls.staticfiles_urlpatterns()\n\nThis will return the proper URL pattern for serving static files to your\nalready defined pattern list. Use it like this::\n\n   from django.contrib.staticfiles.urls import staticfiles_urlpatterns\n\n   # ... the rest of your URLconf here ...\n\n   urlpatterns += staticfiles_urlpatterns()\n\nThis will inspect your :setting:`STATIC_URL` setting and wire up the view\nto serve static files accordingly. Don't forget to set the\n:setting:`STATICFILES_DIRS` setting appropriately to let\n``django.contrib.staticfiles`` know where to look for files in addition to\nfiles in app directories.\n\n.. warning::\n\n    This helper function will only work if :setting:`DEBUG` is ``True``\n    and your :setting:`STATIC_URL` setting is neither empty nor a full\n    URL such as ``http://static.example.com/``.\n\n    That's because this view is **grossly inefficient** and probably\n    **insecure**. This is only intended for local development, and should\n    **never be used in production**.\n\nSpecialized test case to support 'live testing'\n-----------------------------------------------\n\n.. class:: testing.StaticLiveServerTestCase\n\nThis unittest TestCase subclass extends :class:`django.test.LiveServerTestCase`.\n\nJust like its parent, you can use it to write tests that involve running the\ncode under test and consuming it with testing tools through HTTP (e.g. Selenium,\nPhantomJS, etc.), because of which it's needed that the static assets are also\npublished.\n\nBut given the fact that it makes use of the\n:func:`django.contrib.staticfiles.views.serve` view described above, it can\ntransparently overlay at test execution-time the assets provided by the\n``staticfiles`` finders. This means you don't need to run\n:djadmin:`collectstatic` before or as a part of your tests setup.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":103,"nodeType":"TextFile","repoName":null,"name":"sitemaps.txt","path":"docs/ref/contrib","text":"=====================\nThe sitemap framework\n=====================\n\n.. module:: django.contrib.sitemaps\n   :synopsis: A framework for generating Google sitemap XML files.\n\nDjango comes with a high-level sitemap-generating framework to create sitemap_\nXML files.\n\n.. _sitemap: https://www.sitemaps.org/\n\nOverview\n========\n\nA sitemap is an XML file on your website that tells search-engine indexers how\nfrequently your pages change and how \"important\" certain pages are in relation\nto other pages on your site. This information helps search engines index your\nsite.\n\nThe Django sitemap framework automates the creation of this XML file by letting\nyou express this information in Python code.\n\nIt works much like Django's :doc:`syndication framework\n</ref/contrib/syndication>`. To create a sitemap, write a\n:class:`~django.contrib.sitemaps.Sitemap` class and point to it in your\n:doc:`URLconf </topics/http/urls>`.\n\nInstallation\n============\n\nTo install the sitemap app, follow these steps:\n\n#. Add ``'django.contrib.sitemaps'`` to your :setting:`INSTALLED_APPS` setting.\n\n#. Make sure your :setting:`TEMPLATES` setting contains a ``DjangoTemplates``\n   backend whose ``APP_DIRS`` options is set to ``True``. It's in there by\n   default, so you'll only need to change this if you've changed that setting.\n\n#. Make sure you've installed the :mod:`sites framework<django.contrib.sites>`.\n\n(Note: The sitemap application doesn't install any database tables. The only\nreason it needs to go into :setting:`INSTALLED_APPS` is so that the\n:func:`~django.template.loaders.app_directories.Loader` template\nloader can find the default templates.)\n\nInitialization\n==============\n\n.. function:: views.sitemap(request, sitemaps, section=None, template_name='sitemap.xml', content_type='application/xml')\n\nTo activate sitemap generation on your Django site, add this line to your\n:doc:`URLconf </topics/http/urls>`::\n\n    from django.contrib.sitemaps.views import sitemap\n\n    path('sitemap.xml', sitemap, {'sitemaps': sitemaps},\n         name='django.contrib.sitemaps.views.sitemap')\n\nThis tells Django to build a sitemap when a client accesses :file:`/sitemap.xml`.\n\nThe name of the sitemap file is not important, but the location is. Search\nengines will only index links in your sitemap for the current URL level and\nbelow. For instance, if :file:`sitemap.xml` lives in your root directory, it may\nreference any URL in your site. However, if your sitemap lives at\n:file:`/content/sitemap.xml`, it may only reference URLs that begin with\n:file:`/content/`.\n\nThe sitemap view takes an extra, required argument: ``{'sitemaps': sitemaps}``.\n``sitemaps`` should be a dictionary that maps a short section label (e.g.,\n``blog`` or ``news``) to its :class:`~django.contrib.sitemaps.Sitemap` class\n(e.g., ``BlogSitemap`` or ``NewsSitemap``). It may also map to an *instance* of\na :class:`~django.contrib.sitemaps.Sitemap` class (e.g.,\n``BlogSitemap(some_var)``).\n\n``Sitemap`` classes\n===================\n\nA :class:`~django.contrib.sitemaps.Sitemap` class is a Python class that\nrepresents a \"section\" of entries in your sitemap. For example, one\n:class:`~django.contrib.sitemaps.Sitemap` class could represent all the entries\nof your Weblog, while another could represent all of the events in your events\ncalendar.\n\nIn the simplest case, all these sections get lumped together into one\n:file:`sitemap.xml`, but it's also possible to use the framework to generate a\nsitemap index that references individual sitemap files, one per section. (See\n`Creating a sitemap index`_ below.)\n\n:class:`~django.contrib.sitemaps.Sitemap` classes must subclass\n``django.contrib.sitemaps.Sitemap``. They can live anywhere in your codebase.\n\nAn example\n==========\n\nLet's assume you have a blog system, with an ``Entry`` model, and you want your\nsitemap to include all the links to your individual blog entries. Here's how\nyour sitemap class might look::\n\n    from django.contrib.sitemaps import Sitemap\n    from blog.models import Entry\n\n    class BlogSitemap(Sitemap):\n        changefreq = \"never\"\n        priority = 0.5\n\n        def items(self):\n            return Entry.objects.filter(is_draft=False)\n\n        def lastmod(self, obj):\n            return obj.pub_date\n\nNote:\n\n* :attr:`~Sitemap.changefreq` and :attr:`~Sitemap.priority` are class\n  attributes corresponding to ``<changefreq>`` and ``<priority>`` elements,\n  respectively. They can be made callable as functions, as\n  :attr:`~Sitemap.lastmod` was in the example.\n* :attr:`~Sitemap.items()` is a method that returns a :term:`sequence` or\n  ``QuerySet`` of objects. The objects returned will get passed to any callable\n  methods corresponding to a sitemap property (:attr:`~Sitemap.location`,\n  :attr:`~Sitemap.lastmod`, :attr:`~Sitemap.changefreq`, and\n  :attr:`~Sitemap.priority`).\n* :attr:`~Sitemap.lastmod` should return a :class:`~datetime.datetime`.\n* There is no :attr:`~Sitemap.location` method in this example, but you\n  can provide it in order to specify the URL for your object. By default,\n  :attr:`~Sitemap.location()` calls ``get_absolute_url()`` on each object\n  and returns the result.\n\n``Sitemap`` class reference\n===========================\n\n.. class:: Sitemap\n\n    A ``Sitemap`` class can define the following methods/attributes:\n\n    .. attribute:: Sitemap.items\n\n        **Required.** A method that returns a :term:`sequence` or ``QuerySet``\n        of objects. The framework doesn't care what *type* of objects they are;\n        all that matters is that these objects get passed to the\n        :attr:`~Sitemap.location()`, :attr:`~Sitemap.lastmod()`,\n        :attr:`~Sitemap.changefreq()` and :attr:`~Sitemap.priority()` methods.\n\n    .. attribute:: Sitemap.location\n\n        **Optional.** Either a method or attribute.\n\n        If it's a method, it should return the absolute path for a given object\n        as returned by :attr:`~Sitemap.items()`.\n\n        If it's an attribute, its value should be a string representing an\n        absolute path to use for *every* object returned by\n        :attr:`~Sitemap.items()`.\n\n        In both cases, \"absolute path\" means a URL that doesn't include the\n        protocol or domain. Examples:\n\n        * Good: :file:`'/foo/bar/'`\n        * Bad: :file:`'example.com/foo/bar/'`\n        * Bad: :file:`'https://example.com/foo/bar/'`\n\n        If :attr:`~Sitemap.location` isn't provided, the framework will call\n        the ``get_absolute_url()`` method on each object as returned by\n        :attr:`~Sitemap.items()`.\n\n        To specify a protocol other than ``'http'``, use\n        :attr:`~Sitemap.protocol`.\n\n    .. attribute:: Sitemap.lastmod\n\n        **Optional.** Either a method or attribute.\n\n        If it's a method, it should take one argument -- an object as returned\n        by :attr:`~Sitemap.items()` -- and return that object's last-modified\n        date/time as a :class:`~datetime.datetime`.\n\n        If it's an attribute, its value should be a :class:`~datetime.datetime`\n        representing the last-modified date/time for *every* object returned by\n        :attr:`~Sitemap.items()`.\n\n        If all items in a sitemap have a :attr:`~Sitemap.lastmod`, the sitemap\n        generated by :func:`views.sitemap` will have a ``Last-Modified``\n        header equal to the latest ``lastmod``. You can activate the\n        :class:`~django.middleware.http.ConditionalGetMiddleware` to make\n        Django respond appropriately to requests with an ``If-Modified-Since``\n        header which will prevent sending the sitemap if it hasn't changed.\n\n    .. attribute:: Sitemap.changefreq\n\n        **Optional.** Either a method or attribute.\n\n        If it's a method, it should take one argument -- an object as returned\n        by :attr:`~Sitemap.items()` -- and return that object's change\n        frequency as a string.\n\n        If it's an attribute, its value should be a string representing the\n        change frequency of *every* object returned by :attr:`~Sitemap.items()`.\n\n        Possible values for :attr:`~Sitemap.changefreq`, whether you use a\n        method or attribute, are:\n\n        * ``'always'``\n        * ``'hourly'``\n        * ``'daily'``\n        * ``'weekly'``\n        * ``'monthly'``\n        * ``'yearly'``\n        * ``'never'``\n\n    .. attribute:: Sitemap.priority\n\n        **Optional.** Either a method or attribute.\n\n        If it's a method, it should take one argument -- an object as returned\n        by :attr:`~Sitemap.items()` -- and return that object's priority as\n        either a string or float.\n\n        If it's an attribute, its value should be either a string or float\n        representing the priority of *every* object returned by\n        :attr:`~Sitemap.items()`.\n\n        Example values for :attr:`~Sitemap.priority`: ``0.4``, ``1.0``. The\n        default priority of a page is ``0.5``. See the `sitemaps.org\n        documentation`_ for more.\n\n        .. _sitemaps.org documentation: https://www.sitemaps.org/protocol.html#prioritydef\n\n    .. attribute:: Sitemap.protocol\n\n        **Optional.**\n\n        This attribute defines the protocol (``'http'`` or ``'https'``) of the\n        URLs in the sitemap. If it isn't set, the protocol with which the\n        sitemap was requested is used. If the sitemap is built outside the\n        context of a request, the default is ``'http'``.\n\n    .. attribute:: Sitemap.limit\n\n        **Optional.**\n\n        This attribute defines the maximum number of URLs included on each page\n        of the sitemap. Its value should not exceed the default value of\n        ``50000``, which is the upper limit allowed in the `Sitemaps protocol\n        <https://www.sitemaps.org/protocol.html#index>`_.\n\n    .. attribute:: Sitemap.i18n\n\n        **Optional.**\n\n        A boolean attribute that defines if the URLs of this sitemap should\n        be generated using all of your :setting:`LANGUAGES`. The default is\n        ``False``.\n\nShortcuts\n=========\n\nThe sitemap framework provides a convenience class for a common case:\n\n.. class:: GenericSitemap(info_dict, priority=None, changefreq=None, protocol=None)\n\n    The :class:`django.contrib.sitemaps.GenericSitemap` class allows you to\n    create a sitemap by passing it a dictionary which has to contain at least\n    a ``queryset`` entry. This queryset will be used to generate the items\n    of the sitemap. It may also have a ``date_field`` entry that\n    specifies a date field for objects retrieved from the ``queryset``.\n    This will be used for the :attr:`~Sitemap.lastmod` attribute in the\n    generated sitemap.\n\n    The :attr:`~Sitemap.priority`, :attr:`~Sitemap.changefreq`,\n    and :attr:`~Sitemap.protocol` keyword arguments allow specifying these\n    attributes for all URLs.\n\nExample\n-------\n\nHere's an example of a :doc:`URLconf </topics/http/urls>` using\n:class:`GenericSitemap`::\n\n    from django.contrib.sitemaps import GenericSitemap\n    from django.contrib.sitemaps.views import sitemap\n    from django.urls import path\n    from blog.models import Entry\n\n    info_dict = {\n        'queryset': Entry.objects.all(),\n        'date_field': 'pub_date',\n    }\n\n    urlpatterns = [\n        # some generic view using info_dict\n        # ...\n\n        # the sitemap\n        path('sitemap.xml', sitemap,\n             {'sitemaps': {'blog': GenericSitemap(info_dict, priority=0.6)}},\n             name='django.contrib.sitemaps.views.sitemap'),\n    ]\n\n.. _URLconf: ../url_dispatch/\n\nSitemap for static views\n========================\n\nOften you want the search engine crawlers to index views which are neither\nobject detail pages nor flatpages. The solution is to explicitly list URL\nnames for these views in ``items`` and call :func:`~django.urls.reverse` in\nthe ``location`` method of the sitemap. For example::\n\n    # sitemaps.py\n    from django.contrib import sitemaps\n    from django.urls import reverse\n\n    class StaticViewSitemap(sitemaps.Sitemap):\n        priority = 0.5\n        changefreq = 'daily'\n\n        def items(self):\n            return ['main', 'about', 'license']\n\n        def location(self, item):\n            return reverse(item)\n\n    # urls.py\n    from django.contrib.sitemaps.views import sitemap\n    from django.urls import path\n\n    from .sitemaps import StaticViewSitemap\n    from . import views\n\n    sitemaps = {\n        'static': StaticViewSitemap,\n    }\n\n    urlpatterns = [\n        path('', views.main, name='main'),\n        path('about/', views.about, name='about'),\n        path('license/', views.license, name='license'),\n        # ...\n        path('sitemap.xml', sitemap, {'sitemaps': sitemaps},\n             name='django.contrib.sitemaps.views.sitemap')\n    ]\n\n\nCreating a sitemap index\n========================\n\n.. function:: views.index(request, sitemaps, template_name='sitemap_index.xml', content_type='application/xml', sitemap_url_name='django.contrib.sitemaps.views.sitemap')\n\nThe sitemap framework also has the ability to create a sitemap index that\nreferences individual sitemap files, one per each section defined in your\n``sitemaps`` dictionary. The only differences in usage are:\n\n* You use two views in your URLconf: :func:`django.contrib.sitemaps.views.index`\n  and :func:`django.contrib.sitemaps.views.sitemap`.\n* The :func:`django.contrib.sitemaps.views.sitemap` view should take a\n  ``section`` keyword argument.\n\nHere's what the relevant URLconf lines would look like for the example above::\n\n    from django.contrib.sitemaps import views\n\n    urlpatterns = [\n        path('sitemap.xml', views.index, {'sitemaps': sitemaps}),\n        path('sitemap-<section>.xml', views.sitemap, {'sitemaps': sitemaps},\n             name='django.contrib.sitemaps.views.sitemap'),\n    ]\n\nThis will automatically generate a :file:`sitemap.xml` file that references\nboth :file:`sitemap-flatpages.xml` and :file:`sitemap-blog.xml`. The\n:class:`~django.contrib.sitemaps.Sitemap` classes and the ``sitemaps``\ndict don't change at all.\n\nYou should create an index file if one of your sitemaps has more than 50,000\nURLs. In this case, Django will automatically paginate the sitemap, and the\nindex will reflect that.\n\nIf you're not using the vanilla sitemap view -- for example, if it's wrapped\nwith a caching decorator -- you must name your sitemap view and pass\n``sitemap_url_name`` to the index view::\n\n    from django.contrib.sitemaps import views as sitemaps_views\n    from django.views.decorators.cache import cache_page\n\n    urlpatterns = [\n        path('sitemap.xml',\n             cache_page(86400)(sitemaps_views.index),\n             {'sitemaps': sitemaps, 'sitemap_url_name': 'sitemaps'}),\n        path('sitemap-<section>.xml',\n             cache_page(86400)(sitemaps_views.sitemap),\n             {'sitemaps': sitemaps}, name='sitemaps'),\n    ]\n\n\nTemplate customization\n======================\n\nIf you wish to use a different template for each sitemap or sitemap index\navailable on your site, you may specify it by passing a ``template_name``\nparameter to the ``sitemap`` and ``index`` views via the URLconf::\n\n    from django.contrib.sitemaps import views\n\n    urlpatterns = [\n        path('custom-sitemap.xml', views.index, {\n            'sitemaps': sitemaps,\n            'template_name': 'custom_sitemap.html'\n        }),\n        path('custom-sitemap-<section>.xml', views.sitemap, {\n            'sitemaps': sitemaps,\n            'template_name': 'custom_sitemap.html'\n        }, name='django.contrib.sitemaps.views.sitemap'),\n    ]\n\n\nThese views return :class:`~django.template.response.TemplateResponse`\ninstances which allow you to easily customize the response data before\nrendering. For more details, see the :doc:`TemplateResponse documentation\n</ref/template-response>`.\n\nContext variables\n-----------------\n\nWhen customizing the templates for the\n:func:`~django.contrib.sitemaps.views.index` and\n:func:`~django.contrib.sitemaps.views.sitemap` views, you can rely on the\nfollowing context variables.\n\nIndex\n-----\n\nThe variable ``sitemaps`` is a list of absolute URLs to each of the sitemaps.\n\nSitemap\n-------\n\nThe variable ``urlset`` is a list of URLs that should appear in the\nsitemap. Each URL exposes attributes as defined in the\n:class:`~django.contrib.sitemaps.Sitemap` class:\n\n- ``changefreq``\n- ``item``\n- ``lastmod``\n- ``location``\n- ``priority``\n\nThe ``item`` attribute has been added for each URL to allow more flexible\ncustomization of the templates, such as `Google news sitemaps`_. Assuming\nSitemap's :attr:`~Sitemap.items()` would return a list of items with\n``publication_data`` and a ``tags`` field something like this would\ngenerate a Google News compatible sitemap:\n\n.. code-block:: xml+django\n\n    <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n    <urlset\n      xmlns=\"https://www.sitemaps.org/schemas/sitemap/0.9\"\n      xmlns:news=\"http://www.google.com/schemas/sitemap-news/0.9\">\n    {% spaceless %}\n    {% for url in urlset %}\n      <url>\n        <loc>{{ url.location }}</loc>\n        {% if url.lastmod %}<lastmod>{{ url.lastmod|date:\"Y-m-d\" }}</lastmod>{% endif %}\n        {% if url.changefreq %}<changefreq>{{ url.changefreq }}</changefreq>{% endif %}\n        {% if url.priority %}<priority>{{ url.priority }}</priority>{% endif %}\n        <news:news>\n          {% if url.item.publication_date %}<news:publication_date>{{ url.item.publication_date|date:\"Y-m-d\" }}</news:publication_date>{% endif %}\n          {% if url.item.tags %}<news:keywords>{{ url.item.tags }}</news:keywords>{% endif %}\n        </news:news>\n       </url>\n    {% endfor %}\n    {% endspaceless %}\n    </urlset>\n\n.. _`Google news sitemaps`: https://support.google.com/news/publisher/answer/74288?hl=en\n\nPinging Google\n==============\n\nYou may want to \"ping\" Google when your sitemap changes, to let it know to\nreindex your site. The sitemaps framework provides a function to do just\nthat: :func:`django.contrib.sitemaps.ping_google()`.\n\n.. function:: ping_google(sitemap_url=None, ping_url=PING_URL, sitemap_uses_https=True)\n\n    ``ping_google`` takes these optional arguments:\n\n    * ``sitemap_url`` - The absolute path to your site's sitemap (e.g.,\n      :file:`'/sitemap.xml'`). If this argument isn't provided, ``ping_google``\n      will attempt to figure out your sitemap by performing a reverse lookup in\n      your URLconf.\n\n    * ``ping_url`` - Defaults to Google's Ping Tool:\n      https://www.google.com/webmasters/tools/ping.\n\n    * ``sitemap_uses_https`` - Set to ``False`` if your site uses ``http``\n      rather than ``https``.\n\n    :func:`ping_google` raises the exception\n    ``django.contrib.sitemaps.SitemapNotFound`` if it cannot determine your\n    sitemap URL.\n\n.. admonition:: Register with Google first!\n\n    The :func:`ping_google` command only works if you have registered your\n    site with `Google Webmaster Tools`_.\n\n.. _`Google Webmaster Tools`: https://www.google.com/webmasters/tools/\n\nOne useful way to call :func:`ping_google` is from a model's ``save()``\nmethod::\n\n    from django.contrib.sitemaps import ping_google\n\n    class Entry(models.Model):\n        # ...\n        def save(self, force_insert=False, force_update=False):\n            super().save(force_insert, force_update)\n            try:\n                ping_google()\n            except Exception:\n                # Bare 'except' because we could get a variety\n                # of HTTP-related exceptions.\n                pass\n\nA more efficient solution, however, would be to call :func:`ping_google` from a\ncron script, or some other scheduled task. The function makes an HTTP request\nto Google's servers, so you may not want to introduce that network overhead\neach time you call ``save()``.\n\nPinging Google via ``manage.py``\n--------------------------------\n\n.. django-admin:: ping_google [sitemap_url]\n\nOnce the sitemaps application is added to your project, you may also\nping Google using the ``ping_google`` management command::\n\n    python manage.py ping_google [/sitemap.xml]\n\n.. django-admin-option:: --sitemap-uses-http\n\nUse this option if your sitemap uses ``http`` rather than ``https``.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":104,"nodeType":"TextFile","repoName":null,"name":"options.txt","path":"docs/ref/models","text":"======================\nModel ``Meta`` options\n======================\n\nThis document explains all the possible :ref:`metadata options\n<meta-options>` that you can give your model in its internal\n``class Meta``.\n\nAvailable ``Meta`` options\n==========================\n\n.. currentmodule:: django.db.models\n\n``abstract``\n------------\n\n.. attribute:: Options.abstract\n\n    If ``abstract = True``, this model will be an\n    :ref:`abstract base class <abstract-base-classes>`.\n\n``app_label``\n-------------\n\n.. attribute:: Options.app_label\n\n    If a model is defined outside of an application in\n    :setting:`INSTALLED_APPS`, it must declare which app it belongs to::\n\n        app_label = 'myapp'\n\n    If you want to represent a model with the format ``app_label.object_name``\n    or ``app_label.model_name`` you can use ``model._meta.label``\n    or ``model._meta.label_lower`` respectively.\n\n``base_manager_name``\n---------------------\n\n.. attribute:: Options.base_manager_name\n\n    The attribute name of the manager, for example, ``'objects'``, to use for\n    the model's :attr:`~django.db.models.Model._base_manager`.\n\n``db_table``\n------------\n\n.. attribute:: Options.db_table\n\n    The name of the database table to use for the model::\n\n        db_table = 'music_album'\n\n.. _table-names:\n\nTable names\n~~~~~~~~~~~\n\nTo save you time, Django automatically derives the name of the database table\nfrom the name of your model class and the app that contains it. A model's\ndatabase table name is constructed by joining the model's \"app label\" -- the\nname you used in :djadmin:`manage.py startapp <startapp>` -- to the model's\nclass name, with an underscore between them.\n\nFor example, if you have an app ``bookstore`` (as created by\n``manage.py startapp bookstore``), a model defined as ``class Book`` will have\na database table named ``bookstore_book``.\n\nTo override the database table name, use the ``db_table`` parameter in\n``class Meta``.\n\nIf your database table name is an SQL reserved word, or contains characters that\naren't allowed in Python variable names -- notably, the hyphen -- that's OK.\nDjango quotes column and table names behind the scenes.\n\n.. admonition:: Use lowercase table names for MariaDB and MySQL\n\n    It is strongly advised that you use lowercase table names when you override\n    the table name via ``db_table``, particularly if you are using the MySQL\n    backend. See the :ref:`MySQL notes <mysql-notes>` for more details.\n\n.. admonition:: Table name quoting for Oracle\n\n   In order to meet the 30-char limitation Oracle has on table names,\n   and match the usual conventions for Oracle databases, Django may shorten\n   table names and turn them all-uppercase. To prevent such transformations,\n   use a quoted name as the value for ``db_table``::\n\n       db_table = '\"name_left_in_lowercase\"'\n\n   Such quoted names can also be used with Django's other supported database\n   backends; except for Oracle, however, the quotes have no effect. See the\n   :ref:`Oracle notes <oracle-notes>` for more details.\n\n``db_tablespace``\n-----------------\n\n.. attribute:: Options.db_tablespace\n\n    The name of the :doc:`database tablespace </topics/db/tablespaces>` to use\n    for this model. The default is the project's :setting:`DEFAULT_TABLESPACE`\n    setting, if set. If the backend doesn't support tablespaces, this option is\n    ignored.\n\n``default_manager_name``\n------------------------\n\n.. attribute:: Options.default_manager_name\n\n    The name of the manager to use for the model's\n    :attr:`~django.db.models.Model._default_manager`.\n\n``default_related_name``\n------------------------\n\n.. attribute:: Options.default_related_name\n\n    The name that will be used by default for the relation from a related object\n    back to this one. The default is ``<model_name>_set``.\n\n    This option also sets :attr:`~ForeignKey.related_query_name`.\n\n    As the reverse name for a field should be unique, be careful if you intend\n    to subclass your model. To work around name collisions, part of the name\n    should contain ``'%(app_label)s'`` and ``'%(model_name)s'``, which are\n    replaced respectively by the name of the application the model is in,\n    and the name of the model, both lowercased. See the paragraph on\n    :ref:`related names for abstract models <abstract-related-name>`.\n\n``get_latest_by``\n-----------------\n\n.. attribute:: Options.get_latest_by\n\n    The name of a field or a list of field names in the model, typically\n    :class:`DateField`, :class:`DateTimeField`, or :class:`IntegerField`. This\n    specifies the default field(s) to use in your model :class:`Manager`’s\n    :meth:`~django.db.models.query.QuerySet.latest` and\n    :meth:`~django.db.models.query.QuerySet.earliest` methods.\n\n    Example::\n\n        # Latest by ascending order_date.\n        get_latest_by = \"order_date\"\n\n        # Latest by priority descending, order_date ascending.\n        get_latest_by = ['-priority', 'order_date']\n\n    See the :meth:`~django.db.models.query.QuerySet.latest` docs for more.\n\n``managed``\n-----------\n\n.. attribute:: Options.managed\n\n    Defaults to ``True``, meaning Django will create the appropriate database\n    tables in :djadmin:`migrate` or as part of migrations and remove them as\n    part of a :djadmin:`flush` management command. That is, Django\n    *manages* the database tables' lifecycles.\n\n    If ``False``, no database table creation or deletion operations will be\n    performed for this model. This is useful if the model represents an existing\n    table or a database view that has been created by some other means. This is\n    the *only* difference when ``managed=False``. All other aspects of\n    model handling are exactly the same as normal. This includes\n\n    #. Adding an automatic primary key field to the model if you don't\n       declare it.  To avoid confusion for later code readers, it's\n       recommended to specify all the columns from the database table you\n       are modeling when using unmanaged models.\n\n    #. If a model with ``managed=False`` contains a\n       :class:`~django.db.models.ManyToManyField` that points to another\n       unmanaged model, then the intermediate table for the many-to-many\n       join will also not be created. However, the intermediary table\n       between one managed and one unmanaged model *will* be created.\n\n       If you need to change this default behavior, create the intermediary\n       table as an explicit model (with ``managed`` set as needed) and use\n       the :attr:`ManyToManyField.through` attribute to make the relation\n       use your custom model.\n\n    For tests involving models with ``managed=False``, it's up to you to ensure\n    the correct tables are created as part of the test setup.\n\n    If you're interested in changing the Python-level behavior of a model class,\n    you *could* use ``managed=False`` and create a copy of an existing model.\n    However, there's a better approach for that situation: :ref:`proxy-models`.\n\n``order_with_respect_to``\n-------------------------\n\n.. attribute:: Options.order_with_respect_to\n\n    Makes this object orderable with respect to the given field, usually a\n    ``ForeignKey``. This can be used to make related objects orderable with\n    respect to a parent object. For example, if an ``Answer`` relates to a\n    ``Question`` object, and a question has more than one answer, and the order\n    of answers matters, you'd do this::\n\n        from django.db import models\n\n        class Question(models.Model):\n            text = models.TextField()\n            # ...\n\n        class Answer(models.Model):\n            question = models.ForeignKey(Question, on_delete=models.CASCADE)\n            # ...\n\n            class Meta:\n                order_with_respect_to = 'question'\n\n    When ``order_with_respect_to`` is set, two additional methods are provided to\n    retrieve and to set the order of the related objects: ``get_RELATED_order()``\n    and ``set_RELATED_order()``, where ``RELATED`` is the lowercased model name. For\n    example, assuming that a ``Question`` object has multiple related ``Answer``\n    objects, the list returned contains the primary keys of the related ``Answer``\n    objects::\n\n        >>> question = Question.objects.get(id=1)\n        >>> question.get_answer_order()\n        [1, 2, 3]\n\n    The order of a ``Question`` object's related ``Answer`` objects can be set by\n    passing in a list of ``Answer`` primary keys::\n\n        >>> question.set_answer_order([3, 1, 2])\n\n    The related objects also get two methods, ``get_next_in_order()`` and\n    ``get_previous_in_order()``, which can be used to access those objects in their\n    proper order. Assuming the ``Answer`` objects are ordered by ``id``::\n\n        >>> answer = Answer.objects.get(id=2)\n        >>> answer.get_next_in_order()\n        <Answer: 3>\n        >>> answer.get_previous_in_order()\n        <Answer: 1>\n\n.. admonition:: ``order_with_respect_to`` implicitly sets the ``ordering`` option\n\n    Internally, ``order_with_respect_to`` adds an additional field/database\n    column named ``_order`` and sets the model's :attr:`~Options.ordering`\n    option to this field. Consequently, ``order_with_respect_to`` and\n    ``ordering`` cannot be used together, and the ordering added by\n    ``order_with_respect_to`` will apply whenever you obtain a list of objects\n    of this model.\n\n.. admonition:: Changing ``order_with_respect_to``\n\n    Because ``order_with_respect_to`` adds a new database column, be sure to\n    make and apply the appropriate migrations if you add or change\n    ``order_with_respect_to`` after your initial :djadmin:`migrate`.\n\n``ordering``\n------------\n\n.. attribute:: Options.ordering\n\n    The default ordering for the object, for use when obtaining lists of objects::\n\n        ordering = ['-order_date']\n\n    This is a tuple or list of strings and/or query expressions. Each string is\n    a field name with an optional \"-\" prefix, which indicates descending order.\n    Fields without a leading \"-\" will be ordered ascending. Use the string \"?\"\n    to order randomly.\n\n    For example, to order by a ``pub_date`` field ascending, use this::\n\n        ordering = ['pub_date']\n\n    To order by ``pub_date`` descending, use this::\n\n        ordering = ['-pub_date']\n\n    To order by ``pub_date`` descending, then by ``author`` ascending, use this::\n\n        ordering = ['-pub_date', 'author']\n\n    You can also use :doc:`query expressions </ref/models/expressions>`. To\n    order by ``author`` ascending and make null values sort last, use this::\n\n        from django.db.models import F\n\n        ordering = [F('author').asc(nulls_last=True)]\n\n.. warning::\n\n    Ordering is not a free operation. Each field you add to the ordering\n    incurs a cost to your database. Each foreign key you add will\n    implicitly include all of its default orderings as well.\n\n    If a query doesn't have an ordering specified, results are returned from\n    the database in an unspecified order. A particular ordering is guaranteed\n    only when ordering by a set of fields that uniquely identify each object in\n    the results. For example, if a ``name`` field isn't unique, ordering by it\n    won't guarantee objects with the same name always appear in the same order.\n\n``permissions``\n---------------\n\n.. attribute:: Options.permissions\n\n    Extra permissions to enter into the permissions table when creating this object.\n    Add, change, delete, and view permissions are automatically created for each\n    model. This example specifies an extra permission, ``can_deliver_pizzas``::\n\n        permissions = [('can_deliver_pizzas', 'Can deliver pizzas')]\n\n    This is a list or tuple of 2-tuples in the format ``(permission_code,\n    human_readable_permission_name)``.\n\n``default_permissions``\n-----------------------\n\n.. attribute:: Options.default_permissions\n\n    Defaults to ``('add', 'change', 'delete', 'view')``. You may customize this\n    list, for example, by setting this to an empty list if your app doesn't\n    require any of the default permissions. It must be specified on the model\n    before the model is created by :djadmin:`migrate` in order to prevent any\n    omitted permissions from being created.\n\n``proxy``\n---------\n\n.. attribute:: Options.proxy\n\n    If ``proxy = True``, a model which subclasses another model will be treated as\n    a :ref:`proxy model <proxy-models>`.\n\n``required_db_features``\n------------------------\n\n.. attribute:: Options.required_db_features\n\n    List of database features that the current connection should have so that\n    the model is considered during the migration phase. For example, if you set\n    this list to ``['gis_enabled']``, the model will only be synchronized on\n    GIS-enabled databases. It's also useful to skip some models when testing\n    with several database backends. Avoid relations between models that may or\n    may not be created as the ORM doesn't handle this.\n\n``required_db_vendor``\n----------------------\n\n.. attribute:: Options.required_db_vendor\n\n    Name of a supported database vendor that this model is specific to. Current\n    built-in vendor names are: ``sqlite``, ``postgresql``, ``mysql``,\n    ``oracle``. If this attribute is not empty and the current connection vendor\n    doesn't match it, the model will not be synchronized.\n\n``select_on_save``\n------------------\n\n.. attribute:: Options.select_on_save\n\n    Determines if Django will use the pre-1.6\n    :meth:`django.db.models.Model.save()` algorithm. The old algorithm\n    uses ``SELECT`` to determine if there is an existing row to be updated.\n    The new algorithm tries an ``UPDATE`` directly. In some rare cases the\n    ``UPDATE`` of an existing row isn't visible to Django. An example is the\n    PostgreSQL ``ON UPDATE`` trigger which returns ``NULL``. In such cases the\n    new algorithm will end up doing an ``INSERT`` even when a row exists in\n    the database.\n\n    Usually there is no need to set this attribute. The default is\n    ``False``.\n\n    See :meth:`django.db.models.Model.save()` for more about the old and\n    new saving algorithm.\n\n``indexes``\n-----------\n\n.. attribute:: Options.indexes\n\n    A list of :doc:`indexes </ref/models/indexes>` that you want to define on\n    the model::\n\n        from django.db import models\n\n        class Customer(models.Model):\n            first_name = models.CharField(max_length=100)\n            last_name = models.CharField(max_length=100)\n\n            class Meta:\n                indexes = [\n                    models.Index(fields=['last_name', 'first_name']),\n                    models.Index(fields=['first_name'], name='first_name_idx'),\n                ]\n\n``unique_together``\n-------------------\n\n.. attribute:: Options.unique_together\n\n    .. admonition:: Use :class:`.UniqueConstraint` with the :attr:`~Options.constraints` option instead.\n\n        :class:`.UniqueConstraint` provides more functionality than\n        ``unique_together``. ``unique_together`` may be deprecated in the\n        future.\n\n    Sets of field names that, taken together, must be unique::\n\n        unique_together = [['driver', 'restaurant']]\n\n    This is a list of lists that must be unique when considered together.\n    It's used in the Django admin and is enforced at the database level (i.e., the\n    appropriate ``UNIQUE`` statements are included in the ``CREATE TABLE``\n    statement).\n\n    For convenience, ``unique_together`` can be a single list when dealing with\n    a single set of fields::\n\n        unique_together = ['driver', 'restaurant']\n\n    A :class:`~django.db.models.ManyToManyField` cannot be included in\n    unique_together. (It's not clear what that would even mean!) If you\n    need to validate uniqueness related to a\n    :class:`~django.db.models.ManyToManyField`, try using a signal or\n    an explicit :attr:`through <ManyToManyField.through>` model.\n\n    The ``ValidationError`` raised during model validation when the constraint\n    is violated has the ``unique_together`` error code.\n\n``index_together``\n------------------\n\n.. attribute:: Options.index_together\n\n    .. admonition:: Use the :attr:`~Options.indexes` option instead.\n\n        The newer :attr:`~Options.indexes` option provides more functionality\n        than ``index_together``. ``index_together`` may be deprecated in the\n        future.\n\n    Sets of field names that, taken together, are indexed::\n\n        index_together = [\n            [\"pub_date\", \"deadline\"],\n        ]\n\n    This list of fields will be indexed together (i.e. the appropriate\n    ``CREATE INDEX`` statement will be issued.)\n\n    For convenience, ``index_together`` can be a single list when dealing with a single\n    set of fields::\n\n        index_together = [\"pub_date\", \"deadline\"]\n\n``constraints``\n---------------\n\n.. attribute:: Options.constraints\n\n    A list of :doc:`constraints </ref/models/constraints>` that you want to\n    define on the model::\n\n        from django.db import models\n\n        class Customer(models.Model):\n            age = models.IntegerField()\n\n            class Meta:\n                constraints = [\n                    models.CheckConstraint(check=models.Q(age__gte=18), name='age_gte_18'),\n                ]\n\n``verbose_name``\n----------------\n\n.. attribute:: Options.verbose_name\n\n    A human-readable name for the object, singular::\n\n        verbose_name = \"pizza\"\n\n    If this isn't given, Django will use a munged version of the class name:\n    ``CamelCase`` becomes ``camel case``.\n\n``verbose_name_plural``\n-----------------------\n\n.. attribute:: Options.verbose_name_plural\n\n    The plural name for the object::\n\n        verbose_name_plural = \"stories\"\n\n    If this isn't given, Django will use :attr:`~Options.verbose_name` + ``\"s\"``.\n\nRead-only ``Meta`` attributes\n=============================\n\n``label``\n---------\n\n.. attribute:: Options.label\n\n    Representation of the object, returns ``app_label.object_name``, e.g.\n    ``'polls.Question'``.\n\n``label_lower``\n---------------\n\n.. attribute:: Options.label_lower\n\n    Representation of the model, returns ``app_label.model_name``, e.g.\n    ``'polls.question'``.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":105,"nodeType":"TextFile","repoName":null,"name":"auth.txt","path":"docs/ref/contrib","text":"=======================\n``django.contrib.auth``\n=======================\n\nThis document provides API reference material for the components of Django's\nauthentication system. For more details on the usage of these components or\nhow to customize authentication and authorization see the :doc:`authentication\ntopic guide </topics/auth/index>`.\n\n.. currentmodule:: django.contrib.auth\n\n``User`` model\n==============\n\n.. class:: models.User\n\nFields\n------\n\n.. class:: models.User\n    :noindex:\n\n    :class:`~django.contrib.auth.models.User` objects have the following\n    fields:\n\n    .. attribute:: username\n\n        Required. 150 characters or fewer. Usernames may contain alphanumeric,\n        ``_``, ``@``, ``+``, ``.`` and ``-`` characters.\n\n        The ``max_length`` should be sufficient for many use cases. If you need\n        a longer length, please use a :ref:`custom user model\n        <specifying-custom-user-model>`. If you use MySQL with the ``utf8mb4``\n        encoding (recommended for proper Unicode support), specify at most\n        ``max_length=191`` because MySQL can only create unique indexes with\n        191 characters in that case by default.\n\n    .. attribute:: first_name\n\n        Optional (:attr:`blank=True <django.db.models.Field.blank>`). 150\n        characters or fewer.\n\n        .. versionchanged:: 3.1\n\n            The ``max_length`` increased from 30 to 150 characters.\n\n    .. attribute:: last_name\n\n        Optional (:attr:`blank=True <django.db.models.Field.blank>`). 150\n        characters or fewer.\n\n    .. attribute:: email\n\n        Optional (:attr:`blank=True <django.db.models.Field.blank>`). Email\n        address.\n\n    .. attribute:: password\n\n        Required. A hash of, and metadata about, the password. (Django doesn't\n        store the raw password.) Raw passwords can be arbitrarily long and can\n        contain any character. See the :doc:`password documentation\n        </topics/auth/passwords>`.\n\n    .. attribute:: groups\n\n        Many-to-many relationship to :class:`~django.contrib.auth.models.Group`\n\n    .. attribute:: user_permissions\n\n        Many-to-many relationship to :class:`~django.contrib.auth.models.Permission`\n\n    .. attribute:: is_staff\n\n        Boolean. Designates whether this user can access the admin site.\n\n    .. attribute:: is_active\n\n        Boolean. Designates whether this user account should be considered\n        active. We recommend that you set this flag to ``False`` instead of\n        deleting accounts; that way, if your applications have any foreign keys\n        to users, the foreign keys won't break.\n\n        This doesn't necessarily control whether or not the user can log in.\n        Authentication backends aren't required to check for the ``is_active``\n        flag but the default backend\n        (:class:`~django.contrib.auth.backends.ModelBackend`) and the\n        :class:`~django.contrib.auth.backends.RemoteUserBackend` do. You can\n        use :class:`~django.contrib.auth.backends.AllowAllUsersModelBackend`\n        or :class:`~django.contrib.auth.backends.AllowAllUsersRemoteUserBackend`\n        if you want to allow inactive users to login. In this case, you'll also\n        want to customize the\n        :class:`~django.contrib.auth.forms.AuthenticationForm` used by the\n        :class:`~django.contrib.auth.views.LoginView` as it rejects inactive\n        users. Be aware that the permission-checking methods such as\n        :meth:`~django.contrib.auth.models.User.has_perm` and the\n        authentication in the Django admin all return ``False`` for inactive\n        users.\n\n    .. attribute:: is_superuser\n\n        Boolean. Designates that this user has all permissions without\n        explicitly assigning them.\n\n    .. attribute:: last_login\n\n        A datetime of the user's last login.\n\n    .. attribute:: date_joined\n\n        A datetime designating when the account was created. Is set to the\n        current date/time by default when the account is created.\n\nAttributes\n----------\n\n.. class:: models.User\n    :noindex:\n\n    .. attribute:: is_authenticated\n\n        Read-only attribute which is always ``True`` (as opposed to\n        ``AnonymousUser.is_authenticated`` which is always ``False``). This is\n        a way to tell if the user has been authenticated. This does not imply\n        any permissions and doesn't check if the user is active or has a valid\n        session. Even though normally you will check this attribute on\n        ``request.user`` to find out whether it has been populated by the\n        :class:`~django.contrib.auth.middleware.AuthenticationMiddleware`\n        (representing the currently logged-in user), you should know this\n        attribute is ``True`` for any :class:`~models.User` instance.\n\n    .. attribute:: is_anonymous\n\n        Read-only attribute which is always ``False``. This is a way of\n        differentiating :class:`~models.User` and :class:`~models.AnonymousUser`\n        objects. Generally, you should prefer using\n        :attr:`~django.contrib.auth.models.User.is_authenticated` to this\n        attribute.\n\nMethods\n-------\n\n.. class:: models.User\n    :noindex:\n\n    .. method:: get_username()\n\n        Returns the username for the user. Since the ``User`` model can be\n        swapped out, you should use this method instead of referencing the\n        username attribute directly.\n\n    .. method:: get_full_name()\n\n        Returns the :attr:`~django.contrib.auth.models.User.first_name` plus\n        the :attr:`~django.contrib.auth.models.User.last_name`, with a space in\n        between.\n\n    .. method:: get_short_name()\n\n        Returns the :attr:`~django.contrib.auth.models.User.first_name`.\n\n    .. method:: set_password(raw_password)\n\n        Sets the user's password to the given raw string, taking care of the\n        password hashing. Doesn't save the\n        :class:`~django.contrib.auth.models.User` object.\n\n        When the ``raw_password`` is ``None``, the password will be set to an\n        unusable password, as if\n        :meth:`~django.contrib.auth.models.User.set_unusable_password()`\n        were used.\n\n    .. method:: check_password(raw_password)\n\n        Returns ``True`` if the given raw string is the correct password for\n        the user. (This takes care of the password hashing in making the\n        comparison.)\n\n    .. method:: set_unusable_password()\n\n        Marks the user as having no password set.  This isn't the same as\n        having a blank string for a password.\n        :meth:`~django.contrib.auth.models.User.check_password()` for this user\n        will never return ``True``. Doesn't save the\n        :class:`~django.contrib.auth.models.User` object.\n\n        You may need this if authentication for your application takes place\n        against an existing external source such as an LDAP directory.\n\n    .. method:: has_usable_password()\n\n        Returns ``False`` if\n        :meth:`~django.contrib.auth.models.User.set_unusable_password()` has\n        been called for this user.\n\n    .. method:: get_user_permissions(obj=None)\n\n        Returns a set of permission strings that the user has directly.\n\n        If ``obj`` is passed in, only returns the user permissions for this\n        specific object.\n\n    .. method:: get_group_permissions(obj=None)\n\n        Returns a set of permission strings that the user has, through their\n        groups.\n\n        If ``obj`` is passed in, only returns the group permissions for\n        this specific object.\n\n    .. method:: get_all_permissions(obj=None)\n\n        Returns a set of permission strings that the user has, both through\n        group and user permissions.\n\n        If ``obj`` is passed in, only returns the permissions for this\n        specific object.\n\n    .. method:: has_perm(perm, obj=None)\n\n        Returns ``True`` if the user has the specified permission, where perm\n        is in the format ``\"<app label>.<permission codename>\"``. (see\n        documentation on :ref:`permissions <topic-authorization>`). If the user is\n        inactive, this method will always return ``False``. For an active\n        superuser, this method will always return ``True``.\n\n        If ``obj`` is passed in, this method won't check for a permission for\n        the model, but for this specific object.\n\n    .. method:: has_perms(perm_list, obj=None)\n\n        Returns ``True`` if the user has each of the specified permissions,\n        where each perm is in the format\n        ``\"<app label>.<permission codename>\"``. If the user is inactive,\n        this method will always return ``False``. For an active superuser, this\n        method will always return ``True``.\n\n        If ``obj`` is passed in, this method won't check for permissions for\n        the model, but for the specific object.\n\n    .. method:: has_module_perms(package_name)\n\n        Returns ``True`` if the user has any permissions in the given package\n        (the Django app label). If the user is inactive, this method will\n        always return ``False``. For an active superuser, this method will\n        always return ``True``.\n\n    .. method:: email_user(subject, message, from_email=None, **kwargs)\n\n        Sends an email to the user. If ``from_email`` is ``None``, Django uses\n        the :setting:`DEFAULT_FROM_EMAIL`. Any ``**kwargs`` are passed to the\n        underlying :meth:`~django.core.mail.send_mail()` call.\n\nManager methods\n---------------\n\n.. class:: models.UserManager\n\n    The :class:`~django.contrib.auth.models.User` model has a custom manager\n    that has the following helper methods (in addition to the methods provided\n    by :class:`~django.contrib.auth.models.BaseUserManager`):\n\n    .. method:: create_user(username, email=None, password=None, **extra_fields)\n\n        Creates, saves and returns a :class:`~django.contrib.auth.models.User`.\n\n        The :attr:`~django.contrib.auth.models.User.username` and\n        :attr:`~django.contrib.auth.models.User.password` are set as given. The\n        domain portion of :attr:`~django.contrib.auth.models.User.email` is\n        automatically converted to lowercase, and the returned\n        :class:`~django.contrib.auth.models.User` object will have\n        :attr:`~django.contrib.auth.models.User.is_active` set to ``True``.\n\n        If no password is provided,\n        :meth:`~django.contrib.auth.models.User.set_unusable_password()` will\n        be called.\n\n        The ``extra_fields`` keyword arguments are passed through to the\n        :class:`~django.contrib.auth.models.User`’s ``__init__`` method to\n        allow setting arbitrary fields on a :ref:`custom user model\n        <auth-custom-user>`.\n\n        See :ref:`Creating users <topics-auth-creating-users>` for example usage.\n\n    .. method:: create_superuser(username, email=None, password=None, **extra_fields)\n\n        Same as :meth:`create_user`, but sets :attr:`~models.User.is_staff` and\n        :attr:`~models.User.is_superuser` to ``True``.\n\n    .. method:: with_perm(perm, is_active=True, include_superusers=True, backend=None, obj=None)\n\n        Returns users that have the given permission ``perm`` either in the\n        ``\"<app label>.<permission codename>\"`` format or as a\n        :class:`~django.contrib.auth.models.Permission` instance. Returns an\n        empty queryset if no users who have the ``perm`` found.\n\n        If ``is_active`` is ``True`` (default), returns only active users, or\n        if ``False``, returns only inactive users. Use ``None`` to return all\n        users irrespective of active state.\n\n        If ``include_superusers`` is ``True`` (default), the result will\n        include superusers.\n\n        If ``backend`` is passed in and it's defined in\n        :setting:`AUTHENTICATION_BACKENDS`, then this method will use it.\n        Otherwise, it will use the ``backend`` in\n        :setting:`AUTHENTICATION_BACKENDS`, if there is only one, or raise an\n        exception.\n\n``AnonymousUser`` object\n========================\n\n.. class:: models.AnonymousUser\n\n    :class:`django.contrib.auth.models.AnonymousUser` is a class that\n    implements the :class:`django.contrib.auth.models.User` interface, with\n    these differences:\n\n    * :ref:`id <automatic-primary-key-fields>` is always ``None``.\n    * :attr:`~django.contrib.auth.models.User.username` is always the empty\n      string.\n    * :meth:`~django.contrib.auth.models.User.get_username()` always returns\n      the empty string.\n    * :attr:`~django.contrib.auth.models.User.is_anonymous` is ``True``\n      instead of ``False``.\n    * :attr:`~django.contrib.auth.models.User.is_authenticated` is\n      ``False`` instead of ``True``.\n    * :attr:`~django.contrib.auth.models.User.is_staff` and\n      :attr:`~django.contrib.auth.models.User.is_superuser` are always\n      ``False``.\n    * :attr:`~django.contrib.auth.models.User.is_active` is always ``False``.\n    * :attr:`~django.contrib.auth.models.User.groups` and\n      :attr:`~django.contrib.auth.models.User.user_permissions` are always\n      empty.\n    * :meth:`~django.contrib.auth.models.User.set_password()`,\n      :meth:`~django.contrib.auth.models.User.check_password()`,\n      :meth:`~django.db.models.Model.save` and\n      :meth:`~django.db.models.Model.delete()` raise :exc:`NotImplementedError`.\n\nIn practice, you probably won't need to use\n:class:`~django.contrib.auth.models.AnonymousUser` objects on your own, but\nthey're used by Web requests, as explained in the next section.\n\n``Permission`` model\n====================\n\n.. class:: models.Permission\n\nFields\n------\n\n:class:`~django.contrib.auth.models.Permission` objects have the following\nfields:\n\n.. class:: models.Permission\n    :noindex:\n\n    .. attribute:: name\n\n        Required. 255 characters or fewer. Example: ``'Can vote'``.\n\n    .. attribute:: content_type\n\n        Required. A reference to the ``django_content_type`` database table,\n        which contains a record for each installed model.\n\n    .. attribute:: codename\n\n        Required. 100 characters or fewer. Example: ``'can_vote'``.\n\nMethods\n-------\n\n:class:`~django.contrib.auth.models.Permission` objects have the standard\ndata-access methods like any other :doc:`Django model </ref/models/instances>`.\n\n``Group`` model\n===============\n\n.. class:: models.Group\n\nFields\n------\n\n:class:`~django.contrib.auth.models.Group` objects have the following fields:\n\n.. class:: models.Group\n    :noindex:\n\n    .. attribute:: name\n\n        Required. 150 characters or fewer. Any characters are permitted.\n        Example: ``'Awesome Users'``.\n\n    .. attribute:: permissions\n\n        Many-to-many field to :class:`~django.contrib.auth.models.Permission`::\n\n            group.permissions.set([permission_list])\n            group.permissions.add(permission, permission, ...)\n            group.permissions.remove(permission, permission, ...)\n            group.permissions.clear()\n\nValidators\n==========\n\n.. class:: validators.ASCIIUsernameValidator\n\n    A field validator allowing only ASCII letters and numbers, in addition to\n    ``@``, ``.``, ``+``, ``-``, and ``_``.\n\n.. class:: validators.UnicodeUsernameValidator\n\n    A field validator allowing Unicode characters, in addition to ``@``, ``.``,\n    ``+``, ``-``, and ``_``. The default validator for ``User.username``.\n\n.. _topics-auth-signals:\n\nLogin and logout signals\n========================\n\n.. module:: django.contrib.auth.signals\n\nThe auth framework uses the following :doc:`signals </topics/signals>` that\ncan be used for notification when a user logs in or out.\n\n.. function:: user_logged_in\n\n    Sent when a user logs in successfully.\n\n    Arguments sent with this signal:\n\n    ``sender``\n        The class of the user that just logged in.\n\n    ``request``\n        The current :class:`~django.http.HttpRequest` instance.\n\n    ``user``\n        The user instance that just logged in.\n\n.. function:: user_logged_out\n\n    Sent when the logout method is called.\n\n    ``sender``\n        As above: the class of the user that just logged out or ``None``\n        if the user was not authenticated.\n\n    ``request``\n        The current :class:`~django.http.HttpRequest` instance.\n\n    ``user``\n        The user instance that just logged out or ``None`` if the\n        user was not authenticated.\n\n.. function:: user_login_failed\n\n    Sent when the user failed to login successfully\n\n    ``sender``\n        The name of the module used for authentication.\n\n    ``credentials``\n        A dictionary of keyword arguments containing the user credentials that were\n        passed to :func:`~django.contrib.auth.authenticate()` or your own custom\n        authentication backend. Credentials matching a set of 'sensitive' patterns,\n        (including password) will not be sent in the clear as part of the signal.\n\n    ``request``\n        The :class:`~django.http.HttpRequest` object, if one was provided to\n        :func:`~django.contrib.auth.authenticate`.\n\n.. _authentication-backends-reference:\n\nAuthentication backends\n=======================\n\n.. module:: django.contrib.auth.backends\n   :synopsis: Django's built-in authentication backend classes.\n\nThis section details the authentication backends that come with Django. For\ninformation on how to use them and how to write your own authentication\nbackends, see the :ref:`Other authentication sources section\n<authentication-backends>` of the :doc:`User authentication guide\n</topics/auth/index>`.\n\nAvailable authentication backends\n---------------------------------\n\nThe following backends are available in :mod:`django.contrib.auth.backends`:\n\n.. class:: BaseBackend\n\n    A base class that provides default implementations for all required\n    methods. By default, it will reject any user and provide no permissions.\n\n    .. method:: get_user_permissions(user_obj, obj=None)\n\n        Returns an empty set.\n\n    .. method:: get_group_permissions(user_obj, obj=None)\n\n        Returns an empty set.\n\n    .. method:: get_all_permissions(user_obj, obj=None)\n\n        Uses :meth:`get_user_permissions` and :meth:`get_group_permissions` to\n        get the set of permission strings the ``user_obj`` has.\n\n    .. method:: has_perm(user_obj, perm, obj=None)\n\n        Uses :meth:`get_all_permissions` to check if ``user_obj`` has the\n        permission string ``perm``.\n\n.. class:: ModelBackend\n\n    This is the default authentication backend used by Django.  It\n    authenticates using credentials consisting of a user identifier and\n    password.  For Django's default user model, the user identifier is the\n    username, for custom user models it is the field specified by\n    USERNAME_FIELD (see :doc:`Customizing Users and authentication\n    </topics/auth/customizing>`).\n\n    It also handles the default permissions model as defined for\n    :class:`~django.contrib.auth.models.User` and\n    :class:`~django.contrib.auth.models.PermissionsMixin`.\n\n    :meth:`has_perm`, :meth:`get_all_permissions`, :meth:`get_user_permissions`,\n    and :meth:`get_group_permissions` allow an object to be passed as a\n    parameter for object-specific permissions, but this backend does not\n    implement them other than returning an empty set of permissions if\n    ``obj is not None``.\n\n    :meth:`with_perm` also allows an object to be passed as a parameter, but\n    unlike others methods it returns an empty queryset if ``obj is not None``.\n\n    .. method:: authenticate(request, username=None, password=None, **kwargs)\n\n        Tries to authenticate ``username`` with ``password`` by calling\n        :meth:`User.check_password\n        <django.contrib.auth.models.User.check_password>`. If no ``username``\n        is provided, it tries to fetch a username from ``kwargs`` using the\n        key :attr:`CustomUser.USERNAME_FIELD\n        <django.contrib.auth.models.CustomUser.USERNAME_FIELD>`. Returns an\n        authenticated user or ``None``.\n\n        ``request`` is an :class:`~django.http.HttpRequest` and may be ``None``\n        if it wasn't provided to :func:`~django.contrib.auth.authenticate`\n        (which passes it on to the backend).\n\n    .. method:: get_user_permissions(user_obj, obj=None)\n\n        Returns the set of permission strings the ``user_obj`` has from their\n        own user permissions. Returns an empty set if\n        :attr:`~django.contrib.auth.models.AbstractBaseUser.is_anonymous` or\n        :attr:`~django.contrib.auth.models.CustomUser.is_active` is ``False``.\n\n    .. method:: get_group_permissions(user_obj, obj=None)\n\n        Returns the set of permission strings the ``user_obj`` has from the\n        permissions of the groups they belong. Returns an empty set if\n        :attr:`~django.contrib.auth.models.AbstractBaseUser.is_anonymous` or\n        :attr:`~django.contrib.auth.models.CustomUser.is_active`  is ``False``.\n\n    .. method:: get_all_permissions(user_obj, obj=None)\n\n        Returns the set of permission strings the ``user_obj`` has, including both\n        user permissions and group permissions. Returns an empty set if\n        :attr:`~django.contrib.auth.models.AbstractBaseUser.is_anonymous` or\n        :attr:`~django.contrib.auth.models.CustomUser.is_active` is ``False``.\n\n    .. method:: has_perm(user_obj, perm, obj=None)\n\n        Uses :meth:`get_all_permissions` to check if ``user_obj`` has the\n        permission string ``perm``. Returns ``False`` if the user is not\n        :attr:`~django.contrib.auth.models.CustomUser.is_active`.\n\n    .. method:: has_module_perms(user_obj, app_label)\n\n        Returns whether the ``user_obj`` has any permissions on the app\n        ``app_label``.\n\n    .. method:: user_can_authenticate()\n\n        Returns whether the user is allowed to authenticate. To match the\n        behavior of :class:`~django.contrib.auth.forms.AuthenticationForm`\n        which :meth:`prohibits inactive users from logging in\n        <django.contrib.auth.forms.AuthenticationForm.confirm_login_allowed>`,\n        this method returns ``False`` for users with :attr:`is_active=False\n        <django.contrib.auth.models.User.is_active>`. Custom user models that\n        don't have an :attr:`~django.contrib.auth.models.CustomUser.is_active`\n        field are allowed.\n\n    .. method:: with_perm(perm, is_active=True, include_superusers=True, obj=None)\n\n        Returns all active users who have the permission ``perm`` either in\n        the form of ``\"<app label>.<permission codename>\"`` or a\n        :class:`~django.contrib.auth.models.Permission` instance. Returns an\n        empty queryset if no users who have the ``perm`` found.\n\n        If ``is_active`` is ``True`` (default), returns only active users, or\n        if ``False``, returns only inactive users. Use ``None`` to return all\n        users irrespective of active state.\n\n        If ``include_superusers`` is ``True`` (default), the result will\n        include superusers.\n\n.. class:: AllowAllUsersModelBackend\n\n    Same as :class:`ModelBackend` except that it doesn't reject inactive users\n    because :meth:`~ModelBackend.user_can_authenticate` always returns ``True``.\n\n    When using this backend, you'll likely want to customize the\n    :class:`~django.contrib.auth.forms.AuthenticationForm` used by the\n    :class:`~django.contrib.auth.views.LoginView` by overriding the\n    :meth:`~django.contrib.auth.forms.AuthenticationForm.confirm_login_allowed`\n    method as it rejects inactive users.\n\n.. class:: RemoteUserBackend\n\n    Use this backend to take advantage of external-to-Django-handled\n    authentication.  It authenticates using usernames passed in\n    :attr:`request.META['REMOTE_USER'] <django.http.HttpRequest.META>`.  See\n    the :doc:`Authenticating against REMOTE_USER </howto/auth-remote-user>`\n    documentation.\n\n    If you need more control, you can create your own authentication backend\n    that inherits from this class and override these attributes or methods:\n\n    .. attribute:: create_unknown_user\n\n        ``True`` or ``False``. Determines whether or not a user object is\n        created if not already in the database  Defaults to ``True``.\n\n    .. method:: authenticate(request, remote_user)\n\n        The username passed as ``remote_user`` is considered trusted. This\n        method returns the user object with the given username, creating a new\n        user object if :attr:`~RemoteUserBackend.create_unknown_user` is\n        ``True``.\n\n        Returns ``None`` if :attr:`~RemoteUserBackend.create_unknown_user` is\n        ``False`` and a ``User`` object with the given username is not found in\n        the database.\n\n        ``request`` is an :class:`~django.http.HttpRequest` and may be ``None``\n        if it wasn't provided to :func:`~django.contrib.auth.authenticate`\n        (which passes it on to the backend).\n\n    .. method:: clean_username(username)\n\n        Performs any cleaning on the ``username`` (e.g. stripping LDAP DN\n        information) prior to using it to get or create a user object. Returns\n        the cleaned username.\n\n    .. method:: configure_user(request, user)\n\n        Configures a newly created user.  This method is called immediately\n        after a new user is created, and can be used to perform custom setup\n        actions, such as setting the user's groups based on attributes in an\n        LDAP directory. Returns the user object.\n\n        ``request`` is an :class:`~django.http.HttpRequest` and may be ``None``\n        if it wasn't provided to :func:`~django.contrib.auth.authenticate`\n        (which passes it on to the backend).\n\n    .. method:: user_can_authenticate()\n\n        Returns whether the user is allowed to authenticate. This method\n        returns ``False`` for users with :attr:`is_active=False\n        <django.contrib.auth.models.User.is_active>`. Custom user models that\n        don't have an :attr:`~django.contrib.auth.models.CustomUser.is_active`\n        field are allowed.\n\n.. class:: AllowAllUsersRemoteUserBackend\n\n    Same as :class:`RemoteUserBackend` except that it doesn't reject inactive\n    users because :attr:`~RemoteUserBackend.user_can_authenticate` always\n    returns ``True``.\n\nUtility functions\n=================\n\n.. currentmodule:: django.contrib.auth\n\n.. function:: get_user(request)\n\n    Returns the user model instance associated with the given ``request``’s\n    session.\n\n    It checks if the authentication backend stored in the session is present in\n    :setting:`AUTHENTICATION_BACKENDS`. If so, it uses the backend's\n    ``get_user()`` method to retrieve the user model instance and then verifies\n    the session by calling the user model's\n    :meth:`~django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash`\n    method.\n\n    Returns an instance of :class:`~django.contrib.auth.models.AnonymousUser`\n    if the authentication backend stored in the session is no longer in\n    :setting:`AUTHENTICATION_BACKENDS`, if a user isn't returned by the\n    backend's ``get_user()`` method, or if the session auth hash doesn't\n    validate.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":106,"nodeType":"TextFile","repoName":null,"name":"contenttypes.txt","path":"docs/ref/contrib","text":"==========================\nThe contenttypes framework\n==========================\n\n.. module:: django.contrib.contenttypes\n   :synopsis: Provides generic interface to installed models.\n\nDjango includes a :mod:`~django.contrib.contenttypes` application that can\ntrack all of the models installed in your Django-powered project, providing a\nhigh-level, generic interface for working with your models.\n\nOverview\n========\n\nAt the heart of the contenttypes application is the\n:class:`~django.contrib.contenttypes.models.ContentType` model, which lives at\n``django.contrib.contenttypes.models.ContentType``. Instances of\n:class:`~django.contrib.contenttypes.models.ContentType` represent and store\ninformation about the models installed in your project, and new instances of\n:class:`~django.contrib.contenttypes.models.ContentType` are automatically\ncreated whenever new models are installed.\n\nInstances of :class:`~django.contrib.contenttypes.models.ContentType` have\nmethods for returning the model classes they represent and for querying objects\nfrom those models. :class:`~django.contrib.contenttypes.models.ContentType`\nalso has a :ref:`custom manager <custom-managers>` that adds methods for\nworking with :class:`~django.contrib.contenttypes.models.ContentType` and for\nobtaining instances of :class:`~django.contrib.contenttypes.models.ContentType`\nfor a particular model.\n\nRelations between your models and\n:class:`~django.contrib.contenttypes.models.ContentType` can also be used to\nenable \"generic\" relationships between an instance of one of your\nmodels and instances of any model you have installed.\n\nInstalling the contenttypes framework\n=====================================\n\nThe contenttypes framework is included in the default\n:setting:`INSTALLED_APPS` list created by ``django-admin startproject``,\nbut if you've removed it or if you manually set up your\n:setting:`INSTALLED_APPS` list, you can enable it by adding\n``'django.contrib.contenttypes'`` to your :setting:`INSTALLED_APPS` setting.\n\nIt's generally a good idea to have the contenttypes framework\ninstalled; several of Django's other bundled applications require it:\n\n* The admin application uses it to log the history of each object\n  added or changed through the admin interface.\n\n* Django's :mod:`authentication framework <django.contrib.auth>` uses it\n  to tie user permissions to specific models.\n\n.. currentmodule:: django.contrib.contenttypes.models\n\nThe ``ContentType`` model\n=========================\n\n.. class:: ContentType\n\n    Each instance of :class:`~django.contrib.contenttypes.models.ContentType`\n    has two fields which, taken together, uniquely describe an installed\n    model:\n\n    .. attribute:: app_label\n\n        The name of the application the model is part of. This is taken from\n        the :attr:`app_label` attribute of the model, and includes only the\n        *last* part of the application's Python import path;\n        ``django.contrib.contenttypes``, for example, becomes an\n        :attr:`app_label` of ``contenttypes``.\n\n    .. attribute:: model\n\n        The name of the model class.\n\n    Additionally, the following property is available:\n\n    .. attribute:: name\n\n        The human-readable name of the content type. This is taken from the\n        :attr:`verbose_name <django.db.models.Field.verbose_name>`\n        attribute of the model.\n\nLet's look at an example to see how this works. If you already have\nthe :mod:`~django.contrib.contenttypes` application installed, and then add\n:mod:`the sites application <django.contrib.sites>` to your\n:setting:`INSTALLED_APPS` setting and run ``manage.py migrate`` to install it,\nthe model :class:`django.contrib.sites.models.Site` will be installed into\nyour database. Along with it a new instance of\n:class:`~django.contrib.contenttypes.models.ContentType` will be\ncreated with the following values:\n\n* :attr:`~django.contrib.contenttypes.models.ContentType.app_label`\n  will be set to ``'sites'`` (the last part of the Python\n  path ``django.contrib.sites``).\n\n* :attr:`~django.contrib.contenttypes.models.ContentType.model`\n  will be set to ``'site'``.\n\nMethods on ``ContentType`` instances\n====================================\n\nEach :class:`~django.contrib.contenttypes.models.ContentType` instance has\nmethods that allow you to get from a\n:class:`~django.contrib.contenttypes.models.ContentType` instance to the\nmodel it represents, or to retrieve objects from that model:\n\n.. method:: ContentType.get_object_for_this_type(**kwargs)\n\n    Takes a set of valid :ref:`lookup arguments <field-lookups-intro>` for the\n    model the :class:`~django.contrib.contenttypes.models.ContentType`\n    represents, and does\n    :meth:`a get() lookup <django.db.models.query.QuerySet.get>`\n    on that model, returning the corresponding object.\n\n.. method:: ContentType.model_class()\n\n    Returns the model class represented by this\n    :class:`~django.contrib.contenttypes.models.ContentType` instance.\n\nFor example, we could look up the\n:class:`~django.contrib.contenttypes.models.ContentType` for the\n:class:`~django.contrib.auth.models.User` model::\n\n    >>> from django.contrib.contenttypes.models import ContentType\n    >>> user_type = ContentType.objects.get(app_label='auth', model='user')\n    >>> user_type\n    <ContentType: user>\n\nAnd then use it to query for a particular\n:class:`~django.contrib.auth.models.User`, or to get access\nto the ``User`` model class::\n\n    >>> user_type.model_class()\n    <class 'django.contrib.auth.models.User'>\n    >>> user_type.get_object_for_this_type(username='Guido')\n    <User: Guido>\n\nTogether,\n:meth:`~django.contrib.contenttypes.models.ContentType.get_object_for_this_type`\nand :meth:`~django.contrib.contenttypes.models.ContentType.model_class` enable\ntwo extremely important use cases:\n\n1. Using these methods, you can write high-level generic code that\n   performs queries on any installed model -- instead of importing and\n   using a single specific model class, you can pass an ``app_label`` and\n   ``model`` into a\n   :class:`~django.contrib.contenttypes.models.ContentType` lookup at\n   runtime, and then work with the model class or retrieve objects from it.\n\n2. You can relate another model to\n   :class:`~django.contrib.contenttypes.models.ContentType` as a way of\n   tying instances of it to particular model classes, and use these methods\n   to get access to those model classes.\n\nSeveral of Django's bundled applications make use of the latter technique.\nFor example,\n:class:`the permissions system <django.contrib.auth.models.Permission>` in\nDjango's authentication framework uses a\n:class:`~django.contrib.auth.models.Permission` model with a foreign\nkey to :class:`~django.contrib.contenttypes.models.ContentType`; this lets\n:class:`~django.contrib.auth.models.Permission` represent concepts like\n\"can add blog entry\" or \"can delete news story\".\n\nThe ``ContentTypeManager``\n--------------------------\n\n.. class:: ContentTypeManager\n\n    :class:`~django.contrib.contenttypes.models.ContentType` also has a custom\n    manager, :class:`~django.contrib.contenttypes.models.ContentTypeManager`,\n    which adds the following methods:\n\n    .. method:: clear_cache()\n\n        Clears an internal cache used by\n        :class:`~django.contrib.contenttypes.models.ContentType` to keep track\n        of models for which it has created\n        :class:`~django.contrib.contenttypes.models.ContentType` instances. You\n        probably won't ever need to call this method yourself; Django will call\n        it automatically when it's needed.\n\n    .. method:: get_for_id(id)\n\n        Lookup a :class:`~django.contrib.contenttypes.models.ContentType` by ID.\n        Since this method uses the same shared cache as\n        :meth:`~django.contrib.contenttypes.models.ContentTypeManager.get_for_model`,\n        it's preferred to use this method over the usual\n        ``ContentType.objects.get(pk=id)``\n\n    .. method:: get_for_model(model, for_concrete_model=True)\n\n        Takes either a model class or an instance of a model, and returns the\n        :class:`~django.contrib.contenttypes.models.ContentType` instance\n        representing that model. ``for_concrete_model=False`` allows fetching\n        the :class:`~django.contrib.contenttypes.models.ContentType` of a proxy\n        model.\n\n    .. method:: get_for_models(*models, for_concrete_models=True)\n\n        Takes a variadic number of model classes, and returns a dictionary\n        mapping the model classes to the\n        :class:`~django.contrib.contenttypes.models.ContentType` instances\n        representing them. ``for_concrete_models=False`` allows fetching the\n        :class:`~django.contrib.contenttypes.models.ContentType` of proxy\n        models.\n\n    .. method:: get_by_natural_key(app_label, model)\n\n        Returns the :class:`~django.contrib.contenttypes.models.ContentType`\n        instance uniquely identified by the given application label and model\n        name. The primary purpose of this method is to allow\n        :class:`~django.contrib.contenttypes.models.ContentType` objects to be\n        referenced via a :ref:`natural key<topics-serialization-natural-keys>`\n        during deserialization.\n\nThe :meth:`~ContentTypeManager.get_for_model()` method is especially\nuseful when you know you need to work with a\n:class:`ContentType <django.contrib.contenttypes.models.ContentType>` but don't\nwant to go to the trouble of obtaining the model's metadata to perform a manual\nlookup::\n\n    >>> from django.contrib.auth.models import User\n    >>> ContentType.objects.get_for_model(User)\n    <ContentType: user>\n\n.. module:: django.contrib.contenttypes.fields\n\n.. _generic-relations:\n\nGeneric relations\n=================\n\nAdding a foreign key from one of your own models to\n:class:`~django.contrib.contenttypes.models.ContentType` allows your model to\neffectively tie itself to another model class, as in the example of the\n:class:`~django.contrib.auth.models.Permission` model above. But it's possible\nto go one step further and use\n:class:`~django.contrib.contenttypes.models.ContentType` to enable truly\ngeneric (sometimes called \"polymorphic\") relationships between models.\n\nFor example, it could be used for a tagging system like so::\n\n    from django.contrib.contenttypes.fields import GenericForeignKey\n    from django.contrib.contenttypes.models import ContentType\n    from django.db import models\n\n    class TaggedItem(models.Model):\n        tag = models.SlugField()\n        content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)\n        object_id = models.PositiveIntegerField()\n        content_object = GenericForeignKey('content_type', 'object_id')\n\n        def __str__(self):\n            return self.tag\n\nA normal :class:`~django.db.models.ForeignKey` can only \"point\nto\" one other model, which means that if the ``TaggedItem`` model used a\n:class:`~django.db.models.ForeignKey` it would have to\nchoose one and only one model to store tags for. The contenttypes\napplication provides a special field type (``GenericForeignKey``) which\nworks around this and allows the relationship to be with any\nmodel:\n\n.. class:: GenericForeignKey\n\n    There are three parts to setting up a\n    :class:`~django.contrib.contenttypes.fields.GenericForeignKey`:\n\n    1. Give your model a :class:`~django.db.models.ForeignKey`\n       to :class:`~django.contrib.contenttypes.models.ContentType`. The usual\n       name for this field is \"content_type\".\n\n    2. Give your model a field that can store primary key values from the\n       models you'll be relating to. For most models, this means a\n       :class:`~django.db.models.PositiveIntegerField`. The usual name\n       for this field is \"object_id\".\n\n    3. Give your model a\n       :class:`~django.contrib.contenttypes.fields.GenericForeignKey`, and\n       pass it the names of the two fields described above. If these fields\n       are named \"content_type\" and \"object_id\", you can omit this -- those\n       are the default field names\n       :class:`~django.contrib.contenttypes.fields.GenericForeignKey` will\n       look for.\n\n    .. attribute:: GenericForeignKey.for_concrete_model\n\n       If ``False``, the field will be able to reference proxy models. Default\n       is ``True``. This mirrors the ``for_concrete_model`` argument to\n       :meth:`~django.contrib.contenttypes.models.ContentTypeManager.get_for_model`.\n\n.. admonition:: Primary key type compatibility\n\n   The \"object_id\" field doesn't have to be the same type as the\n   primary key fields on the related models, but their primary key values\n   must be coercible to the same type as the \"object_id\" field by its\n   :meth:`~django.db.models.Field.get_db_prep_value` method.\n\n   For example, if you want to allow generic relations to models with either\n   :class:`~django.db.models.IntegerField` or\n   :class:`~django.db.models.CharField` primary key fields, you\n   can use :class:`~django.db.models.CharField` for the\n   \"object_id\" field on your model since integers can be coerced to\n   strings by :meth:`~django.db.models.Field.get_db_prep_value`.\n\n   For maximum flexibility you can use a\n   :class:`~django.db.models.TextField` which doesn't have a\n   maximum length defined, however this may incur significant performance\n   penalties depending on your database backend.\n\n   There is no one-size-fits-all solution for which field type is best. You\n   should evaluate the models you expect to be pointing to and determine\n   which solution will be most effective for your use case.\n\n.. admonition:: Serializing references to ``ContentType`` objects\n\n   If you're serializing data (for example, when generating\n   :class:`~django.test.TransactionTestCase.fixtures`) from a model that implements\n   generic relations, you should probably be using a natural key to uniquely\n   identify related :class:`~django.contrib.contenttypes.models.ContentType`\n   objects. See :ref:`natural keys<topics-serialization-natural-keys>` and\n   :option:`dumpdata --natural-foreign` for more information.\n\nThis will enable an API similar to the one used for a normal\n:class:`~django.db.models.ForeignKey`;\neach ``TaggedItem`` will have a ``content_object`` field that returns the\nobject it's related to, and you can also assign to that field or use it when\ncreating a ``TaggedItem``::\n\n    >>> from django.contrib.auth.models import User\n    >>> guido = User.objects.get(username='Guido')\n    >>> t = TaggedItem(content_object=guido, tag='bdfl')\n    >>> t.save()\n    >>> t.content_object\n    <User: Guido>\n\nIf the related object is deleted, the ``content_type`` and ``object_id`` fields\nremain set to their original values and the ``GenericForeignKey`` returns\n``None``::\n\n    >>> guido.delete()\n    >>> t.content_object  # returns None\n\nDue to the way :class:`~django.contrib.contenttypes.fields.GenericForeignKey`\nis implemented, you cannot use such fields directly with filters (``filter()``\nand ``exclude()``, for example) via the database API. Because a\n:class:`~django.contrib.contenttypes.fields.GenericForeignKey` isn't a\nnormal field object, these examples will *not* work::\n\n    # This will fail\n    >>> TaggedItem.objects.filter(content_object=guido)\n    # This will also fail\n    >>> TaggedItem.objects.get(content_object=guido)\n\nLikewise, :class:`~django.contrib.contenttypes.fields.GenericForeignKey`\\s\ndoes not appear in :class:`~django.forms.ModelForm`\\s.\n\nReverse generic relations\n-------------------------\n\n.. class:: GenericRelation\n\n    .. attribute:: related_query_name\n\n        The relation on the related object back to this object doesn't exist by\n        default. Setting ``related_query_name`` creates a relation from the\n        related object back to this one. This allows querying and filtering\n        from the related object.\n\nIf you know which models you'll be using most often, you can also add\na \"reverse\" generic relationship to enable an additional API. For example::\n\n    from django.contrib.contenttypes.fields import GenericRelation\n    from django.db import models\n\n    class Bookmark(models.Model):\n        url = models.URLField()\n        tags = GenericRelation(TaggedItem)\n\n``Bookmark`` instances will each have a ``tags`` attribute, which can\nbe used to retrieve their associated ``TaggedItems``::\n\n    >>> b = Bookmark(url='https://www.djangoproject.com/')\n    >>> b.save()\n    >>> t1 = TaggedItem(content_object=b, tag='django')\n    >>> t1.save()\n    >>> t2 = TaggedItem(content_object=b, tag='python')\n    >>> t2.save()\n    >>> b.tags.all()\n    <QuerySet [<TaggedItem: django>, <TaggedItem: python>]>\n\nDefining :class:`~django.contrib.contenttypes.fields.GenericRelation` with\n``related_query_name`` set allows querying from the related object::\n\n    tags = GenericRelation(TaggedItem, related_query_name='bookmark')\n\nThis enables filtering, ordering, and other query operations on ``Bookmark``\nfrom ``TaggedItem``::\n\n    >>> # Get all tags belonging to bookmarks containing `django` in the url\n    >>> TaggedItem.objects.filter(bookmark__url__contains='django')\n    <QuerySet [<TaggedItem: django>, <TaggedItem: python>]>\n\nIf you don't add the ``related_query_name``, you can do the same types of\nlookups manually::\n\n    >>> bookmarks = Bookmark.objects.filter(url__contains='django')\n    >>> bookmark_type = ContentType.objects.get_for_model(Bookmark)\n    >>> TaggedItem.objects.filter(content_type__pk=bookmark_type.id, object_id__in=bookmarks)\n    <QuerySet [<TaggedItem: django>, <TaggedItem: python>]>\n\nJust as :class:`~django.contrib.contenttypes.fields.GenericForeignKey`\naccepts the names of the content-type and object-ID fields as\narguments, so too does\n:class:`~django.contrib.contenttypes.fields.GenericRelation`;\nif the model which has the generic foreign key is using non-default names\nfor those fields, you must pass the names of the fields when setting up a\n:class:`.GenericRelation` to it. For example, if the ``TaggedItem`` model\nreferred to above used fields named ``content_type_fk`` and\n``object_primary_key`` to create its generic foreign key, then a\n:class:`.GenericRelation` back to it would need to be defined like so::\n\n    tags = GenericRelation(\n        TaggedItem,\n        content_type_field='content_type_fk',\n        object_id_field='object_primary_key',\n    )\n\nNote also, that if you delete an object that has a\n:class:`~django.contrib.contenttypes.fields.GenericRelation`, any objects\nwhich have a :class:`~django.contrib.contenttypes.fields.GenericForeignKey`\npointing at it will be deleted as well. In the example above, this means that\nif a ``Bookmark`` object were deleted, any ``TaggedItem`` objects pointing at\nit would be deleted at the same time.\n\nUnlike :class:`~django.db.models.ForeignKey`,\n:class:`~django.contrib.contenttypes.fields.GenericForeignKey` does not accept\nan :attr:`~django.db.models.ForeignKey.on_delete` argument to customize this\nbehavior; if desired, you can avoid the cascade-deletion by not using\n:class:`~django.contrib.contenttypes.fields.GenericRelation`, and alternate\nbehavior can be provided via the :data:`~django.db.models.signals.pre_delete`\nsignal.\n\nGeneric relations and aggregation\n---------------------------------\n\n:doc:`Django's database aggregation API </topics/db/aggregation>` works with a\n:class:`~django.contrib.contenttypes.fields.GenericRelation`. For example, you\ncan find out how many tags all the bookmarks have::\n\n    >>> Bookmark.objects.aggregate(Count('tags'))\n    {'tags__count': 3}\n\n.. module:: django.contrib.contenttypes.forms\n\nGeneric relation in forms\n-------------------------\n\nThe :mod:`django.contrib.contenttypes.forms` module provides:\n\n* :class:`BaseGenericInlineFormSet`\n* A formset factory, :func:`generic_inlineformset_factory`, for use with\n  :class:`~django.contrib.contenttypes.fields.GenericForeignKey`.\n\n.. class:: BaseGenericInlineFormSet\n\n.. function:: generic_inlineformset_factory(model, form=ModelForm, formset=BaseGenericInlineFormSet, ct_field=\"content_type\", fk_field=\"object_id\", fields=None, exclude=None, extra=3, can_order=False, can_delete=True, max_num=None, formfield_callback=None, validate_max=False, for_concrete_model=True, min_num=None, validate_min=False)\n\n    Returns a ``GenericInlineFormSet`` using\n    :func:`~django.forms.models.modelformset_factory`.\n\n    You must provide ``ct_field`` and ``fk_field`` if they are different from\n    the defaults, ``content_type`` and ``object_id`` respectively. Other\n    parameters are similar to those documented in\n    :func:`~django.forms.models.modelformset_factory` and\n    :func:`~django.forms.models.inlineformset_factory`.\n\n    The ``for_concrete_model`` argument corresponds to the\n    :class:`~django.contrib.contenttypes.fields.GenericForeignKey.for_concrete_model`\n    argument on ``GenericForeignKey``.\n\n.. module:: django.contrib.contenttypes.admin\n\nGeneric relations in admin\n--------------------------\n\nThe :mod:`django.contrib.contenttypes.admin` module provides\n:class:`~django.contrib.contenttypes.admin.GenericTabularInline` and\n:class:`~django.contrib.contenttypes.admin.GenericStackedInline` (subclasses of\n:class:`~django.contrib.contenttypes.admin.GenericInlineModelAdmin`)\n\nThese classes and functions enable the use of generic relations in forms\nand the admin. See the :doc:`model formset </topics/forms/modelforms>` and\n:ref:`admin <using-generic-relations-as-an-inline>` documentation for more\ninformation.\n\n.. class:: GenericInlineModelAdmin\n\n    The :class:`~django.contrib.contenttypes.admin.GenericInlineModelAdmin`\n    class inherits all properties from an\n    :class:`~django.contrib.admin.InlineModelAdmin` class. However,\n    it adds a couple of its own for working with the generic relation:\n\n    .. attribute:: ct_field\n\n        The name of the\n        :class:`~django.contrib.contenttypes.models.ContentType` foreign key\n        field on the model. Defaults to ``content_type``.\n\n    .. attribute:: ct_fk_field\n\n        The name of the integer field that represents the ID of the related\n        object. Defaults to ``object_id``.\n\n.. class:: GenericTabularInline\n.. class:: GenericStackedInline\n\n    Subclasses of :class:`GenericInlineModelAdmin` with stacked and tabular\n    layouts, respectively.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":107,"nodeType":"TextFile","repoName":null,"name":"syndication.txt","path":"docs/ref/contrib","text":"==============================\nThe syndication feed framework\n==============================\n\n.. module:: django.contrib.syndication\n   :synopsis: A framework for generating syndication feeds, in RSS and Atom,\n              quite easily.\n\nDjango comes with a high-level syndication-feed-generating framework for\ncreating RSS_ and :rfc:`Atom <4287>` feeds.\n\nTo create any syndication feed, all you have to do is write a short\nPython class. You can create as many feeds as you want.\n\nDjango also comes with a lower-level feed-generating API. Use this if\nyou want to generate feeds outside of a Web context, or in some other\nlower-level way.\n\n.. _RSS: http://www.whatisrss.com/\n\nThe high-level framework\n========================\n\nOverview\n--------\n\nThe high-level feed-generating framework is supplied by the\n:class:`~django.contrib.syndication.views.Feed` class. To create a\nfeed, write a :class:`~django.contrib.syndication.views.Feed` class\nand point to an instance of it in your :doc:`URLconf\n</topics/http/urls>`.\n\n``Feed`` classes\n----------------\n\nA :class:`~django.contrib.syndication.views.Feed` class is a Python\nclass that represents a syndication feed. A feed can be simple (e.g.,\na \"site news\" feed, or a basic feed displaying the latest entries of a\nblog) or more complex (e.g., a feed displaying all the blog entries in\na particular category, where the category is variable).\n\nFeed classes subclass :class:`django.contrib.syndication.views.Feed`.\nThey can live anywhere in your codebase.\n\nInstances of :class:`~django.contrib.syndication.views.Feed` classes\nare views which can be used in your :doc:`URLconf </topics/http/urls>`.\n\nA simple example\n----------------\n\nThis simple example, taken from a hypothetical police beat news site describes\na feed of the latest five news items::\n\n    from django.contrib.syndication.views import Feed\n    from django.urls import reverse\n    from policebeat.models import NewsItem\n\n    class LatestEntriesFeed(Feed):\n        title = \"Police beat site news\"\n        link = \"/sitenews/\"\n        description = \"Updates on changes and additions to police beat central.\"\n\n        def items(self):\n            return NewsItem.objects.order_by('-pub_date')[:5]\n\n        def item_title(self, item):\n            return item.title\n\n        def item_description(self, item):\n            return item.description\n\n        # item_link is only needed if NewsItem has no get_absolute_url method.\n        def item_link(self, item):\n            return reverse('news-item', args=[item.pk])\n\nTo connect a URL to this feed, put an instance of the Feed object in\nyour :doc:`URLconf </topics/http/urls>`. For example::\n\n    from django.urls import path\n    from myproject.feeds import LatestEntriesFeed\n\n    urlpatterns = [\n        # ...\n        path('latest/feed/', LatestEntriesFeed()),\n        # ...\n    ]\n\nNote:\n\n* The Feed class subclasses :class:`django.contrib.syndication.views.Feed`.\n\n* ``title``, ``link`` and ``description`` correspond to the\n  standard RSS ``<title>``, ``<link>`` and ``<description>`` elements,\n  respectively.\n\n* ``items()`` is, a method that returns a list of objects that should be\n  included in the feed as ``<item>`` elements. Although this example returns\n  ``NewsItem`` objects using Django's :doc:`object-relational mapper\n  </ref/models/querysets>`, ``items()`` doesn't have to return model instances.\n  Although you get a few bits of functionality \"for free\" by using Django\n  models, ``items()`` can return any type of object you want.\n\n* If you're creating an Atom feed, rather than an RSS feed, set the\n  ``subtitle`` attribute instead of the ``description`` attribute.\n  See `Publishing Atom and RSS feeds in tandem`_, later, for an example.\n\nOne thing is left to do. In an RSS feed, each ``<item>`` has a ``<title>``,\n``<link>`` and ``<description>``. We need to tell the framework what data to put\ninto those elements.\n\n* For the contents of ``<title>`` and ``<description>``, Django tries\n  calling the methods ``item_title()`` and ``item_description()`` on\n  the :class:`~django.contrib.syndication.views.Feed` class. They are passed\n  a single parameter, ``item``, which is the object itself. These are\n  optional; by default, the string representation of the object is used for\n  both.\n\n  If you want to do any special formatting for either the title or\n  description, :doc:`Django templates </ref/templates/language>` can be used\n  instead. Their paths can be specified with the ``title_template`` and\n  ``description_template`` attributes on the\n  :class:`~django.contrib.syndication.views.Feed` class. The templates are\n  rendered for each item and are passed two template context variables:\n\n  * ``{{ obj }}`` -- The current object (one of whichever objects you\n    returned in ``items()``).\n\n  * ``{{ site }}`` -- A :class:`django.contrib.sites.models.Site` object\n    representing the current site. This is useful for ``{{ site.domain\n    }}`` or ``{{ site.name }}``. If you do *not* have the Django sites\n    framework installed, this will be set to a\n    :class:`~django.contrib.sites.requests.RequestSite` object. See the\n    :ref:`RequestSite section of the sites framework documentation\n    <requestsite-objects>` for more.\n\n  See `a complex example`_ below that uses a description template.\n\n  .. method:: Feed.get_context_data(**kwargs)\n\n      There is also a way to pass additional information to title and description\n      templates, if you need to supply more than the two variables mentioned\n      before. You can provide your implementation of ``get_context_data`` method\n      in your ``Feed`` subclass. For example::\n\n        from mysite.models import Article\n        from django.contrib.syndication.views import Feed\n\n        class ArticlesFeed(Feed):\n            title = \"My articles\"\n            description_template = \"feeds/articles.html\"\n\n            def items(self):\n                return Article.objects.order_by('-pub_date')[:5]\n\n            def get_context_data(self, **kwargs):\n                context = super().get_context_data(**kwargs)\n                context['foo'] = 'bar'\n                return context\n\n  And the template:\n\n  .. code-block:: html+django\n\n    Something about {{ foo }}: {{ obj.description }}\n\n  This method will be called once per each item in the list returned by\n  ``items()`` with the following keyword arguments:\n\n  * ``item``: the current item. For backward compatibility reasons, the name\n    of this context variable is ``{{ obj }}``.\n\n  * ``obj``: the object returned by ``get_object()``. By default this is not\n    exposed to the templates to avoid confusion with ``{{ obj }}`` (see above),\n    but you can use it in your implementation of ``get_context_data()``.\n\n  * ``site``: current site as described above.\n\n  * ``request``: current request.\n\n  The behavior of ``get_context_data()`` mimics that of\n  :ref:`generic views <adding-extra-context>` - you're supposed to call\n  ``super()`` to retrieve context data from parent class, add your data\n  and return the modified dictionary.\n\n* To specify the contents of ``<link>``, you have two options. For each item\n  in ``items()``, Django first tries calling the\n  ``item_link()`` method on the\n  :class:`~django.contrib.syndication.views.Feed` class. In a similar way to\n  the title and description, it is passed it a single parameter,\n  ``item``. If that method doesn't exist, Django tries executing a\n  ``get_absolute_url()`` method on that object. Both\n  ``get_absolute_url()`` and ``item_link()`` should return the\n  item's URL as a normal Python string. As with ``get_absolute_url()``, the\n  result of ``item_link()`` will be included directly in the URL, so you\n  are responsible for doing all necessary URL quoting and conversion to\n  ASCII inside the method itself.\n\nA complex example\n-----------------\n\nThe framework also supports more complex feeds, via arguments.\n\nFor example, a website could offer an RSS feed of recent crimes for every\npolice beat in a city. It'd be silly to create a separate\n:class:`~django.contrib.syndication.views.Feed` class for each police beat; that\nwould violate the :ref:`DRY principle <dry>` and would couple data to\nprogramming logic. Instead, the syndication framework lets you access the\narguments passed from your :doc:`URLconf </topics/http/urls>` so feeds can output\nitems based on information in the feed's URL.\n\nThe police beat feeds could be accessible via URLs like this:\n\n* :file:`/beats/613/rss/` -- Returns recent crimes for beat 613.\n* :file:`/beats/1424/rss/` -- Returns recent crimes for beat 1424.\n\nThese can be matched with a :doc:`URLconf </topics/http/urls>` line such as::\n\n    path('beats/<int:beat_id>/rss/', BeatFeed()),\n\nLike a view, the arguments in the URL are passed to the ``get_object()``\nmethod along with the request object.\n\nHere's the code for these beat-specific feeds::\n\n    from django.contrib.syndication.views import Feed\n\n    class BeatFeed(Feed):\n        description_template = 'feeds/beat_description.html'\n\n        def get_object(self, request, beat_id):\n            return Beat.objects.get(pk=beat_id)\n\n        def title(self, obj):\n            return \"Police beat central: Crimes for beat %s\" % obj.beat\n\n        def link(self, obj):\n            return obj.get_absolute_url()\n\n        def description(self, obj):\n            return \"Crimes recently reported in police beat %s\" % obj.beat\n\n        def items(self, obj):\n            return Crime.objects.filter(beat=obj).order_by('-crime_date')[:30]\n\nTo generate the feed's ``<title>``, ``<link>`` and ``<description>``, Django\nuses the ``title()``, ``link()`` and ``description()`` methods. In\nthe previous example, they were string class attributes, but this example\nillustrates that they can be either strings *or* methods. For each of\n``title``, ``link`` and ``description``, Django follows this\nalgorithm:\n\n* First, it tries to call a method, passing the ``obj`` argument, where\n  ``obj`` is the object returned by ``get_object()``.\n\n* Failing that, it tries to call a method with no arguments.\n\n* Failing that, it uses the class attribute.\n\nAlso note that ``items()`` also follows the same algorithm -- first, it\ntries ``items(obj)``, then ``items()``, then finally an ``items``\nclass attribute (which should be a list).\n\nWe are using a template for the item descriptions. It can be as minimal as\nthis:\n\n.. code-block:: html+django\n\n    {{ obj.description }}\n\nHowever, you are free to add formatting as desired.\n\nThe ``ExampleFeed`` class below gives full documentation on methods and\nattributes of :class:`~django.contrib.syndication.views.Feed` classes.\n\nSpecifying the type of feed\n---------------------------\n\nBy default, feeds produced in this framework use RSS 2.0.\n\nTo change that, add a ``feed_type`` attribute to your\n:class:`~django.contrib.syndication.views.Feed` class, like so::\n\n    from django.utils.feedgenerator import Atom1Feed\n\n    class MyFeed(Feed):\n        feed_type = Atom1Feed\n\nNote that you set ``feed_type`` to a class object, not an instance.\n\nCurrently available feed types are:\n\n* :class:`django.utils.feedgenerator.Rss201rev2Feed` (RSS 2.01. Default.)\n* :class:`django.utils.feedgenerator.RssUserland091Feed` (RSS 0.91.)\n* :class:`django.utils.feedgenerator.Atom1Feed` (Atom 1.0.)\n\nEnclosures\n----------\n\nTo specify enclosures, such as those used in creating podcast feeds, use the\n``item_enclosures`` hook or, alternatively and if you only have a single\nenclosure per item, the ``item_enclosure_url``, ``item_enclosure_length``, and\n``item_enclosure_mime_type`` hooks. See the ``ExampleFeed`` class below for\nusage examples.\n\nLanguage\n--------\n\nFeeds created by the syndication framework automatically include the\nappropriate ``<language>`` tag (RSS 2.0) or ``xml:lang`` attribute (Atom). By\ndefault, this is :func:`django.utils.translation.get_language()`. You can change it\nby setting the ``language`` class attribute.\n\nURLs\n----\n\nThe ``link`` method/attribute can return either an absolute path (e.g.\n:file:`\"/blog/\"`) or a URL with the fully-qualified domain and protocol (e.g.\n``\"https://www.example.com/blog/\"``). If ``link`` doesn't return the domain,\nthe syndication framework will insert the domain of the current site, according\nto your :setting:`SITE_ID setting <SITE_ID>`.\n\nAtom feeds require a ``<link rel=\"self\">`` that defines the feed's current\nlocation. The syndication framework populates this automatically, using the\ndomain of the current site according to the :setting:`SITE_ID` setting.\n\nPublishing Atom and RSS feeds in tandem\n---------------------------------------\n\nSome developers like to make available both Atom *and* RSS versions of their\nfeeds. To do that, you can create a subclass of your\n:class:`~django.contrib.syndication.views.Feed` class and set the ``feed_type``\nto something different. Then update your URLconf to add the extra versions.\n\nHere's a full example::\n\n    from django.contrib.syndication.views import Feed\n    from policebeat.models import NewsItem\n    from django.utils.feedgenerator import Atom1Feed\n\n    class RssSiteNewsFeed(Feed):\n        title = \"Police beat site news\"\n        link = \"/sitenews/\"\n        description = \"Updates on changes and additions to police beat central.\"\n\n        def items(self):\n            return NewsItem.objects.order_by('-pub_date')[:5]\n\n    class AtomSiteNewsFeed(RssSiteNewsFeed):\n        feed_type = Atom1Feed\n        subtitle = RssSiteNewsFeed.description\n\n.. Note::\n    In this example, the RSS feed uses a ``description`` while the Atom\n    feed uses a ``subtitle``. That's because Atom feeds don't provide for\n    a feed-level \"description,\" but they *do* provide for a \"subtitle.\"\n\n    If you provide a ``description`` in your\n    :class:`~django.contrib.syndication.views.Feed` class, Django will *not*\n    automatically put that into the ``subtitle`` element, because a\n    subtitle and description are not necessarily the same thing. Instead, you\n    should define a ``subtitle`` attribute.\n\n    In the above example, we set the Atom feed's ``subtitle`` to the RSS feed's\n    ``description``, because it's quite short already.\n\nAnd the accompanying URLconf::\n\n    from django.urls import path\n    from myproject.feeds import AtomSiteNewsFeed, RssSiteNewsFeed\n\n    urlpatterns = [\n        # ...\n        path('sitenews/rss/', RssSiteNewsFeed()),\n        path('sitenews/atom/', AtomSiteNewsFeed()),\n        # ...\n    ]\n\n``Feed`` class reference\n------------------------\n\n.. class:: views.Feed\n\nThis example illustrates all possible attributes and methods for a\n:class:`~django.contrib.syndication.views.Feed` class::\n\n    from django.contrib.syndication.views import Feed\n    from django.utils import feedgenerator\n\n    class ExampleFeed(Feed):\n\n        # FEED TYPE -- Optional. This should be a class that subclasses\n        # django.utils.feedgenerator.SyndicationFeed. This designates\n        # which type of feed this should be: RSS 2.0, Atom 1.0, etc. If\n        # you don't specify feed_type, your feed will be RSS 2.0. This\n        # should be a class, not an instance of the class.\n\n        feed_type = feedgenerator.Rss201rev2Feed\n\n        # TEMPLATE NAMES -- Optional. These should be strings\n        # representing names of Django templates that the system should\n        # use in rendering the title and description of your feed items.\n        # Both are optional. If a template is not specified, the\n        # item_title() or item_description() methods are used instead.\n\n        title_template = None\n        description_template = None\n\n        # LANGUAGE -- Optional. This should be a string specifying a language\n        # code. Defaults to django.utils.translation.get_language().\n        language = 'de'\n\n        # TITLE -- One of the following three is required. The framework\n        # looks for them in this order.\n\n        def title(self, obj):\n            \"\"\"\n            Takes the object returned by get_object() and returns the\n            feed's title as a normal Python string.\n            \"\"\"\n\n        def title(self):\n            \"\"\"\n            Returns the feed's title as a normal Python string.\n            \"\"\"\n\n        title = 'foo' # Hard-coded title.\n\n        # LINK -- One of the following three is required. The framework\n        # looks for them in this order.\n\n        def link(self, obj):\n            \"\"\"\n            # Takes the object returned by get_object() and returns the URL\n            # of the HTML version of the feed as a normal Python string.\n            \"\"\"\n\n        def link(self):\n            \"\"\"\n            Returns the URL of the HTML version of the feed as a normal Python\n            string.\n            \"\"\"\n\n        link = '/blog/' # Hard-coded URL.\n\n        # FEED_URL -- One of the following three is optional. The framework\n        # looks for them in this order.\n\n        def feed_url(self, obj):\n            \"\"\"\n            # Takes the object returned by get_object() and returns the feed's\n            # own URL as a normal Python string.\n            \"\"\"\n\n        def feed_url(self):\n            \"\"\"\n            Returns the feed's own URL as a normal Python string.\n            \"\"\"\n\n        feed_url = '/blog/rss/' # Hard-coded URL.\n\n        # GUID -- One of the following three is optional. The framework looks\n        # for them in this order. This property is only used for Atom feeds\n        # (where it is the feed-level ID element). If not provided, the feed\n        # link is used as the ID.\n\n        def feed_guid(self, obj):\n            \"\"\"\n            Takes the object returned by get_object() and returns the globally\n            unique ID for the feed as a normal Python string.\n            \"\"\"\n\n        def feed_guid(self):\n            \"\"\"\n            Returns the feed's globally unique ID as a normal Python string.\n            \"\"\"\n\n        feed_guid = '/foo/bar/1234' # Hard-coded guid.\n\n        # DESCRIPTION -- One of the following three is required. The framework\n        # looks for them in this order.\n\n        def description(self, obj):\n            \"\"\"\n            Takes the object returned by get_object() and returns the feed's\n            description as a normal Python string.\n            \"\"\"\n\n        def description(self):\n            \"\"\"\n            Returns the feed's description as a normal Python string.\n            \"\"\"\n\n        description = 'Foo bar baz.' # Hard-coded description.\n\n        # AUTHOR NAME --One of the following three is optional. The framework\n        # looks for them in this order.\n\n        def author_name(self, obj):\n            \"\"\"\n            Takes the object returned by get_object() and returns the feed's\n            author's name as a normal Python string.\n            \"\"\"\n\n        def author_name(self):\n            \"\"\"\n            Returns the feed's author's name as a normal Python string.\n            \"\"\"\n\n        author_name = 'Sally Smith' # Hard-coded author name.\n\n        # AUTHOR EMAIL --One of the following three is optional. The framework\n        # looks for them in this order.\n\n        def author_email(self, obj):\n            \"\"\"\n            Takes the object returned by get_object() and returns the feed's\n            author's email as a normal Python string.\n            \"\"\"\n\n        def author_email(self):\n            \"\"\"\n            Returns the feed's author's email as a normal Python string.\n            \"\"\"\n\n        author_email = 'test@example.com' # Hard-coded author email.\n\n        # AUTHOR LINK --One of the following three is optional. The framework\n        # looks for them in this order. In each case, the URL should include\n        # the \"http://\" and domain name.\n\n        def author_link(self, obj):\n            \"\"\"\n            Takes the object returned by get_object() and returns the feed's\n            author's URL as a normal Python string.\n            \"\"\"\n\n        def author_link(self):\n            \"\"\"\n            Returns the feed's author's URL as a normal Python string.\n            \"\"\"\n\n        author_link = 'https://www.example.com/' # Hard-coded author URL.\n\n        # CATEGORIES -- One of the following three is optional. The framework\n        # looks for them in this order. In each case, the method/attribute\n        # should return an iterable object that returns strings.\n\n        def categories(self, obj):\n            \"\"\"\n            Takes the object returned by get_object() and returns the feed's\n            categories as iterable over strings.\n            \"\"\"\n\n        def categories(self):\n            \"\"\"\n            Returns the feed's categories as iterable over strings.\n            \"\"\"\n\n        categories = (\"python\", \"django\") # Hard-coded list of categories.\n\n        # COPYRIGHT NOTICE -- One of the following three is optional. The\n        # framework looks for them in this order.\n\n        def feed_copyright(self, obj):\n            \"\"\"\n            Takes the object returned by get_object() and returns the feed's\n            copyright notice as a normal Python string.\n            \"\"\"\n\n        def feed_copyright(self):\n            \"\"\"\n            Returns the feed's copyright notice as a normal Python string.\n            \"\"\"\n\n        feed_copyright = 'Copyright (c) 2007, Sally Smith' # Hard-coded copyright notice.\n\n        # TTL -- One of the following three is optional. The framework looks\n        # for them in this order. Ignored for Atom feeds.\n\n        def ttl(self, obj):\n            \"\"\"\n            Takes the object returned by get_object() and returns the feed's\n            TTL (Time To Live) as a normal Python string.\n            \"\"\"\n\n        def ttl(self):\n            \"\"\"\n            Returns the feed's TTL as a normal Python string.\n            \"\"\"\n\n        ttl = 600 # Hard-coded Time To Live.\n\n        # ITEMS -- One of the following three is required. The framework looks\n        # for them in this order.\n\n        def items(self, obj):\n            \"\"\"\n            Takes the object returned by get_object() and returns a list of\n            items to publish in this feed.\n            \"\"\"\n\n        def items(self):\n            \"\"\"\n            Returns a list of items to publish in this feed.\n            \"\"\"\n\n        items = ('Item 1', 'Item 2') # Hard-coded items.\n\n        # GET_OBJECT -- This is required for feeds that publish different data\n        # for different URL parameters. (See \"A complex example\" above.)\n\n        def get_object(self, request, *args, **kwargs):\n            \"\"\"\n            Takes the current request and the arguments from the URL, and\n            returns an object represented by this feed. Raises\n            django.core.exceptions.ObjectDoesNotExist on error.\n            \"\"\"\n\n        # ITEM TITLE AND DESCRIPTION -- If title_template or\n        # description_template are not defined, these are used instead. Both are\n        # optional, by default they will use the string representation of the\n        # item.\n\n        def item_title(self, item):\n            \"\"\"\n            Takes an item, as returned by items(), and returns the item's\n            title as a normal Python string.\n            \"\"\"\n\n        def item_title(self):\n            \"\"\"\n            Returns the title for every item in the feed.\n            \"\"\"\n\n        item_title = 'Breaking News: Nothing Happening' # Hard-coded title.\n\n        def item_description(self, item):\n            \"\"\"\n            Takes an item, as returned by items(), and returns the item's\n            description as a normal Python string.\n            \"\"\"\n\n        def item_description(self):\n            \"\"\"\n            Returns the description for every item in the feed.\n            \"\"\"\n\n        item_description = 'A description of the item.' # Hard-coded description.\n\n        def get_context_data(self, **kwargs):\n            \"\"\"\n            Returns a dictionary to use as extra context if either\n            description_template or item_template are used.\n\n            Default implementation preserves the old behavior\n            of using {'obj': item, 'site': current_site} as the context.\n            \"\"\"\n\n        # ITEM LINK -- One of these three is required. The framework looks for\n        # them in this order.\n\n        # First, the framework tries the two methods below, in\n        # order. Failing that, it falls back to the get_absolute_url()\n        # method on each item returned by items().\n\n        def item_link(self, item):\n            \"\"\"\n            Takes an item, as returned by items(), and returns the item's URL.\n            \"\"\"\n\n        def item_link(self):\n            \"\"\"\n            Returns the URL for every item in the feed.\n            \"\"\"\n\n        # ITEM_GUID -- The following method is optional. If not provided, the\n        # item's link is used by default.\n\n        def item_guid(self, obj):\n            \"\"\"\n            Takes an item, as return by items(), and returns the item's ID.\n            \"\"\"\n\n        # ITEM_GUID_IS_PERMALINK -- The following method is optional. If\n        # provided, it sets the 'isPermaLink' attribute of an item's\n        # GUID element. This method is used only when 'item_guid' is\n        # specified.\n\n        def item_guid_is_permalink(self, obj):\n            \"\"\"\n            Takes an item, as returned by items(), and returns a boolean.\n            \"\"\"\n\n        item_guid_is_permalink = False  # Hard coded value\n\n        # ITEM AUTHOR NAME -- One of the following three is optional. The\n        # framework looks for them in this order.\n\n        def item_author_name(self, item):\n            \"\"\"\n            Takes an item, as returned by items(), and returns the item's\n            author's name as a normal Python string.\n            \"\"\"\n\n        def item_author_name(self):\n            \"\"\"\n            Returns the author name for every item in the feed.\n            \"\"\"\n\n        item_author_name = 'Sally Smith' # Hard-coded author name.\n\n        # ITEM AUTHOR EMAIL --One of the following three is optional. The\n        # framework looks for them in this order.\n        #\n        # If you specify this, you must specify item_author_name.\n\n        def item_author_email(self, obj):\n            \"\"\"\n            Takes an item, as returned by items(), and returns the item's\n            author's email as a normal Python string.\n            \"\"\"\n\n        def item_author_email(self):\n            \"\"\"\n            Returns the author email for every item in the feed.\n            \"\"\"\n\n        item_author_email = 'test@example.com' # Hard-coded author email.\n\n        # ITEM AUTHOR LINK -- One of the following three is optional. The\n        # framework looks for them in this order. In each case, the URL should\n        # include the \"http://\" and domain name.\n        #\n        # If you specify this, you must specify item_author_name.\n\n        def item_author_link(self, obj):\n            \"\"\"\n            Takes an item, as returned by items(), and returns the item's\n            author's URL as a normal Python string.\n            \"\"\"\n\n        def item_author_link(self):\n            \"\"\"\n            Returns the author URL for every item in the feed.\n            \"\"\"\n\n        item_author_link = 'https://www.example.com/' # Hard-coded author URL.\n\n        # ITEM ENCLOSURES -- One of the following three is optional. The\n        # framework looks for them in this order. If one of them is defined,\n        # ``item_enclosure_url``, ``item_enclosure_length``, and\n        # ``item_enclosure_mime_type`` will have no effect.\n\n        def item_enclosures(self, item):\n            \"\"\"\n            Takes an item, as returned by items(), and returns a list of\n            ``django.utils.feedgenerator.Enclosure`` objects.\n            \"\"\"\n\n        def item_enclosures(self):\n            \"\"\"\n            Returns the ``django.utils.feedgenerator.Enclosure`` list for every\n            item in the feed.\n            \"\"\"\n\n        item_enclosures = []  # Hard-coded enclosure list\n\n        # ITEM ENCLOSURE URL -- One of these three is required if you're\n        # publishing enclosures and you're not using ``item_enclosures``. The\n        # framework looks for them in this order.\n\n        def item_enclosure_url(self, item):\n            \"\"\"\n            Takes an item, as returned by items(), and returns the item's\n            enclosure URL.\n            \"\"\"\n\n        def item_enclosure_url(self):\n            \"\"\"\n            Returns the enclosure URL for every item in the feed.\n            \"\"\"\n\n        item_enclosure_url = \"/foo/bar.mp3\" # Hard-coded enclosure link.\n\n        # ITEM ENCLOSURE LENGTH -- One of these three is required if you're\n        # publishing enclosures and you're not using ``item_enclosures``. The\n        # framework looks for them in this order. In each case, the returned\n        # value should be either an integer, or a string representation of the\n        # integer, in bytes.\n\n        def item_enclosure_length(self, item):\n            \"\"\"\n            Takes an item, as returned by items(), and returns the item's\n            enclosure length.\n            \"\"\"\n\n        def item_enclosure_length(self):\n            \"\"\"\n            Returns the enclosure length for every item in the feed.\n            \"\"\"\n\n        item_enclosure_length = 32000 # Hard-coded enclosure length.\n\n        # ITEM ENCLOSURE MIME TYPE -- One of these three is required if you're\n        # publishing enclosures and you're not using ``item_enclosures``. The\n        # framework looks for them in this order.\n\n        def item_enclosure_mime_type(self, item):\n            \"\"\"\n            Takes an item, as returned by items(), and returns the item's\n            enclosure MIME type.\n            \"\"\"\n\n        def item_enclosure_mime_type(self):\n            \"\"\"\n            Returns the enclosure MIME type for every item in the feed.\n            \"\"\"\n\n        item_enclosure_mime_type = \"audio/mpeg\" # Hard-coded enclosure MIME type.\n\n        # ITEM PUBDATE -- It's optional to use one of these three. This is a\n        # hook that specifies how to get the pubdate for a given item.\n        # In each case, the method/attribute should return a Python\n        # datetime.datetime object.\n\n        def item_pubdate(self, item):\n            \"\"\"\n            Takes an item, as returned by items(), and returns the item's\n            pubdate.\n            \"\"\"\n\n        def item_pubdate(self):\n            \"\"\"\n            Returns the pubdate for every item in the feed.\n            \"\"\"\n\n        item_pubdate = datetime.datetime(2005, 5, 3) # Hard-coded pubdate.\n\n        # ITEM UPDATED -- It's optional to use one of these three. This is a\n        # hook that specifies how to get the updateddate for a given item.\n        # In each case, the method/attribute should return a Python\n        # datetime.datetime object.\n\n        def item_updateddate(self, item):\n            \"\"\"\n            Takes an item, as returned by items(), and returns the item's\n            updateddate.\n            \"\"\"\n\n        def item_updateddate(self):\n            \"\"\"\n            Returns the updateddate for every item in the feed.\n            \"\"\"\n\n        item_updateddate = datetime.datetime(2005, 5, 3) # Hard-coded updateddate.\n\n        # ITEM CATEGORIES -- It's optional to use one of these three. This is\n        # a hook that specifies how to get the list of categories for a given\n        # item. In each case, the method/attribute should return an iterable\n        # object that returns strings.\n\n        def item_categories(self, item):\n            \"\"\"\n            Takes an item, as returned by items(), and returns the item's\n            categories.\n            \"\"\"\n\n        def item_categories(self):\n            \"\"\"\n            Returns the categories for every item in the feed.\n            \"\"\"\n\n        item_categories = (\"python\", \"django\") # Hard-coded categories.\n\n        # ITEM COPYRIGHT NOTICE (only applicable to Atom feeds) -- One of the\n        # following three is optional. The framework looks for them in this\n        # order.\n\n        def item_copyright(self, obj):\n            \"\"\"\n            Takes an item, as returned by items(), and returns the item's\n            copyright notice as a normal Python string.\n            \"\"\"\n\n        def item_copyright(self):\n            \"\"\"\n            Returns the copyright notice for every item in the feed.\n            \"\"\"\n\n        item_copyright = 'Copyright (c) 2007, Sally Smith' # Hard-coded copyright notice.\n\n\nThe low-level framework\n=======================\n\nBehind the scenes, the high-level RSS framework uses a lower-level framework\nfor generating feeds' XML. This framework lives in a single module:\n:source:`django/utils/feedgenerator.py`.\n\nYou use this framework on your own, for lower-level feed generation. You can\nalso create custom feed generator subclasses for use with the ``feed_type``\n``Feed`` option.\n\n.. currentmodule:: django.utils.feedgenerator\n\n``SyndicationFeed`` classes\n---------------------------\n\nThe :mod:`~django.utils.feedgenerator` module contains a base class:\n\n* :class:`django.utils.feedgenerator.SyndicationFeed`\n\nand several subclasses:\n\n* :class:`django.utils.feedgenerator.RssUserland091Feed`\n* :class:`django.utils.feedgenerator.Rss201rev2Feed`\n* :class:`django.utils.feedgenerator.Atom1Feed`\n\nEach of these three classes knows how to render a certain type of feed as XML.\nThey share this interface:\n\n:meth:`.SyndicationFeed.__init__`\n    Initialize the feed with the given dictionary of metadata, which applies to\n    the entire feed. Required keyword arguments are:\n\n    * ``title``\n    * ``link``\n    * ``description``\n\n    There's also a bunch of other optional keywords:\n\n    * ``language``\n    * ``author_email``\n    * ``author_name``\n    * ``author_link``\n    * ``subtitle``\n    * ``categories``\n    * ``feed_url``\n    * ``feed_copyright``\n    * ``feed_guid``\n    * ``ttl``\n\n    Any extra keyword arguments you pass to ``__init__`` will be stored in\n    ``self.feed`` for use with `custom feed generators`_.\n\n    All parameters should be strings, except ``categories``, which should be a\n    sequence of strings. Beware that some control characters\n    are `not allowed <https://www.w3.org/International/questions/qa-controls>`_\n    in XML documents. If your content has some of them, you might encounter a\n    :exc:`ValueError` when producing the feed.\n\n:meth:`.SyndicationFeed.add_item`\n    Add an item to the feed with the given parameters.\n\n    Required keyword arguments are:\n\n    * ``title``\n    * ``link``\n    * ``description``\n\n    Optional keyword arguments are:\n\n    * ``author_email``\n    * ``author_name``\n    * ``author_link``\n    * ``pubdate``\n    * ``comments``\n    * ``unique_id``\n    * ``enclosures``\n    * ``categories``\n    * ``item_copyright``\n    * ``ttl``\n    * ``updateddate``\n\n    Extra keyword arguments will be stored for `custom feed generators`_.\n\n    All parameters, if given, should be strings, except:\n\n    * ``pubdate`` should be a Python  :class:`~datetime.datetime` object.\n    * ``updateddate`` should be a Python  :class:`~datetime.datetime` object.\n    * ``enclosures`` should be a list of\n      :class:`django.utils.feedgenerator.Enclosure` instances.\n    * ``categories`` should be a sequence of strings.\n\n:meth:`.SyndicationFeed.write`\n    Outputs the feed in the given encoding to outfile, which is a file-like object.\n\n:meth:`.SyndicationFeed.writeString`\n    Returns the feed as a string in the given encoding.\n\nFor example, to create an Atom 1.0 feed and print it to standard output::\n\n    >>> from django.utils import feedgenerator\n    >>> from datetime import datetime\n    >>> f = feedgenerator.Atom1Feed(\n    ...     title=\"My Weblog\",\n    ...     link=\"https://www.example.com/\",\n    ...     description=\"In which I write about what I ate today.\",\n    ...     language=\"en\",\n    ...     author_name=\"Myself\",\n    ...     feed_url=\"https://example.com/atom.xml\")\n    >>> f.add_item(title=\"Hot dog today\",\n    ...     link=\"https://www.example.com/entries/1/\",\n    ...     pubdate=datetime.now(),\n    ...     description=\"<p>Today I had a Vienna Beef hot dog. It was pink, plump and perfect.</p>\")\n    >>> print(f.writeString('UTF-8'))\n    <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n    <feed xmlns=\"http://www.w3.org/2005/Atom\" xml:lang=\"en\">\n    ...\n    </feed>\n\n.. currentmodule:: django.contrib.syndication\n\nCustom feed generators\n----------------------\n\nIf you need to produce a custom feed format, you've got a couple of options.\n\nIf the feed format is totally custom, you'll want to subclass\n``SyndicationFeed`` and completely replace the ``write()`` and\n``writeString()`` methods.\n\nHowever, if the feed format is a spin-off of RSS or Atom (i.e. GeoRSS_, Apple's\n`iTunes podcast format`_, etc.), you've got a better choice. These types of\nfeeds typically add extra elements and/or attributes to the underlying format,\nand there are a set of methods that ``SyndicationFeed`` calls to get these extra\nattributes. Thus, you can subclass the appropriate feed generator class\n(``Atom1Feed`` or ``Rss201rev2Feed``) and extend these callbacks. They are:\n\n.. _georss: http://georss.org/\n.. _itunes podcast format: https://help.apple.com/itc/podcasts_connect/#/itcb54353390\n\n``SyndicationFeed.root_attributes(self)``\n    Return a ``dict`` of attributes to add to the root feed element\n    (``feed``/``channel``).\n\n``SyndicationFeed.add_root_elements(self, handler)``\n    Callback to add elements inside the root feed element\n    (``feed``/``channel``). ``handler`` is an\n    :class:`~xml.sax.saxutils.XMLGenerator` from Python's built-in SAX library;\n    you'll call methods on it to add to the XML document in process.\n\n``SyndicationFeed.item_attributes(self, item)``\n    Return a ``dict`` of attributes to add to each item (``item``/``entry``)\n    element. The argument, ``item``, is a dictionary of all the data passed to\n    ``SyndicationFeed.add_item()``.\n\n``SyndicationFeed.add_item_elements(self, handler, item)``\n    Callback to add elements to each item (``item``/``entry``) element.\n    ``handler`` and ``item`` are as above.\n\n.. warning::\n\n    If you override any of these methods, be sure to call the superclass methods\n    since they add the required elements for each feed format.\n\nFor example, you might start implementing an iTunes RSS feed generator like so::\n\n    class iTunesFeed(Rss201rev2Feed):\n        def root_attributes(self):\n            attrs = super().root_attributes()\n            attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'\n            return attrs\n\n        def add_root_elements(self, handler):\n            super().add_root_elements(handler)\n            handler.addQuickElement('itunes:explicit', 'clean')\n\nThere's a lot more work to be done for a complete custom feed class, but the\nabove example should demonstrate the basic idea.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":108,"nodeType":"Package","repoName":null,"name":"docs/ref/contrib/gis","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":109,"nodeType":"TextFile","repoName":null,"name":"ogrinspect.txt","path":"docs/ref/contrib/gis","text":"==============\nOGR Inspection\n==============\n\n.. module:: django.contrib.gis.utils.ogrinspect\n    :synopsis: Utilities for inspecting OGR data sources.\n\n.. currentmodule:: django.contrib.gis.utils\n\n``ogrinspect``\n==============\n\n.. function:: ogrinspect(data_source, model_name, **kwargs)\n    :noindex:\n\n``mapping``\n===========\n\n.. function:: mapping(data_source, geom_name='geom', layer_key=0, multi_geom=False)\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":110,"nodeType":"TextFile","repoName":null,"name":"utils.txt","path":"docs/ref/contrib/gis","text":"===================\nGeoDjango Utilities\n===================\n\n.. module:: django.contrib.gis.utils\n    :synopsis: GeoDjango's collection of utilities.\n\nThe :mod:`django.contrib.gis.utils` module contains various utilities that are\nuseful in creating geospatial Web applications.\n\n.. toctree::\n    :maxdepth: 2\n\n    layermapping\n    ogrinspect\n    serializers\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":111,"nodeType":"TextFile","repoName":null,"name":"deployment.txt","path":"docs/ref/contrib/gis","text":"===================\nDeploying GeoDjango\n===================\n\nBasically, the deployment of a GeoDjango application is not different from\nthe deployment of a normal Django application. Please consult Django's\n:doc:`deployment documentation </howto/deployment/index>`.\n\n.. warning::\n\n    GeoDjango uses the GDAL geospatial library which is\n    not thread safe at this time.  Thus, it is *highly* recommended\n    to not use threading when deploying -- in other words, use an\n    appropriate configuration of Apache.\n\n    For example, when configuring your application with ``mod_wsgi``,\n    set the ``WSGIDaemonProcess`` attribute ``threads`` to ``1``, unless\n    Apache may crash when running your GeoDjango application.  Increase the\n    number of ``processes`` instead.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":112,"nodeType":"TextFile","repoName":null,"name":"feeds.txt","path":"docs/ref/contrib/gis","text":"================\nGeographic Feeds\n================\n\n.. module:: django.contrib.gis.feeds\n    :synopsis: GeoDjango's framework for generating spatial feeds.\n\nGeoDjango has its own :class:`Feed` subclass that may embed location information\nin RSS/Atom feeds formatted according to either the `Simple GeoRSS`__ or\n`W3C Geo`_ standards.  Because GeoDjango's syndication API is a superset of\nDjango's, please consult :doc:`Django's syndication documentation\n</ref/contrib/syndication>` for details on general usage.\n\n.. _W3C Geo: https://www.w3.org/2003/01/geo/\n\n__ http://georss.org/simple.html\n\nExample\n=======\n\nAPI Reference\n=============\n\n``Feed`` Subclass\n-----------------\n\n.. class:: Feed\n\n    In addition to methods provided by the\n    :class:`django.contrib.syndication.views.Feed` base class, GeoDjango's\n    ``Feed`` class provides the following overrides. Note that these overrides\n    may be done in multiple ways::\n\n        from django.contrib.gis.feeds import Feed\n\n        class MyFeed(Feed):\n\n            # First, as a class attribute.\n            geometry = ...\n            item_geometry = ...\n\n            # Also a function with no arguments\n            def geometry(self):\n                ...\n\n            def item_geometry(self):\n                ...\n\n            # And as a function with a single argument\n            def geometry(self, obj):\n                ...\n\n            def item_geometry(self, item):\n                ...\n\n    .. method:: geometry(obj)\n\n    Takes the object returned by ``get_object()`` and returns the *feed's*\n    geometry. Typically this is a ``GEOSGeometry`` instance, or can be a tuple\n    to represent a point or a box. For example::\n\n        class ZipcodeFeed(Feed):\n\n            def geometry(self, obj):\n                # Can also return: `obj.poly`, and `obj.poly.centroid`.\n                return obj.poly.extent # tuple like: (X0, Y0, X1, Y1).\n\n    .. method:: item_geometry(item)\n\n    Set this to return the geometry for each *item* in the feed. This can be a\n    ``GEOSGeometry`` instance, or a tuple that represents a point coordinate or\n    bounding box. For example::\n\n        class ZipcodeFeed(Feed):\n\n            def item_geometry(self, obj):\n                # Returns the polygon.\n                return obj.poly\n\n``SyndicationFeed`` Subclasses\n------------------------------\n\nThe following :class:`django.utils.feedgenerator.SyndicationFeed` subclasses\nare available:\n\n.. class:: GeoRSSFeed\n\n.. class:: GeoAtom1Feed\n\n.. class:: W3CGeoFeed\n\n.. note::\n\n    `W3C Geo`_ formatted feeds only support\n    :class:`~django.contrib.gis.db.models.PointField` geometries.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":113,"nodeType":"TextFile","repoName":null,"name":"serializers.txt","path":"docs/ref/contrib/gis","text":"======================\n``GeoJSON`` Serializer\n======================\n\n.. module:: django.contrib.gis.serializers.geojson\n    :synopsis: Serialization of GeoDjango models in the GeoJSON format.\n\nGeoDjango provides a specific serializer for the `GeoJSON`__ format. See\n:doc:`/topics/serialization` for more information on serialization.\n\n__ https://geojson.org/\n\nThe ``geojson`` serializer is not meant for round-tripping data, as it has no\ndeserializer equivalent. For example, you cannot use :djadmin:`loaddata` to\nreload the output produced by this serializer. If you plan to reload the\noutputted data, use the plain :ref:`json serializer <serialization-formats-json>`\ninstead.\n\nIn addition to the options of the ``json`` serializer, the ``geojson``\nserializer accepts the following additional option when it is called by\n``serializers.serialize()``:\n\n* ``geometry_field``: A string containing the name of a geometry field to use\n  for the ``geometry`` key of the GeoJSON feature. This is only needed when you\n  have a model with more than one geometry field and you don't want to use the\n  first defined geometry field (by default, the first geometry field is picked).\n\n* ``srid``: The SRID to use for the ``geometry`` content. Defaults to 4326\n  (WGS 84).\n\nThe :ref:`fields <subset-of-fields>` option can be used to limit fields that\nwill be present in the ``properties`` key, as it works with all other\nserializers.\n\nExample::\n\n    from django.core.serializers import serialize\n    from my_app.models import City\n\n    serialize('geojson', City.objects.all(),\n              geometry_field='point',\n              fields=('name',))\n\nWould output::\n\n    {\n      'type': 'FeatureCollection',\n      'crs': {\n        'type': 'name',\n        'properties': {'name': 'EPSG:4326'}\n      },\n      'features': [\n        {\n          'type': 'Feature',\n          'geometry': {\n            'type': 'Point',\n            'coordinates': [-87.650175, 41.850385]\n          },\n          'properties': {\n            'name': 'Chicago'\n          }\n        }\n      ]\n    }\n\nWhen the ``fields`` parameter is not specified, the ``geojson`` serializer adds\na ``pk`` key to the ``properties`` dictionary with the primary key of the\nobject as the value.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":114,"nodeType":"TextFile","repoName":null,"name":"sitemaps.txt","path":"docs/ref/contrib/gis","text":"===================\nGeographic Sitemaps\n===================\n\nKML is an XML language focused on geographic visualization [#]_. ``KMLSitemap``\nand its compressed counterpart ``KMZSitemap`` allow you to present geolocated\ndata in a machine-readable format.\n\nExample\n=======\n\nReference\n=========\n\n``KMLSitemap``\n--------------\n\n``KMZSitemap``\n--------------\n\n.. rubric:: Footnotes\n.. [#] https://www.opengeospatial.org/standards/kml\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":115,"nodeType":"TextFile","repoName":null,"name":"admin.txt","path":"docs/ref/contrib/gis","text":"======================\nGeoDjango's admin site\n======================\n\n.. module:: django.contrib.gis.admin\n    :synopsis: GeoDjango's extensions to the admin site.\n\n``GeoModelAdmin``\n=================\n\n.. class:: GeoModelAdmin\n\n    .. attribute:: default_lon\n\n    The default center longitude.\n\n    .. attribute:: default_lat\n\n    The default center latitude.\n\n    .. attribute:: default_zoom\n\n    The default zoom level to use.  Defaults to 4.\n\n    .. attribute:: extra_js\n\n    Sequence of URLs to any extra JavaScript to include.\n\n    .. attribute:: map_template\n\n    Override the template used to generate the JavaScript slippy map.\n    Default is ``'gis/admin/openlayers.html'``.\n\n    .. attribute:: map_width\n\n    Width of the map, in pixels.  Defaults to 600.\n\n    .. attribute:: map_height\n\n    Height of the map, in pixels.  Defaults to 400.\n\n    .. attribute:: openlayers_url\n\n    Link to the URL of the OpenLayers JavaScript.  Defaults to\n    ``'https://cdnjs.cloudflare.com/ajax/libs/openlayers/2.13.1/OpenLayers.js'``.\n\n    .. attribute:: modifiable\n\n    Defaults to ``True``.  When set to ``False``, disables editing of\n    existing geometry fields in the admin.\n\n    .. note::\n\n        This is different from adding the geometry field to\n        :attr:`~django.contrib.admin.ModelAdmin.readonly_fields`,\n        which will only display the WKT of the geometry. Setting\n        ``modifiable=False``, actually displays the geometry in a map,\n        but disables the ability to edit its vertices.\n\n``OSMGeoAdmin``\n===============\n\n.. class:: OSMGeoAdmin\n\n    A subclass of :class:`GeoModelAdmin` that uses a Spherical Mercator projection\n    with `OpenStreetMap <https://www.openstreetmap.org/>`_ street data tiles.\n    See the :ref:`OSMGeoAdmin introduction <osmgeoadmin-intro>`\n    in the tutorial for a usage example.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":116,"nodeType":"TextFile","repoName":null,"name":"geoip2.txt","path":"docs/ref/contrib/gis","text":"=======================\nGeolocation with GeoIP2\n=======================\n\n.. module:: django.contrib.gis.geoip2\n    :synopsis: Python interface for MaxMind's GeoIP2 databases.\n\nThe :class:`GeoIP2` object is a wrapper for the `MaxMind geoip2 Python\nlibrary`__. [#]_\n\nIn order to perform IP-based geolocation, the :class:`GeoIP2` object requires\nthe `geoip2 Python library`__ and the GeoIP ``Country`` and/or ``City``\n`datasets in binary format`__ (the CSV files will not work!). Grab the\n``GeoLite2-Country.mmdb.gz`` and ``GeoLite2-City.mmdb.gz`` files and unzip them\nin a directory corresponding to the :setting:`GEOIP_PATH` setting.\n\nAdditionally, it is recommended to install the `libmaxminddb C library`__, so\nthat ``geoip2`` can leverage the C library's faster speed.\n\n__ https://geoip2.readthedocs.io/\n__ https://pypi.org/project/geoip2/\n__ https://dev.maxmind.com/geoip/geoip2/geolite2/\n__ https://github.com/maxmind/libmaxminddb\n\nExample\n=======\n\nHere is an example of its usage::\n\n    >>> from django.contrib.gis.geoip2 import GeoIP2\n    >>> g = GeoIP2()\n    >>> g.country('google.com')\n    {'country_code': 'US', 'country_name': 'United States'}\n    >>> g.city('72.14.207.99')\n    {'city': 'Mountain View',\n    'continent_code': 'NA',\n    'continent_name': 'North America',\n    'country_code': 'US',\n    'country_name': 'United States',\n    'dma_code': 807,\n    'is_in_european_union': False,\n    'latitude': 37.419200897216797,\n    'longitude': -122.05740356445312,\n    'postal_code': '94043',\n    'region': 'CA',\n    'time_zone': 'America/Los_Angeles'}\n    >>> g.lat_lon('salon.com')\n    (39.0437, -77.4875)\n    >>> g.lon_lat('uh.edu')\n    (-95.4342, 29.834)\n    >>> g.geos('24.124.1.80').wkt\n    'POINT (-97 38)'\n\nAPI Reference\n=============\n\n.. class:: GeoIP2(path=None, cache=0, country=None, city=None)\n\nThe ``GeoIP`` object does not require any parameters to use the default\nsettings. However, at the very least the :setting:`GEOIP_PATH` setting\nshould be set with the path of the location of your GeoIP datasets. The\nfollowing initialization keywords may be used to customize any of the\ndefaults.\n\n===================  =======================================================\nKeyword Arguments    Description\n===================  =======================================================\n``path``             Base directory to where GeoIP data is located or the\n                     full path to where the city or country data files\n                     (``.mmdb``) are located. Assumes that both the city and\n                     country datasets are located in this directory;\n                     overrides the :setting:`GEOIP_PATH` setting.\n\n``cache``            The cache settings when opening up the GeoIP datasets. May\n                     be an integer in (0, 1, 2, 4, 8) corresponding to the\n                     ``MODE_AUTO``, ``MODE_MMAP_EXT``, ``MODE_MMAP``, and\n                     ``GEOIP_INDEX_CACHE`` ``MODE_MEMORY`` C API settings,\n                     respectively. Defaults to 0 (``MODE_AUTO``).\n\n``country``          The name of the GeoIP country data file. Defaults\n                     to ``GeoLite2-Country.mmdb``. Setting this keyword\n                     overrides the :setting:`GEOIP_COUNTRY` setting.\n\n``city``             The name of the GeoIP city data file. Defaults to\n                     ``GeoLite2-City.mmdb``. Setting this keyword overrides\n                     the :setting:`GEOIP_CITY` setting.\n===================  =======================================================\n\nMethods\n=======\n\nInstantiating\n-------------\n\n.. classmethod:: GeoIP2.open(path, cache)\n\nThis classmethod instantiates the GeoIP object from the given database path\nand given cache setting.\n\nQuerying\n--------\n\nAll the following querying routines may take either a string IP address\nor a fully qualified domain name (FQDN). For example, both\n``'205.186.163.125'`` and ``'djangoproject.com'`` would be valid query\nparameters.\n\n.. method:: GeoIP2.city(query)\n\nReturns a dictionary of city information for the given query. Some\nof the values in the dictionary may be undefined (``None``).\n\n.. method:: GeoIP2.country(query)\n\nReturns a dictionary with the country code and country for the given\nquery.\n\n.. method:: GeoIP2.country_code(query)\n\nReturns the country code corresponding to the query.\n\n.. method:: GeoIP2.country_name(query)\n\nReturns the country name corresponding to the query.\n\nCoordinate Retrieval\n--------------------\n\n.. method:: GeoIP2.coords(query)\n\nReturns a coordinate tuple of (longitude, latitude).\n\n.. method:: GeoIP2.lon_lat(query)\n\nReturns a coordinate tuple of (longitude, latitude).\n\n.. method:: GeoIP2.lat_lon(query)\n\nReturns a coordinate tuple of (latitude, longitude),\n\n.. method:: GeoIP2.geos(query)\n\nReturns a :class:`~django.contrib.gis.geos.Point` object corresponding to the\nquery.\n\nSettings\n========\n\n.. setting:: GEOIP_PATH\n\n``GEOIP_PATH``\n--------------\n\nA string or :class:`pathlib.Path` specifying the directory where the GeoIP data\nfiles are located. This setting is *required* unless manually specified\nwith ``path`` keyword when initializing the :class:`GeoIP2` object.\n\n.. setting:: GEOIP_COUNTRY\n\n``GEOIP_COUNTRY``\n-----------------\n\nThe basename to use for the GeoIP country data file. Defaults to\n``'GeoLite2-Country.mmdb'``.\n\n.. setting:: GEOIP_CITY\n\n``GEOIP_CITY``\n--------------\n\nThe basename to use for the GeoIP city data file. Defaults to\n``'GeoLite2-City.mmdb'``.\n\nExceptions\n==========\n\n.. exception:: GeoIP2Exception\n\n    The exception raised when an error occurs in a call to the underlying\n    ``geoip2`` library.\n\n.. rubric:: Footnotes\n.. [#] GeoIP(R) is a registered trademark of MaxMind, Inc.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":117,"nodeType":"TextFile","repoName":null,"name":"measure.txt","path":"docs/ref/contrib/gis","text":"===================\nMeasurement Objects\n===================\n\n.. module:: django.contrib.gis.measure\n    :synopsis: GeoDjango's distance and area measurement objects.\n\nThe :mod:`django.contrib.gis.measure` module contains objects that allow\nfor convenient representation of distance and area units of measure. [#]_\nSpecifically, it implements two objects, :class:`Distance` and\n:class:`Area` -- both of which may be accessed via the\n:class:`D` and :class:`A` convenience aliases, respectively.\n\nExample\n=======\n\n:class:`Distance` objects may be instantiated using a keyword argument indicating the\ncontext of the units.  In the example below, two different distance objects are\ninstantiated in units of kilometers (``km``) and miles (``mi``)::\n\n    >>> from django.contrib.gis.measure import D, Distance\n    >>> d1 = Distance(km=5)\n    >>> print(d1)\n    5.0 km\n    >>> d2 = D(mi=5) # `D` is an alias for `Distance`\n    >>> print(d2)\n    5.0 mi\n\nFor conversions, access the preferred unit attribute to get a converted\ndistance quantity::\n\n    >>> print(d1.mi) # Converting 5 kilometers to miles\n    3.10685596119\n    >>> print(d2.km) # Converting 5 miles to kilometers\n    8.04672\n\nMoreover, arithmetic operations may be performed between the distance\nobjects::\n\n    >>> print(d1 + d2) # Adding 5 miles to 5 kilometers\n    13.04672 km\n    >>> print(d2 - d1) # Subtracting 5 kilometers from 5 miles\n    1.89314403881 mi\n\nTwo :class:`Distance` objects multiplied together will yield an :class:`Area`\nobject, which uses squared units of measure::\n\n    >>> a = d1 * d2 # Returns an Area object.\n    >>> print(a)\n    40.2336 sq_km\n\nTo determine what the attribute abbreviation of a unit is, the ``unit_attname``\nclass method may be used::\n\n    >>> print(Distance.unit_attname('US Survey Foot'))\n    survey_ft\n    >>> print(Distance.unit_attname('centimeter'))\n    cm\n\n.. _supported_units:\n\nSupported units\n===============\n\n=================================  ========================================\nUnit Attribute                     Full name or alias(es)\n=================================  ========================================\n``km``                             Kilometre, Kilometer\n``mi``                             Mile\n``m``                              Meter, Metre\n``yd``                             Yard\n``ft``                             Foot, Foot (International)\n``survey_ft``                      U.S. Foot, US survey foot\n``inch``                           Inches\n``cm``                             Centimeter\n``mm``                             Millimetre, Millimeter\n``um``                             Micrometer, Micrometre\n``british_ft``                     British foot (Sears 1922)\n``british_yd``                     British yard (Sears 1922)\n``british_chain_sears``            British chain (Sears 1922)\n``indian_yd``                      Indian yard, Yard (Indian)\n``sears_yd``                       Yard (Sears)\n``clarke_ft``                      Clarke's Foot\n``chain``                          Chain\n``chain_benoit``                   Chain (Benoit)\n``chain_sears``                    Chain (Sears)\n``british_chain_benoit``           British chain (Benoit 1895 B)\n``british_chain_sears_truncated``  British chain (Sears 1922 truncated)\n``gold_coast_ft``                  Gold Coast foot\n``link``                           Link\n``link_benoit``                    Link (Benoit)\n``link_sears``                     Link (Sears)\n``clarke_link``                    Clarke's link\n``fathom``                         Fathom\n``rod``                            Rod\n``furlong``                        Furlong, Furrow Long\n``nm``                             Nautical Mile\n``nm_uk``                          Nautical Mile (UK)\n``german_m``                       German legal metre\n=================================  ========================================\n\n.. note::\n\n    :class:`Area` attributes are the same as :class:`Distance` attributes,\n    except they are prefixed with ``sq_`` (area units are square in nature).\n    For example, ``Area(sq_m=2)`` creates an :class:`Area` object\n    representing two square meters.\n\nMeasurement API\n===============\n\n``Distance``\n------------\n\n.. class:: Distance(**kwargs)\n\n    To initialize a distance object, pass in a keyword corresponding to the\n    desired :ref:`unit attribute name <supported_units>` set with desired\n    value. For example, the following creates a distance object representing 5\n    miles::\n\n        >>> dist = Distance(mi=5)\n\n    .. method:: __getattr__(unit_att)\n\n    Returns the distance value in units corresponding to the given unit\n    attribute. For example::\n\n        >>> print(dist.km)\n        8.04672\n\n    .. classmethod:: unit_attname(unit_name)\n\n    Returns the distance unit attribute name for the given full unit name. For\n    example::\n\n        >>> Distance.unit_attname('Mile')\n        'mi'\n\n.. class:: D\n\n    Alias for :class:`Distance` class.\n\n``Area``\n--------\n\n.. class:: Area(**kwargs)\n\n    To initialize an area object, pass in a keyword corresponding to the\n    desired :ref:`unit attribute name <supported_units>` set with desired\n    value. For example, the following creates an area object representing 5\n    square miles::\n\n        >>> a = Area(sq_mi=5)\n\n    .. method:: __getattr__(unit_att)\n\n    Returns the area value in units corresponding to the given unit attribute.\n    For example::\n\n        >>> print(a.sq_km)\n        12.949940551680001\n\n    .. classmethod:: unit_attname(unit_name)\n\n    Returns the area unit attribute name for the given full unit name. For\n    example::\n\n        >>> Area.unit_attname('Kilometer')\n        'sq_km'\n\n.. class:: A\n\n    Alias for :class:`Area` class.\n\n.. rubric:: Footnotes\n.. [#] `Robert Coup <https://koordinates.com/>`_ is the initial author of the measure objects,\n       and was inspired by Brian Beck's work in `geopy <https://github.com/geopy/geopy/>`_\n       and Geoff Biggs' PhD work on dimensioned units for robotics.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":118,"nodeType":"TextFile","repoName":null,"name":"testing.txt","path":"docs/ref/contrib/gis","text":"======================\nTesting GeoDjango apps\n======================\n\nIncluded in this documentation are some additional notes and settings\nfor :ref:`testing-postgis` users.\n\n.. _testing-postgis:\n\nPostGIS\n=======\n\nSettings\n--------\n\n.. note::\n\n    The settings below have sensible defaults, and shouldn't require manual setting.\n\n.. setting:: POSTGIS_VERSION\n\n``POSTGIS_VERSION``\n~~~~~~~~~~~~~~~~~~~\n\nWhen GeoDjango's spatial backend initializes on PostGIS, it has to perform\nan SQL query to determine the version in order to figure out what\nfeatures are available. Advanced users wishing to prevent this additional\nquery may set the version manually using a 3-tuple of integers specifying\nthe major, minor, and micro version numbers for PostGIS. For example,\nto configure for PostGIS X.Y.Z you would use::\n\n    POSTGIS_VERSION = (X, Y, Z)\n\nObtaining sufficient privileges\n-------------------------------\n\nDepending on your configuration, this section describes several methods to\nconfigure a database user with sufficient privileges to run tests for\nGeoDjango applications on PostgreSQL. If your\n:ref:`spatial database template <spatialdb_template>`\nwas created like in the instructions, then your testing database user\nonly needs to have the ability to create databases. In other configurations,\nyou may be required to use a database superuser.\n\nCreate database user\n~~~~~~~~~~~~~~~~~~~~\n\nTo make a database user with the ability to create databases, use the\nfollowing command::\n\n    $ createuser --createdb -R -S <user_name>\n\nThe ``-R -S`` flags indicate that we do not want the user to have the ability\nto create additional users (roles) or to be a superuser, respectively.\n\nAlternatively, you may alter an existing user's role from the SQL shell\n(assuming this is done from an existing superuser account)::\n\n    postgres# ALTER ROLE <user_name> CREATEDB NOSUPERUSER NOCREATEROLE;\n\nCreate database superuser\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThis may be done at the time the user is created, for example::\n\n    $ createuser --superuser <user_name>\n\nOr you may alter the user's role from the SQL shell (assuming this\nis done from an existing superuser account)::\n\n    postgres# ALTER ROLE <user_name> SUPERUSER;\n\nWindows\n-------\n\nOn Windows platforms you can use the pgAdmin III utility to add superuser\nprivileges to your database user.\n\nBy default, the PostGIS installer on Windows includes a template\nspatial database entitled ``template_postgis``.\n\n.. _geodjango-tests:\n\nGeoDjango tests\n===============\n\nTo have the GeoDjango tests executed when :ref:`running the Django test suite\n<running-unit-tests>` with ``runtests.py`` all of the databases in the settings\nfile must be using one of the :ref:`spatial database backends\n<spatial-backends>`.\n\n\nExample\n-------\n\nThe following is an example bare-bones settings file with spatial backends\nthat can be used to run the entire Django test suite, including those\nin :mod:`django.contrib.gis`::\n\n    DATABASES = {\n        'default': {\n            'ENGINE': 'django.contrib.gis.db.backends.postgis',\n            'NAME': 'geodjango',\n            'USER': 'geodjango',\n        },\n        'other': {\n            'ENGINE': 'django.contrib.gis.db.backends.postgis',\n            'NAME': 'other',\n            'USER': 'geodjango',\n        },\n    }\n\n    SECRET_KEY = 'django_tests_secret_key'\n\nAssuming the settings above were in a ``postgis.py`` file in the same\ndirectory as ``runtests.py``, then all Django and GeoDjango tests would\nbe performed when executing the command::\n\n    $ ./runtests.py --settings=postgis\n\nTo run only the GeoDjango test suite, specify ``gis_tests``::\n\n    $ ./runtests.py --settings=postgis gis_tests\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":119,"nodeType":"TextFile","repoName":null,"name":"forms-api.txt","path":"docs/ref/contrib/gis","text":"===================\nGeoDjango Forms API\n===================\n\n.. module:: django.contrib.gis.forms\n    :synopsis: GeoDjango forms API.\n\nGeoDjango provides some specialized form fields and widgets in order to visually\ndisplay and edit geolocalized data on a map. By default, they use\n`OpenLayers`_-powered maps, with a base WMS layer provided by `NASA`_.\n\n.. _OpenLayers: https://openlayers.org/\n.. _NASA: https://earthdata.nasa.gov/\n\nField arguments\n===============\nIn addition to the regular :ref:`form field arguments <core-field-arguments>`,\nGeoDjango form fields take the following optional arguments.\n\n``srid``\n--------\n\n.. attribute:: Field.srid\n\n    This is the SRID code that the field value should be transformed to. For\n    example, if the map widget SRID is different from the SRID more generally\n    used by your application or database, the field will automatically convert\n    input values into that SRID.\n\n``geom_type``\n-------------\n\n.. attribute:: Field.geom_type\n\n    You generally shouldn't have to set or change that attribute which should\n    be setup depending on the field class. It matches the OpenGIS standard\n    geometry name.\n\nForm field classes\n==================\n\n``GeometryField``\n-----------------\n\n.. class:: GeometryField\n\n``PointField``\n--------------\n\n.. class:: PointField\n\n``LineStringField``\n-------------------\n\n.. class:: LineStringField\n\n``PolygonField``\n----------------\n\n.. class:: PolygonField\n\n``MultiPointField``\n-------------------\n\n.. class:: MultiPointField\n\n``MultiLineStringField``\n------------------------\n\n.. class:: MultiLineStringField\n\n``MultiPolygonField``\n---------------------\n\n.. class:: MultiPolygonField\n\n``GeometryCollectionField``\n---------------------------\n\n.. class:: GeometryCollectionField\n\nForm widgets\n============\n\n.. module:: django.contrib.gis.forms.widgets\n    :synopsis: GeoDjango widgets API.\n\nGeoDjango form widgets allow you to display and edit geographic data on a\nvisual map.\nNote that none of the currently available widgets supports 3D geometries, hence\ngeometry fields will fallback using a ``Textarea`` widget for such data.\n\nWidget attributes\n-----------------\n\nGeoDjango widgets are template-based, so their attributes are mostly different\nfrom other Django widget attributes.\n\n\n.. attribute:: BaseGeometryWidget.geom_type\n\n    The OpenGIS geometry type, generally set by the form field.\n\n.. attribute:: BaseGeometryWidget.map_height\n.. attribute:: BaseGeometryWidget.map_width\n\n    Height and width of the widget map (default is 400x600).\n\n.. attribute:: BaseGeometryWidget.map_srid\n\n    SRID code used by the map (default is 4326).\n\n.. attribute:: BaseGeometryWidget.display_raw\n\n    Boolean value specifying if a textarea input showing the serialized\n    representation of the current geometry is visible, mainly for debugging\n    purposes (default is ``False``).\n\n.. attribute:: BaseGeometryWidget.supports_3d\n\n    Indicates if the widget supports edition of 3D data (default is ``False``).\n\n.. attribute:: BaseGeometryWidget.template_name\n\n    The template used to render the map widget.\n\nYou can pass widget attributes in the same manner that for any other Django\nwidget. For example::\n\n    from django.contrib.gis import forms\n\n    class MyGeoForm(forms.Form):\n        point = forms.PointField(widget=\n            forms.OSMWidget(attrs={'map_width': 800, 'map_height': 500}))\n\nWidget classes\n--------------\n\n``BaseGeometryWidget``\n\n.. class:: BaseGeometryWidget\n\n    This is an abstract base widget containing the logic needed by subclasses.\n    You cannot directly use this widget for a geometry field.\n    Note that the rendering of GeoDjango widgets is based on a template,\n    identified by the :attr:`template_name` class attribute.\n\n``OpenLayersWidget``\n\n.. class:: OpenLayersWidget\n\n    This is the default widget used by all GeoDjango form fields.\n    ``template_name`` is ``gis/openlayers.html``.\n\n    ``OpenLayersWidget`` and :class:`OSMWidget` use the ``openlayers.js`` file\n    hosted on the ``cdnjs.cloudflare.com`` content-delivery network. You can\n    subclass these widgets in order to specify your own version of the\n    ``OpenLayers.js`` file in the ``js`` property of the inner ``Media`` class\n    (see :ref:`assets-as-a-static-definition`).\n\n``OSMWidget``\n\n.. class:: OSMWidget\n\n    This widget uses an OpenStreetMap base layer to display geographic objects\n    on. Attributes are:\n\n    .. attribute:: template_name\n\n        ``gis/openlayers-osm.html``\n\n    .. attribute:: default_lat\n    .. attribute:: default_lon\n\n        The default center latitude and longitude are ``47`` and ``5``,\n        respectively, which is a location in eastern France.\n\n    .. attribute:: default_zoom\n\n        The default map zoom is ``12``.\n\n    The :class:`OpenLayersWidget` note about JavaScript file hosting above also\n    applies here. See also this `FAQ answer`_ about ``https`` access to map\n    tiles.\n\n    .. _FAQ answer: https://help.openstreetmap.org/questions/10920/how-to-embed-a-map-in-my-https-site\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":120,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/ref/contrib/gis","text":"=========\nGeoDjango\n=========\n\n.. module:: django.contrib.gis\n    :synopsis: Geographic Information System (GIS) extensions for Django\n\nGeoDjango intends to be a world-class geographic Web framework. Its goal is to\nmake it as easy as possible to build GIS Web applications and harness the power\nof spatially enabled data.\n\n.. toctree::\n    :maxdepth: 2\n\n    tutorial\n    install/index\n    model-api\n    db-api\n    forms-api\n    geoquerysets\n    functions\n    measure\n    geos\n    gdal\n    geoip2\n    utils\n    commands\n    admin\n    feeds\n    sitemaps\n    testing\n    deployment\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":121,"nodeType":"TextFile","repoName":null,"name":"instances.txt","path":"docs/ref/models","text":"========================\nModel instance reference\n========================\n\n.. currentmodule:: django.db.models\n\nThis document describes the details of the ``Model`` API. It builds on the\nmaterial presented in the :doc:`model </topics/db/models>` and :doc:`database\nquery </topics/db/queries>` guides, so you'll probably want to read and\nunderstand those documents before reading this one.\n\nThroughout this reference we'll use the :ref:`example Weblog models\n<queryset-model-example>` presented in the :doc:`database query guide\n</topics/db/queries>`.\n\nCreating objects\n================\n\nTo create a new instance of a model, instantiate it like any other Python\nclass:\n\n.. class:: Model(**kwargs)\n\nThe keyword arguments are the names of the fields you've defined on your model.\nNote that instantiating a model in no way touches your database; for that, you\nneed to :meth:`~Model.save()`.\n\n.. note::\n\n    You may be tempted to customize the model by overriding the ``__init__``\n    method. If you do so, however, take care not to change the calling\n    signature as any change may prevent the model instance from being saved.\n    Rather than overriding ``__init__``, try using one of these approaches:\n\n    #. Add a classmethod on the model class::\n\n        from django.db import models\n\n        class Book(models.Model):\n            title = models.CharField(max_length=100)\n\n            @classmethod\n            def create(cls, title):\n                book = cls(title=title)\n                # do something with the book\n                return book\n\n        book = Book.create(\"Pride and Prejudice\")\n\n    #. Add a method on a custom manager (usually preferred)::\n\n        class BookManager(models.Manager):\n            def create_book(self, title):\n                book = self.create(title=title)\n                # do something with the book\n                return book\n\n        class Book(models.Model):\n            title = models.CharField(max_length=100)\n\n            objects = BookManager()\n\n        book = Book.objects.create_book(\"Pride and Prejudice\")\n\nCustomizing model loading\n-------------------------\n\n.. classmethod:: Model.from_db(db, field_names, values)\n\nThe ``from_db()`` method can be used to customize model instance creation\nwhen loading from the database.\n\nThe ``db`` argument contains the database alias for the database the model\nis loaded from, ``field_names`` contains the names of all loaded fields, and\n``values`` contains the loaded values for each field in ``field_names``. The\n``field_names`` are in the same order as the ``values``. If all of the model's\nfields are present, then ``values`` are guaranteed to be in the order\n``__init__()`` expects them. That is, the instance can be created by\n``cls(*values)``. If any fields are deferred, they won't appear in\n``field_names``. In that case, assign a value of ``django.db.models.DEFERRED``\nto each of the missing fields.\n\nIn addition to creating the new model, the ``from_db()`` method must set the\n``adding`` and ``db`` flags in the new instance's ``_state`` attribute.\n\nBelow is an example showing how to record the initial values of fields that\nare loaded from the database::\n\n    from django.db.models import DEFERRED\n\n    @classmethod\n    def from_db(cls, db, field_names, values):\n        # Default implementation of from_db() (subject to change and could\n        # be replaced with super()).\n        if len(values) != len(cls._meta.concrete_fields):\n            values = list(values)\n            values.reverse()\n            values = [\n                values.pop() if f.attname in field_names else DEFERRED\n                for f in cls._meta.concrete_fields\n            ]\n        instance = cls(*values)\n        instance._state.adding = False\n        instance._state.db = db\n        # customization to store the original field values on the instance\n        instance._loaded_values = dict(zip(field_names, values))\n        return instance\n\n    def save(self, *args, **kwargs):\n        # Check how the current values differ from ._loaded_values. For example,\n        # prevent changing the creator_id of the model. (This example doesn't\n        # support cases where 'creator_id' is deferred).\n        if not self._state.adding and (\n                self.creator_id != self._loaded_values['creator_id']):\n            raise ValueError(\"Updating the value of creator isn't allowed\")\n        super().save(*args, **kwargs)\n\nThe example above shows a full ``from_db()`` implementation to clarify how that\nis done. In this case it would be possible to use a ``super()`` call in the\n``from_db()`` method.\n\nRefreshing objects from database\n================================\n\nIf you delete a field from a model instance, accessing it again reloads the\nvalue from the database::\n\n    >>> obj = MyModel.objects.first()\n    >>> del obj.field\n    >>> obj.field  # Loads the field from the database\n\n.. method:: Model.refresh_from_db(using=None, fields=None)\n\nIf you need to reload a model's values from the database, you can use the\n``refresh_from_db()`` method. When this method is called without arguments the\nfollowing is done:\n\n#. All non-deferred fields of the model are updated to the values currently\n   present in the database.\n#. Any cached relations are cleared from the reloaded instance.\n\nOnly fields of the model are reloaded from the database. Other\ndatabase-dependent values such as annotations aren't reloaded. Any\n:func:`@cached_property <django.utils.functional.cached_property>` attributes\naren't cleared either.\n\nThe reloading happens from the database the instance was loaded from, or from\nthe default database if the instance wasn't loaded from the database. The\n``using`` argument can be used to force the database used for reloading.\n\nIt is possible to force the set of fields to be loaded by using the ``fields``\nargument.\n\nFor example, to test that an ``update()`` call resulted in the expected\nupdate, you could write a test similar to this::\n\n    def test_update_result(self):\n        obj = MyModel.objects.create(val=1)\n        MyModel.objects.filter(pk=obj.pk).update(val=F('val') + 1)\n        # At this point obj.val is still 1, but the value in the database\n        # was updated to 2. The object's updated value needs to be reloaded\n        # from the database.\n        obj.refresh_from_db()\n        self.assertEqual(obj.val, 2)\n\nNote that when deferred fields are accessed, the loading of the deferred\nfield's value happens through this method. Thus it is possible to customize\nthe way deferred loading happens. The example below shows how one can reload\nall of the instance's fields when a deferred field is reloaded::\n\n    class ExampleModel(models.Model):\n        def refresh_from_db(self, using=None, fields=None, **kwargs):\n            # fields contains the name of the deferred field to be\n            # loaded.\n            if fields is not None:\n                fields = set(fields)\n                deferred_fields = self.get_deferred_fields()\n                # If any deferred field is going to be loaded\n                if fields.intersection(deferred_fields):\n                    # then load all of them\n                    fields = fields.union(deferred_fields)\n            super().refresh_from_db(using, fields, **kwargs)\n\n.. method:: Model.get_deferred_fields()\n\nA helper method that returns a set containing the attribute names of all those\nfields that are currently deferred for this model.\n\n.. _validating-objects:\n\nValidating objects\n==================\n\nThere are three steps involved in validating a model:\n\n1. Validate the model fields - :meth:`Model.clean_fields()`\n2. Validate the model as a whole - :meth:`Model.clean()`\n3. Validate the field uniqueness - :meth:`Model.validate_unique()`\n\nAll three steps are performed when you call a model's\n:meth:`~Model.full_clean()` method.\n\nWhen you use a :class:`~django.forms.ModelForm`, the call to\n:meth:`~django.forms.Form.is_valid()` will perform these validation steps for\nall the fields that are included on the form. See the :doc:`ModelForm\ndocumentation </topics/forms/modelforms>` for more information. You should only\nneed to call a model's :meth:`~Model.full_clean()` method if you plan to handle\nvalidation errors yourself, or if you have excluded fields from the\n:class:`~django.forms.ModelForm` that require validation.\n\n.. method:: Model.full_clean(exclude=None, validate_unique=True)\n\nThis method calls :meth:`Model.clean_fields()`, :meth:`Model.clean()`, and\n:meth:`Model.validate_unique()` (if ``validate_unique`` is ``True``), in that\norder and raises a :exc:`~django.core.exceptions.ValidationError` that has a\n``message_dict`` attribute containing errors from all three stages.\n\nThe optional ``exclude`` argument can be used to provide a list of field names\nthat can be excluded from validation and cleaning.\n:class:`~django.forms.ModelForm` uses this argument to exclude fields that\naren't present on your form from being validated since any errors raised could\nnot be corrected by the user.\n\nNote that ``full_clean()`` will *not* be called automatically when you call\nyour model's :meth:`~Model.save()` method. You'll need to call it manually\nwhen you want to run one-step model validation for your own manually created\nmodels. For example::\n\n    from django.core.exceptions import ValidationError\n    try:\n        article.full_clean()\n    except ValidationError as e:\n        # Do something based on the errors contained in e.message_dict.\n        # Display them to a user, or handle them programmatically.\n        pass\n\nThe first step ``full_clean()`` performs is to clean each individual field.\n\n.. method:: Model.clean_fields(exclude=None)\n\nThis method will validate all fields on your model. The optional ``exclude``\nargument lets you provide a list of field names to exclude from validation. It\nwill raise a :exc:`~django.core.exceptions.ValidationError` if any fields fail\nvalidation.\n\nThe second step ``full_clean()`` performs is to call :meth:`Model.clean()`.\nThis method should be overridden to perform custom validation on your model.\n\n.. method:: Model.clean()\n\nThis method should be used to provide custom model validation, and to modify\nattributes on your model if desired. For instance, you could use it to\nautomatically provide a value for a field, or to do validation that requires\naccess to more than a single field::\n\n    import datetime\n    from django.core.exceptions import ValidationError\n    from django.db import models\n    from django.utils.translation import gettext_lazy as _\n\n    class Article(models.Model):\n        ...\n        def clean(self):\n            # Don't allow draft entries to have a pub_date.\n            if self.status == 'draft' and self.pub_date is not None:\n                raise ValidationError(_('Draft entries may not have a publication date.'))\n            # Set the pub_date for published items if it hasn't been set already.\n            if self.status == 'published' and self.pub_date is None:\n                self.pub_date = datetime.date.today()\n\nNote, however, that like :meth:`Model.full_clean()`, a model's ``clean()``\nmethod is not invoked when you call your model's :meth:`~Model.save()` method.\n\nIn the above example, the :exc:`~django.core.exceptions.ValidationError`\nexception raised by ``Model.clean()`` was instantiated with a string, so it\nwill be stored in a special error dictionary key,\n:data:`~django.core.exceptions.NON_FIELD_ERRORS`. This key is used for errors\nthat are tied to the entire model instead of to a specific field::\n\n    from django.core.exceptions import NON_FIELD_ERRORS, ValidationError\n    try:\n        article.full_clean()\n    except ValidationError as e:\n        non_field_errors = e.message_dict[NON_FIELD_ERRORS]\n\nTo assign exceptions to a specific field, instantiate the\n:exc:`~django.core.exceptions.ValidationError` with a dictionary, where the\nkeys are the field names. We could update the previous example to assign the\nerror to the ``pub_date`` field::\n\n    class Article(models.Model):\n        ...\n        def clean(self):\n            # Don't allow draft entries to have a pub_date.\n            if self.status == 'draft' and self.pub_date is not None:\n                raise ValidationError({'pub_date': _('Draft entries may not have a publication date.')})\n            ...\n\nIf you detect errors in multiple fields during ``Model.clean()``, you can also\npass a dictionary mapping field names to errors::\n\n    raise ValidationError({\n        'title': ValidationError(_('Missing title.'), code='required'),\n        'pub_date': ValidationError(_('Invalid date.'), code='invalid'),\n    })\n\nFinally, ``full_clean()`` will check any unique constraints on your model.\n\n.. admonition:: How to raise field-specific validation errors if those fields don't appear in a ``ModelForm``\n\n    You can't raise validation errors in ``Model.clean()`` for fields that\n    don't appear in a model form (a form may limit its fields using\n    ``Meta.fields`` or ``Meta.exclude``). Doing so will raise a ``ValueError``\n    because the validation error won't be able to be associated with the\n    excluded field.\n\n    To work around this dilemma, instead override :meth:`Model.clean_fields()\n    <django.db.models.Model.clean_fields>` as it receives the list of fields\n    that are excluded from validation. For example::\n\n        class Article(models.Model):\n            ...\n            def clean_fields(self, exclude=None):\n                super().clean_fields(exclude=exclude)\n                if self.status == 'draft' and self.pub_date is not None:\n                    if exclude and 'status' in exclude:\n                        raise ValidationError(\n                            _('Draft entries may not have a publication date.')\n                        )\n                    else:\n                        raise ValidationError({\n                            'status': _(\n                                'Set status to draft if there is not a '\n                                'publication date.'\n                             ),\n                        })\n\n.. method:: Model.validate_unique(exclude=None)\n\nThis method is similar to :meth:`~Model.clean_fields`, but validates all\nuniqueness constraints on your model instead of individual field values. The\noptional ``exclude`` argument allows you to provide a list of field names to\nexclude from validation. It will raise a\n:exc:`~django.core.exceptions.ValidationError` if any fields fail validation.\n\nNote that if you provide an ``exclude`` argument to ``validate_unique()``, any\n:attr:`~django.db.models.Options.unique_together` constraint involving one of\nthe fields you provided will not be checked.\n\n\nSaving objects\n==============\n\nTo save an object back to the database, call ``save()``:\n\n.. method:: Model.save(force_insert=False, force_update=False, using=DEFAULT_DB_ALIAS, update_fields=None)\n\nIf you want customized saving behavior, you can override this ``save()``\nmethod. See :ref:`overriding-model-methods` for more details.\n\nThe model save process also has some subtleties; see the sections below.\n\nAuto-incrementing primary keys\n------------------------------\n\nIf a model has an :class:`~django.db.models.AutoField` — an auto-incrementing\nprimary key — then that auto-incremented value will be calculated and saved as\nan attribute on your object the first time you call ``save()``::\n\n    >>> b2 = Blog(name='Cheddar Talk', tagline='Thoughts on cheese.')\n    >>> b2.id     # Returns None, because b2 doesn't have an ID yet.\n    >>> b2.save()\n    >>> b2.id     # Returns the ID of your new object.\n\nThere's no way to tell what the value of an ID will be before you call\n``save()``, because that value is calculated by your database, not by Django.\n\nFor convenience, each model has an :class:`~django.db.models.AutoField` named\n``id`` by default unless you explicitly specify ``primary_key=True`` on a field\nin your model. See the documentation for :class:`~django.db.models.AutoField`\nfor more details.\n\nThe ``pk`` property\n~~~~~~~~~~~~~~~~~~~\n\n.. attribute:: Model.pk\n\nRegardless of whether you define a primary key field yourself, or let Django\nsupply one for you, each model will have a property called ``pk``. It behaves\nlike a normal attribute on the model, but is actually an alias for whichever\nattribute is the primary key field for the model. You can read and set this\nvalue, just as you would for any other attribute, and it will update the\ncorrect field in the model.\n\nExplicitly specifying auto-primary-key values\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf a model has an :class:`~django.db.models.AutoField` but you want to define a\nnew object's ID explicitly when saving, define it explicitly before saving,\nrather than relying on the auto-assignment of the ID::\n\n    >>> b3 = Blog(id=3, name='Cheddar Talk', tagline='Thoughts on cheese.')\n    >>> b3.id     # Returns 3.\n    >>> b3.save()\n    >>> b3.id     # Returns 3.\n\nIf you assign auto-primary-key values manually, make sure not to use an\nalready-existing primary-key value! If you create a new object with an explicit\nprimary-key value that already exists in the database, Django will assume you're\nchanging the existing record rather than creating a new one.\n\nGiven the above ``'Cheddar Talk'`` blog example, this example would override the\nprevious record in the database::\n\n    b4 = Blog(id=3, name='Not Cheddar', tagline='Anything but cheese.')\n    b4.save()  # Overrides the previous blog with ID=3!\n\nSee `How Django knows to UPDATE vs. INSERT`_, below, for the reason this\nhappens.\n\nExplicitly specifying auto-primary-key values is mostly useful for bulk-saving\nobjects, when you're confident you won't have primary-key collision.\n\nIf you're using PostgreSQL, the sequence associated with the primary key might\nneed to be updated; see :ref:`manually-specified-autoincrement-pk`.\n\nWhat happens when you save?\n---------------------------\n\nWhen you save an object, Django performs the following steps:\n\n#. **Emit a pre-save signal.** The :data:`~django.db.models.signals.pre_save`\n   signal is sent, allowing any functions listening for that signal to do\n   something.\n\n#. **Preprocess the data.** Each field's\n   :meth:`~django.db.models.Field.pre_save` method is called to perform any\n   automated data modification that's needed. For example, the date/time fields\n   override ``pre_save()`` to implement\n   :attr:`~django.db.models.DateField.auto_now_add` and\n   :attr:`~django.db.models.DateField.auto_now`.\n\n#. **Prepare the data for the database.** Each field's\n   :meth:`~django.db.models.Field.get_db_prep_save` method is asked to provide\n   its current value in a data type that can be written to the database.\n\n   Most fields don't require data preparation. Simple data types, such as\n   integers and strings, are 'ready to write' as a Python object. However, more\n   complex data types often require some modification.\n\n   For example, :class:`~django.db.models.DateField` fields use a Python\n   ``datetime`` object to store data. Databases don't store ``datetime``\n   objects, so the field value must be converted into an ISO-compliant date\n   string for insertion into the database.\n\n#. **Insert the data into the database.** The preprocessed, prepared data is\n   composed into an SQL statement for insertion into the database.\n\n#. **Emit a post-save signal.** The :data:`~django.db.models.signals.post_save`\n   signal is sent, allowing any functions listening for that signal to do\n   something.\n\nHow Django knows to UPDATE vs. INSERT\n-------------------------------------\n\nYou may have noticed Django database objects use the same ``save()`` method\nfor creating and changing objects. Django abstracts the need to use ``INSERT``\nor ``UPDATE`` SQL statements. Specifically, when you call ``save()`` and the\nobject's primary key attribute does **not** define a\n:attr:`~django.db.models.Field.default`, Django follows this algorithm:\n\n* If the object's primary key attribute is set to a value that evaluates to\n  ``True`` (i.e., a value other than ``None`` or the empty string), Django\n  executes an ``UPDATE``.\n* If the object's primary key attribute is *not* set or if the ``UPDATE``\n  didn't update anything (e.g. if primary key is set to a value that doesn't\n  exist in the database), Django executes an ``INSERT``.\n\nIf the object's primary key attribute defines a\n:attr:`~django.db.models.Field.default` then Django executes an ``UPDATE`` if\nit is an existing model instance and primary key is set to a value that exists\nin the database. Otherwise, Django executes an ``INSERT``.\n\nThe one gotcha here is that you should be careful not to specify a primary-key\nvalue explicitly when saving new objects, if you cannot guarantee the\nprimary-key value is unused. For more on this nuance, see `Explicitly specifying\nauto-primary-key values`_ above and `Forcing an INSERT or UPDATE`_ below.\n\nIn Django 1.5 and earlier, Django did a ``SELECT`` when the primary key\nattribute was set. If the ``SELECT`` found a row, then Django did an ``UPDATE``,\notherwise it did an ``INSERT``. The old algorithm results in one more query in\nthe ``UPDATE`` case. There are some rare cases where the database doesn't\nreport that a row was updated even if the database contains a row for the\nobject's primary key value. An example is the PostgreSQL ``ON UPDATE`` trigger\nwhich returns ``NULL``. In such cases it is possible to revert to the old\nalgorithm by setting the :attr:`~django.db.models.Options.select_on_save`\noption to ``True``.\n\n.. _ref-models-force-insert:\n\nForcing an INSERT or UPDATE\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIn some rare circumstances, it's necessary to be able to force the\n:meth:`~Model.save()` method to perform an SQL ``INSERT`` and not fall back to\ndoing an ``UPDATE``. Or vice-versa: update, if possible, but not insert a new\nrow. In these cases you can pass the ``force_insert=True`` or\n``force_update=True`` parameters to the :meth:`~Model.save()` method.\nPassing both parameters is an error: you cannot both insert *and* update at the\nsame time!\n\nIt should be very rare that you'll need to use these parameters. Django will\nalmost always do the right thing and trying to override that will lead to\nerrors that are difficult to track down. This feature is for advanced use\nonly.\n\nUsing ``update_fields`` will force an update similarly to ``force_update``.\n\n.. _ref-models-field-updates-using-f-expressions:\n\nUpdating attributes based on existing fields\n--------------------------------------------\n\nSometimes you'll need to perform a simple arithmetic task on a field, such\nas incrementing or decrementing the current value. One way of achieving this is\ndoing the arithmetic in Python like::\n\n    >>> product = Product.objects.get(name='Venezuelan Beaver Cheese')\n    >>> product.number_sold += 1\n    >>> product.save()\n\nIf the old ``number_sold`` value retrieved from the database was 10, then\nthe value of 11 will be written back to the database.\n\nThe process can be made robust, :ref:`avoiding a race condition\n<avoiding-race-conditions-using-f>`, as well as slightly faster by expressing\nthe update relative to the original field value, rather than as an explicit\nassignment of a new value. Django provides :class:`F expressions\n<django.db.models.F>` for performing this kind of relative update. Using\n:class:`F expressions <django.db.models.F>`, the previous example is expressed\nas::\n\n    >>> from django.db.models import F\n    >>> product = Product.objects.get(name='Venezuelan Beaver Cheese')\n    >>> product.number_sold = F('number_sold') + 1\n    >>> product.save()\n\nFor more details, see the documentation on :class:`F expressions\n<django.db.models.F>` and their :ref:`use in update queries\n<topics-db-queries-update>`.\n\nSpecifying which fields to save\n-------------------------------\n\nIf ``save()`` is passed a list of field names in keyword argument\n``update_fields``, only the fields named in that list will be updated.\nThis may be desirable if you want to update just one or a few fields on\nan object. There will be a slight performance benefit from preventing\nall of the model fields from being updated in the database. For example::\n\n    product.name = 'Name changed again'\n    product.save(update_fields=['name'])\n\nThe ``update_fields`` argument can be any iterable containing strings. An\nempty ``update_fields`` iterable will skip the save. A value of None will\nperform an update on all fields.\n\nSpecifying ``update_fields`` will force an update.\n\nWhen saving a model fetched through deferred model loading\n(:meth:`~django.db.models.query.QuerySet.only()` or\n:meth:`~django.db.models.query.QuerySet.defer()`) only the fields loaded\nfrom the DB will get updated. In effect there is an automatic\n``update_fields`` in this case. If you assign or change any deferred field\nvalue, the field will be added to the updated fields.\n\nDeleting objects\n================\n\n.. method:: Model.delete(using=DEFAULT_DB_ALIAS, keep_parents=False)\n\nIssues an SQL ``DELETE`` for the object. This only deletes the object in the\ndatabase; the Python instance will still exist and will still have data in\nits fields. This method returns the number of objects deleted and a dictionary\nwith the number of deletions per object type.\n\nFor more details, including how to delete objects in bulk, see\n:ref:`topics-db-queries-delete`.\n\nIf you want customized deletion behavior, you can override the ``delete()``\nmethod. See :ref:`overriding-model-methods` for more details.\n\nSometimes with :ref:`multi-table inheritance <multi-table-inheritance>` you may\nwant to delete only a child model's data. Specifying ``keep_parents=True`` will\nkeep the parent model's data.\n\nPickling objects\n================\n\nWhen you :mod:`pickle` a model, its current state is pickled. When you unpickle\nit, it'll contain the model instance at the moment it was pickled, rather than\nthe data that's currently in the database.\n\n.. admonition:: You can't share pickles between versions\n\n    Pickles of models are only valid for the version of Django that\n    was used to generate them. If you generate a pickle using Django\n    version N, there is no guarantee that pickle will be readable with\n    Django version N+1. Pickles should not be used as part of a long-term\n    archival strategy.\n\n    Since pickle compatibility errors can be difficult to diagnose, such as\n    silently corrupted objects, a ``RuntimeWarning`` is raised when you try to\n    unpickle a model in a Django version that is different than the one in\n    which it was pickled.\n\n.. _model-instance-methods:\n\nOther model instance methods\n============================\n\nA few object methods have special purposes.\n\n``__str__()``\n-------------\n\n.. method:: Model.__str__()\n\nThe ``__str__()`` method is called whenever you call ``str()`` on an object.\nDjango uses ``str(obj)`` in a number of places. Most notably, to display an\nobject in the Django admin site and as the value inserted into a template when\nit displays an object. Thus, you should always return a nice, human-readable\nrepresentation of the model from the ``__str__()`` method.\n\nFor example::\n\n    from django.db import models\n\n    class Person(models.Model):\n        first_name = models.CharField(max_length=50)\n        last_name = models.CharField(max_length=50)\n\n        def __str__(self):\n            return '%s %s' % (self.first_name, self.last_name)\n\n``__eq__()``\n------------\n\n.. method:: Model.__eq__()\n\nThe equality method is defined such that instances with the same primary\nkey value and the same concrete class are considered equal, except that\ninstances with a primary key value of ``None`` aren't equal to anything except\nthemselves. For proxy models, concrete class is defined as the model's first\nnon-proxy parent; for all other models it's simply the model's class.\n\nFor example::\n\n    from django.db import models\n\n    class MyModel(models.Model):\n        id = models.AutoField(primary_key=True)\n\n    class MyProxyModel(MyModel):\n        class Meta:\n            proxy = True\n\n    class MultitableInherited(MyModel):\n        pass\n\n    # Primary keys compared\n    MyModel(id=1) == MyModel(id=1)\n    MyModel(id=1) != MyModel(id=2)\n    # Primary keys are None\n    MyModel(id=None) != MyModel(id=None)\n    # Same instance\n    instance = MyModel(id=None)\n    instance == instance\n    # Proxy model\n    MyModel(id=1) == MyProxyModel(id=1)\n    # Multi-table inheritance\n    MyModel(id=1) != MultitableInherited(id=1)\n\n``__hash__()``\n--------------\n\n.. method:: Model.__hash__()\n\nThe ``__hash__()`` method is based on the instance's primary key value. It\nis effectively ``hash(obj.pk)``. If the instance doesn't have a primary key\nvalue then a ``TypeError`` will be raised (otherwise the ``__hash__()``\nmethod would return different values before and after the instance is\nsaved, but changing the :meth:`~object.__hash__` value of an instance is\nforbidden in Python.\n\n``get_absolute_url()``\n----------------------\n\n.. method:: Model.get_absolute_url()\n\nDefine a ``get_absolute_url()`` method to tell Django how to calculate the\ncanonical URL for an object. To callers, this method should appear to return a\nstring that can be used to refer to the object over HTTP.\n\nFor example::\n\n    def get_absolute_url(self):\n        return \"/people/%i/\" % self.id\n\nWhile this code is correct and simple, it may not be the most portable way to\nto write this kind of method. The :func:`~django.urls.reverse` function is\nusually the best approach.\n\nFor example::\n\n    def get_absolute_url(self):\n        from django.urls import reverse\n        return reverse('people.views.details', args=[str(self.id)])\n\nOne place Django uses ``get_absolute_url()`` is in the admin app. If an object\ndefines this method, the object-editing page will have a \"View on site\" link\nthat will jump you directly to the object's public view, as given by\n``get_absolute_url()``.\n\nSimilarly, a couple of other bits of Django, such as the :doc:`syndication feed\nframework </ref/contrib/syndication>`, use ``get_absolute_url()`` when it is\ndefined. If it makes sense for your model's instances to each have a unique\nURL, you should define ``get_absolute_url()``.\n\n.. warning::\n\n    You should avoid building the URL from unvalidated user input, in order to\n    reduce possibilities of link or redirect poisoning::\n\n        def get_absolute_url(self):\n            return '/%s/' % self.name\n\n    If ``self.name`` is ``'/example.com'`` this returns ``'//example.com/'``\n    which, in turn, is a valid schema relative URL but not the expected\n    ``'/%2Fexample.com/'``.\n\n\nIt's good practice to use ``get_absolute_url()`` in templates, instead of\nhard-coding your objects' URLs. For example, this template code is bad:\n\n.. code-block:: html+django\n\n    <!-- BAD template code. Avoid! -->\n    <a href=\"/people/{{ object.id }}/\">{{ object.name }}</a>\n\nThis template code is much better:\n\n.. code-block:: html+django\n\n    <a href=\"{{ object.get_absolute_url }}\">{{ object.name }}</a>\n\nThe logic here is that if you change the URL structure of your objects, even\nfor something small like correcting a spelling error, you don't want to have to\ntrack down every place that the URL might be created. Specify it once, in\n``get_absolute_url()`` and have all your other code call that one place.\n\n.. note::\n    The string you return from ``get_absolute_url()`` **must** contain only\n    ASCII characters (required by the URI specification, :rfc:`2396#section-2`)\n    and be URL-encoded, if necessary.\n\n    Code and templates calling ``get_absolute_url()`` should be able to use the\n    result directly without any further processing. You may wish to use the\n    ``django.utils.encoding.iri_to_uri()`` function to help with this if you\n    are using strings containing characters outside the ASCII range.\n\nExtra instance methods\n======================\n\nIn addition to :meth:`~Model.save()`, :meth:`~Model.delete()`, a model object\nmight have some of the following methods:\n\n.. method:: Model.get_FOO_display()\n\nFor every field that has :attr:`~django.db.models.Field.choices` set, the\nobject will have a ``get_FOO_display()`` method, where ``FOO`` is the name of\nthe field. This method returns the \"human-readable\" value of the field.\n\nFor example::\n\n    from django.db import models\n\n    class Person(models.Model):\n        SHIRT_SIZES = (\n            ('S', 'Small'),\n            ('M', 'Medium'),\n            ('L', 'Large'),\n        )\n        name = models.CharField(max_length=60)\n        shirt_size = models.CharField(max_length=2, choices=SHIRT_SIZES)\n\n::\n\n    >>> p = Person(name=\"Fred Flintstone\", shirt_size=\"L\")\n    >>> p.save()\n    >>> p.shirt_size\n    'L'\n    >>> p.get_shirt_size_display()\n    'Large'\n\n.. versionchanged:: 3.1\n\n    Support for :class:`~django.contrib.postgres.fields.ArrayField` and\n    :class:`~django.contrib.postgres.fields.RangeField` was added.\n\n.. method:: Model.get_next_by_FOO(**kwargs)\n.. method:: Model.get_previous_by_FOO(**kwargs)\n\nFor every :class:`~django.db.models.DateField` and\n:class:`~django.db.models.DateTimeField` that does not have :attr:`null=True\n<django.db.models.Field.null>`, the object will have ``get_next_by_FOO()`` and\n``get_previous_by_FOO()`` methods, where ``FOO`` is the name of the field. This\nreturns the next and previous object with respect to the date field, raising\na :exc:`~django.db.models.Model.DoesNotExist` exception when appropriate.\n\nBoth of these methods will perform their queries using the default\nmanager for the model. If you need to emulate filtering used by a\ncustom manager, or want to perform one-off custom filtering, both\nmethods also accept optional keyword arguments, which should be in the\nformat described in :ref:`Field lookups <field-lookups>`.\n\nNote that in the case of identical date values, these methods will use the\nprimary key as a tie-breaker. This guarantees that no records are skipped or\nduplicated. That also means you cannot use those methods on unsaved objects.\n\n.. admonition:: Overriding extra instance methods\n\n    In most cases overriding or inheriting ``get_FOO_display()``,\n    ``get_next_by_FOO()``, and ``get_previous_by_FOO()`` should work as\n    expected. Since they are added by the metaclass however, it is not\n    practical to account for all possible inheritance structures. In more\n    complex cases you should override ``Field.contribute_to_class()`` to set\n    the methods you need.\n\nOther attributes\n================\n\n``DoesNotExist``\n----------------\n\n.. exception:: Model.DoesNotExist\n\n    This exception is raised by the ORM in a couple places, for example by\n    :meth:`QuerySet.get() <django.db.models.query.QuerySet.get>` when an object\n    is not found for the given query parameters.\n\n    Django provides a ``DoesNotExist`` exception as an attribute of each model\n    class to identify the class of object that could not be found and to allow\n    you to catch a particular model class with ``try/except``. The exception is\n    a subclass of :exc:`django.core.exceptions.ObjectDoesNotExist`.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":122,"nodeType":"TextFile","repoName":null,"name":"model-api.txt","path":"docs/ref/contrib/gis","text":"===================\nGeoDjango Model API\n===================\n\n.. module:: django.contrib.gis.db.models\n    :synopsis: GeoDjango model and field API.\n\nThis document explores the details of the GeoDjango Model API.  Throughout this\nsection, we'll be using the following geographic model of a `ZIP code`__ and\nof a `Digital Elevation Model`__ as our examples::\n\n    from django.contrib.gis.db import models\n\n    class Zipcode(models.Model):\n        code = models.CharField(max_length=5)\n        poly = models.PolygonField()\n\n    class Elevation(models.Model):\n        name = models.CharField(max_length=100)\n        rast = models.RasterField()\n\n__ https://en.wikipedia.org/wiki/ZIP_code\n__ https://en.wikipedia.org/wiki/Digital_elevation_model\n\nSpatial Field Types\n===================\n\nSpatial fields consist of a series of geometry field types and one raster field\ntype. Each of the geometry field types correspond to the OpenGIS Simple\nFeatures specification [#fnogc]_. There is no such standard for raster data.\n\n``GeometryField``\n-----------------\n\n.. class:: GeometryField\n\nThe base class for geometry fields.\n\n``PointField``\n--------------\n\n.. class:: PointField\n\nStores a :class:`~django.contrib.gis.geos.Point`.\n\n``LineStringField``\n-------------------\n\n.. class:: LineStringField\n\nStores a :class:`~django.contrib.gis.geos.LineString`.\n\n``PolygonField``\n----------------\n\n.. class:: PolygonField\n\nStores a :class:`~django.contrib.gis.geos.Polygon`.\n\n``MultiPointField``\n-------------------\n\n.. class:: MultiPointField\n\nStores a :class:`~django.contrib.gis.geos.MultiPoint`.\n\n``MultiLineStringField``\n------------------------\n\n.. class:: MultiLineStringField\n\nStores a :class:`~django.contrib.gis.geos.MultiLineString`.\n\n``MultiPolygonField``\n---------------------\n\n.. class:: MultiPolygonField\n\nStores a :class:`~django.contrib.gis.geos.MultiPolygon`.\n\n``GeometryCollectionField``\n---------------------------\n\n.. class:: GeometryCollectionField\n\nStores a :class:`~django.contrib.gis.geos.GeometryCollection`.\n\n``RasterField``\n---------------\n\n.. class:: RasterField\n\nStores a :class:`~django.contrib.gis.gdal.GDALRaster`.\n\n``RasterField`` is currently only implemented for the PostGIS backend.\n\nSpatial Field Options\n=====================\n\nIn addition to the regular :ref:`common-model-field-options` available for\nDjango model fields, spatial fields have the following additional options.\nAll are optional.\n\n``srid``\n--------\n\n.. attribute:: BaseSpatialField.srid\n\nSets the SRID [#fnogcsrid]_ (Spatial Reference System Identity) of the geometry field to\nthe given value. Defaults to 4326 (also known as `WGS84`__, units are in degrees\nof longitude and latitude).\n\n__ https://en.wikipedia.org/wiki/WGS84\n\n.. _selecting-an-srid:\n\nSelecting an SRID\n~~~~~~~~~~~~~~~~~\n\nChoosing an appropriate SRID for your model is an important decision that the\ndeveloper should consider carefully.  The SRID is an integer specifier that\ncorresponds to the projection system that will be used to interpret the data\nin the spatial database. [#fnsrid]_  Projection systems give the context to the\ncoordinates that specify a location.  Although the details of `geodesy`__ are\nbeyond the scope of this documentation, the general problem is that the earth\nis spherical and representations of the earth (e.g., paper maps, Web maps)\nare not.\n\nMost people are familiar with using latitude and longitude to reference a\nlocation on the earth's surface.  However, latitude and longitude are angles,\nnot distances. In other words, while the shortest path between two points on\na flat surface is a straight line, the shortest path between two points on a curved\nsurface (such as the earth) is an *arc* of a `great circle`__. [#fnthematic]_  Thus,\nadditional computation is required to obtain distances in planar units (e.g.,\nkilometers and miles).  Using a geographic coordinate system may introduce\ncomplications for the developer later on. For example, SpatiaLite does not have\nthe capability to perform distance calculations between geometries using\ngeographic coordinate systems, e.g. constructing a query to  find all points\nwithin 5 miles of a county boundary stored as WGS84.\n[#fndist]_\n\nPortions of the earth's surface may projected onto a two-dimensional, or\nCartesian, plane.  Projected coordinate systems are especially convenient\nfor region-specific applications, e.g., if you know that your database will\nonly cover geometries in `North Kansas`__, then you may consider using projection\nsystem specific to that region.  Moreover, projected coordinate systems are\ndefined in Cartesian units (such as meters or feet), easing distance\ncalculations.\n\n.. note::\n\n    If you wish to perform arbitrary distance queries using non-point\n    geometries in WGS84 in PostGIS and you want decent performance, enable the\n    :attr:`GeometryField.geography` keyword so that :ref:`geography database\n    type <geography-type>` is used instead.\n\nAdditional Resources:\n\n* `spatialreference.org`__: A Django-powered database of spatial reference\n  systems.\n* `The State Plane Coordinate System`__: A website covering the various\n  projection systems used in the United States.  Much of the U.S. spatial\n  data encountered will be in one of these coordinate systems rather than\n  in a geographic coordinate system such as WGS84.\n\n__ https://en.wikipedia.org/wiki/Geodesy\n__ https://en.wikipedia.org/wiki/Great_circle\n__ https://www.spatialreference.org/ref/epsg/2796/\n__ https://spatialreference.org/\n__ https://web.archive.org/web/20080302095452/http://welcome.warnercnr.colostate.edu/class_info/nr502/lg3/datums_coordinates/spcs.html\n\n``spatial_index``\n-----------------\n\n.. attribute:: BaseSpatialField.spatial_index\n\nDefaults to ``True``.  Creates a spatial index for the given geometry\nfield.\n\n.. note::\n\n    This is different from the ``db_index`` field option because spatial\n    indexes are created in a different manner than regular database\n    indexes.  Specifically, spatial indexes are typically created using\n    a variant of the R-Tree, while regular database indexes typically\n    use B-Trees.\n\n.. _geometry-field-options:\n\nGeometry Field Options\n======================\n\nThere are additional options available for Geometry fields. All the following\noptions are optional.\n\n``dim``\n-------\n\n.. attribute:: GeometryField.dim\n\nThis option may be used for customizing the coordinate dimension of the\ngeometry field.  By default, it is set to 2, for representing two-dimensional\ngeometries.  For spatial backends that support it, it may be set to 3 for\nthree-dimensional support.\n\n.. note::\n\n    At this time 3D support is limited to the PostGIS and SpatiaLite backends.\n\n``geography``\n-------------\n\n.. attribute:: GeometryField.geography\n\nIf set to ``True``, this option will create a database column of\ntype geography, rather than geometry.  Please refer to the\n:ref:`geography type <geography-type>` section below for more\ndetails.\n\n.. note::\n\n    Geography support is limited to PostGIS and will force the SRID to be 4326.\n\n.. _geography-type:\n\nGeography Type\n~~~~~~~~~~~~~~\n\nThe geography type provides native support for spatial features represented\nwith geographic coordinates (e.g., WGS84 longitude/latitude). [#fngeography]_\nUnlike the plane used by a geometry type, the geography type uses a spherical\nrepresentation of its data.  Distance and measurement operations\nperformed on a geography column automatically employ great circle arc\ncalculations and return linear units.  In other words, when ``ST_Distance``\nis called on two geographies, a value in meters is returned (as opposed\nto degrees if called on a geometry column in WGS84).\n\nBecause geography calculations involve more mathematics, only a subset of the\nPostGIS spatial lookups are available for the geography type. Practically,\nthis means that in addition to the :ref:`distance lookups <distance-lookups>`\nonly the following additional :ref:`spatial lookups <spatial-lookups>` are\navailable for geography columns:\n\n* :lookup:`bboverlaps`\n* :lookup:`coveredby`\n* :lookup:`covers`\n* :lookup:`intersects`\n\nIf you need to use a spatial lookup or aggregate that doesn't support the\ngeography type as input, you can use the\n:class:`~django.db.models.functions.Cast` database function to convert the\ngeography column to a geometry type in the query::\n\n    from django.contrib.gis.db.models import PointField\n    from django.db.models.functions import Cast\n\n    Zipcode.objects.annotate(\n        geom=Cast('geography_field', PointField())\n    ).filter(geom__within=poly)\n\nFor more information, the PostGIS documentation contains a helpful section on\ndetermining `when to use geography data type over geometry data type\n<https://postgis.net/docs/using_postgis_dbmanagement.html#PostGIS_GeographyVSGeometry>`_.\n\n.. rubric:: Footnotes\n.. [#fnogc] OpenGIS Consortium, Inc., `Simple Feature Specification For SQL <https://www.opengeospatial.org/standards/sfs>`_.\n.. [#fnogcsrid] *See id.* at Ch. 2.3.8, p. 39 (Geometry Values and Spatial Reference Systems).\n.. [#fnsrid] Typically, SRID integer corresponds to an EPSG (`European Petroleum Survey Group <http://www.epsg.org>`_) identifier.  However, it may also be associated with custom projections defined in spatial database's spatial reference systems table.\n.. [#fnthematic] Terry A. Slocum, Robert B. McMaster, Fritz C. Kessler, & Hugh H. Howard, *Thematic Cartography and Geographic Visualization* (Prentice Hall, 2nd edition), at Ch. 7.1.3.\n.. [#fndist] This limitation does not apply to PostGIS.\n.. [#fngeography] Please refer to the `PostGIS Geography Type <https://postgis.net/docs/using_postgis_dbmanagement.html#PostGIS_Geography>`_ documentation for more details.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":123,"nodeType":"TextFile","repoName":null,"name":"layermapping.txt","path":"docs/ref/contrib/gis","text":"====================================\n``LayerMapping`` data import utility\n====================================\n\n.. module:: django.contrib.gis.utils.layermapping\n    :synopsis: Spatial data import utility for GeoDjango models.\n\n.. currentmodule:: django.contrib.gis.utils\n\nThe :class:`LayerMapping` class provides a way to map the contents of\nvector spatial data files (e.g. shapefiles) into GeoDjango models.\n\nThis utility grew out of the author's personal needs to eliminate\nthe code repetition that went into pulling geometries and fields out of\na vector layer, converting to another coordinate system (e.g. WGS84), and\nthen inserting into a GeoDjango model.\n\n.. note::\n\n    Use of :class:`LayerMapping` requires GDAL.\n\n.. warning ::\n\n    GIS data sources, like shapefiles, may be very large.  If you find\n    that :class:`LayerMapping` is using too much memory, set\n    :setting:`DEBUG` to ``False`` in your settings.  When :setting:`DEBUG`\n    is set to ``True``, Django :ref:`automatically logs <faq-see-raw-sql-queries>`\n    *every* SQL query -- and when SQL statements contain geometries, this may\n    consume more memory than is typical.\n\nExample\n=======\n\n#. You need a GDAL-supported data source, like a shapefile (here we're using\n   a simple polygon shapefile, ``test_poly.shp``, with three features)::\n\n    >>> from django.contrib.gis.gdal import DataSource\n    >>> ds = DataSource('test_poly.shp')\n    >>> layer = ds[0]\n    >>> print(layer.fields) # Exploring the fields in the layer, we only want the 'str' field.\n    ['float', 'int', 'str']\n    >>> print(len(layer)) # getting the number of features in the layer (should be 3)\n    3\n    >>> print(layer.geom_type) # Should be 'Polygon'\n    Polygon\n    >>> print(layer.srs) # WGS84 in WKT\n    GEOGCS[\"GCS_WGS_1984\",\n        DATUM[\"WGS_1984\",\n            SPHEROID[\"WGS_1984\",6378137,298.257223563]],\n        PRIMEM[\"Greenwich\",0],\n        UNIT[\"Degree\",0.017453292519943295]]\n\n#. Now we define our corresponding Django model (make sure to use :djadmin:`migrate`)::\n\n    from django.contrib.gis.db import models\n\n    class TestGeo(models.Model):\n        name = models.CharField(max_length=25) # corresponds to the 'str' field\n        poly = models.PolygonField(srid=4269) # we want our model in a different SRID\n\n        def __str__(self):\n            return 'Name: %s' % self.name\n\n#. Use :class:`LayerMapping` to extract all the features and place them in the\n   database::\n\n    >>> from django.contrib.gis.utils import LayerMapping\n    >>> from geoapp.models import TestGeo\n    >>> mapping = {'name' : 'str', # The 'name' model field maps to the 'str' layer field.\n                   'poly' : 'POLYGON', # For geometry fields use OGC name.\n                   } # The mapping is a dictionary\n    >>> lm = LayerMapping(TestGeo, 'test_poly.shp', mapping)\n    >>> lm.save(verbose=True) # Save the layermap, imports the data.\n    Saved: Name: 1\n    Saved: Name: 2\n    Saved: Name: 3\n\nHere, :class:`LayerMapping` transformed the three geometries from the shapefile\nin their original spatial reference system (WGS84) to the spatial reference\nsystem of the GeoDjango model (NAD83).  If no spatial reference system is\ndefined for the layer, use the ``source_srs`` keyword with a\n:class:`~django.contrib.gis.gdal.SpatialReference` object to specify one.\n\n``LayerMapping`` API\n====================\n\n.. class:: LayerMapping(model, data_source, mapping, layer=0, source_srs=None, encoding=None, transaction_mode='commit_on_success', transform=True, unique=True, using='default')\n\nThe following are the arguments and keywords that may be used during\ninstantiation of ``LayerMapping`` objects.\n\n=================  =========================================================\nArgument           Description\n=================  =========================================================\n``model``          The geographic model, *not* an instance.\n\n``data_source``    The path to the OGR-supported data source file\n                   (e.g., a shapefile).  Also accepts\n                   :class:`django.contrib.gis.gdal.DataSource` instances.\n\n``mapping``        A dictionary: keys are strings corresponding to\n                   the model field, and values correspond to\n                   string field names for the OGR feature, or if the\n                   model field is a geographic then it should\n                   correspond to the OGR geometry type,\n                   e.g., ``'POINT'``, ``'LINESTRING'``, ``'POLYGON'``.\n=================  =========================================================\n\n=====================  =====================================================\nKeyword Arguments\n=====================  =====================================================\n``layer``              The index of the layer to use from the Data Source\n                       (defaults to 0)\n\n``source_srs``         Use this to specify the source SRS manually (for\n                       example, some shapefiles don't come with a ``'.prj'``\n                       file).  An integer SRID, WKT or PROJ strings, and\n                       :class:`django.contrib.gis.gdal.SpatialReference`\n                       objects are accepted.\n\n``encoding``           Specifies the character set encoding of the strings\n                       in the OGR data source.  For example, ``'latin-1'``,\n                       ``'utf-8'``, and ``'cp437'`` are all valid encoding\n                       parameters.\n\n``transaction_mode``   May be ``'commit_on_success'`` (default) or\n                       ``'autocommit'``.\n\n``transform``          Setting this to False will disable coordinate\n                       transformations.  In other words, geometries will\n                       be inserted into the database unmodified from their\n                       original state in the data source.\n\n``unique``             Setting this to the name, or a tuple of names,\n                       from the given  model will create models unique\n                       only to the given name(s). Geometries from\n                       each feature will be added into the collection\n                       associated with the unique model.  Forces\n                       the transaction mode to be ``'autocommit'``.\n\n``using``              Sets the database to use when importing spatial data.\n                       Default is ``'default'``.\n=====================  =====================================================\n\n``save()`` Keyword Arguments\n----------------------------\n\n.. method:: LayerMapping.save(verbose=False, fid_range=False, step=False, progress=False, silent=False, stream=sys.stdout, strict=False)\n\nThe ``save()`` method also accepts keywords.  These keywords are\nused for controlling output logging, error handling, and for importing\nspecific feature ranges.\n\n===========================  =================================================\nSave Keyword Arguments       Description\n===========================  =================================================\n``fid_range``                May be set with a slice or tuple of\n                             (begin, end) feature ID's to map from\n                             the data source.  In other words, this\n                             keyword enables the user to selectively\n                             import a subset range of features in the\n                             geographic data source.\n\n``progress``                 When this keyword is set, status information\n                             will be printed giving the number of features\n                             processed and successfully saved.  By default,\n                             progress information will be printed every 1000\n                             features processed, however, this default may\n                             be overridden by setting this keyword with an\n                             integer for the desired interval.\n\n``silent``                   By default, non-fatal error notifications are\n                             printed to ``sys.stdout``, but this keyword may\n                             be set to disable these notifications.\n\n``step``                     If set with an integer, transactions will\n                             occur at every step interval. For example, if\n                             ``step=1000``, a commit would occur after the\n                             1,000th feature, the 2,000th feature etc.\n\n\n``stream``                   Status information will be written to this file\n                             handle.  Defaults to using ``sys.stdout``, but\n                             any object with a ``write`` method is supported.\n\n``strict``                   Execution of the model mapping will cease upon\n                             the first error encountered.  The default value\n                             (``False``)\n                             behavior is to attempt to continue.\n\n``verbose``                  If set, information will be printed\n                             subsequent to each model save\n                             executed on the database.\n===========================  =================================================\n\nTroubleshooting\n===============\n\nRunning out of memory\n---------------------\n\nAs noted in the warning at the top of this section, Django stores all SQL\nqueries when ``DEBUG=True``.  Set ``DEBUG=False`` in your settings, and this\nshould stop excessive memory use when running ``LayerMapping`` scripts.\n\nMySQL: ``max_allowed_packet`` error\n-----------------------------------\n\nIf you encounter the following error when using ``LayerMapping`` and MySQL::\n\n    OperationalError: (1153, \"Got a packet bigger than 'max_allowed_packet' bytes\")\n\nThen the solution is to increase the value of the ``max_allowed_packet``\nsetting in your MySQL configuration.  For example, the default value may\nbe something low like one megabyte -- the setting may be modified in MySQL's\nconfiguration file (``my.cnf``) in the ``[mysqld]`` section::\n\n    max_allowed_packet = 10M\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":124,"nodeType":"TextFile","repoName":null,"name":"querysets.txt","path":"docs/ref/models","text":"==========================\n``QuerySet`` API reference\n==========================\n\n.. currentmodule:: django.db.models.query\n\nThis document describes the details of the ``QuerySet`` API. It builds on the\nmaterial presented in the :doc:`model </topics/db/models>` and :doc:`database\nquery </topics/db/queries>` guides, so you'll probably want to read and\nunderstand those documents before reading this one.\n\nThroughout this reference we'll use the :ref:`example Weblog models\n<queryset-model-example>` presented in the :doc:`database query guide\n</topics/db/queries>`.\n\n.. _when-querysets-are-evaluated:\n\nWhen ``QuerySet``\\s are evaluated\n=================================\n\nInternally, a ``QuerySet`` can be constructed, filtered, sliced, and generally\npassed around without actually hitting the database. No database activity\nactually occurs until you do something to evaluate the queryset.\n\nYou can evaluate a ``QuerySet`` in the following ways:\n\n* **Iteration.** A ``QuerySet`` is iterable, and it executes its database\n  query the first time you iterate over it. For example, this will print\n  the headline of all entries in the database::\n\n      for e in Entry.objects.all():\n          print(e.headline)\n\n  Note: Don't use this if all you want to do is determine if at least one\n  result exists. It's more efficient to use :meth:`~QuerySet.exists`.\n\n* **Slicing.** As explained in :ref:`limiting-querysets`, a ``QuerySet`` can\n  be sliced, using Python's array-slicing syntax. Slicing an unevaluated\n  ``QuerySet`` usually returns another unevaluated ``QuerySet``, but Django\n  will execute the database query if you use the \"step\" parameter of slice\n  syntax, and will return a list. Slicing a ``QuerySet`` that has been\n  evaluated also returns a list.\n\n  Also note that even though slicing an unevaluated ``QuerySet`` returns\n  another unevaluated ``QuerySet``, modifying it further (e.g., adding\n  more filters, or modifying ordering) is not allowed, since that does not\n  translate well into SQL and it would not have a clear meaning either.\n\n* **Pickling/Caching.** See the following section for details of what\n  is involved when `pickling QuerySets`_. The important thing for the\n  purposes of this section is that the results are read from the database.\n\n* **repr().** A ``QuerySet`` is evaluated when you call ``repr()`` on it.\n  This is for convenience in the Python interactive interpreter, so you can\n  immediately see your results when using the API interactively.\n\n* **len().** A ``QuerySet`` is evaluated when you call ``len()`` on it.\n  This, as you might expect, returns the length of the result list.\n\n  Note: If you only need to determine the number of records in the set (and\n  don't need the actual objects), it's much more efficient to handle a count\n  at the database level using SQL's ``SELECT COUNT(*)``. Django provides a\n  :meth:`~QuerySet.count` method for precisely this reason.\n\n* **list().** Force evaluation of a ``QuerySet`` by calling ``list()`` on\n  it. For example::\n\n      entry_list = list(Entry.objects.all())\n\n* **bool().** Testing a ``QuerySet`` in a boolean context, such as using\n  ``bool()``, ``or``, ``and`` or an ``if`` statement, will cause the query\n  to be executed. If there is at least one result, the ``QuerySet`` is\n  ``True``, otherwise ``False``. For example::\n\n      if Entry.objects.filter(headline=\"Test\"):\n         print(\"There is at least one Entry with the headline Test\")\n\n  Note: If you only want to determine if at least one result exists (and don't\n  need the actual objects), it's more efficient to use :meth:`~QuerySet.exists`.\n\n.. _pickling QuerySets:\n\nPickling ``QuerySet``\\s\n-----------------------\n\nIf you :mod:`pickle` a ``QuerySet``, this will force all the results to be loaded\ninto memory prior to pickling. Pickling is usually used as a precursor to\ncaching and when the cached queryset is reloaded, you want the results to\nalready be present and ready for use (reading from the database can take some\ntime, defeating the purpose of caching). This means that when you unpickle a\n``QuerySet``, it contains the results at the moment it was pickled, rather\nthan the results that are currently in the database.\n\nIf you only want to pickle the necessary information to recreate the\n``QuerySet`` from the database at a later time, pickle the ``query`` attribute\nof the ``QuerySet``. You can then recreate the original ``QuerySet`` (without\nany results loaded) using some code like this::\n\n    >>> import pickle\n    >>> query = pickle.loads(s)     # Assuming 's' is the pickled string.\n    >>> qs = MyModel.objects.all()\n    >>> qs.query = query            # Restore the original 'query'.\n\nThe ``query`` attribute is an opaque object. It represents the internals of\nthe query construction and is not part of the public API. However, it is safe\n(and fully supported) to pickle and unpickle the attribute's contents as\ndescribed here.\n\n.. admonition:: You can't share pickles between versions\n\n    Pickles of ``QuerySets`` are only valid for the version of Django that\n    was used to generate them. If you generate a pickle using Django\n    version N, there is no guarantee that pickle will be readable with\n    Django version N+1. Pickles should not be used as part of a long-term\n    archival strategy.\n\n    Since pickle compatibility errors can be difficult to diagnose, such as\n    silently corrupted objects, a ``RuntimeWarning`` is raised when you try to\n    unpickle a queryset in a Django version that is different than the one in\n    which it was pickled.\n\n.. _queryset-api:\n\n``QuerySet`` API\n================\n\nHere's the formal declaration of a ``QuerySet``:\n\n.. class:: QuerySet(model=None, query=None, using=None, hints=None)\n\n    Usually when you'll interact with a ``QuerySet`` you'll use it by\n    :ref:`chaining filters <chaining-filters>`. To make this work, most\n    ``QuerySet`` methods return new querysets. These methods are covered in\n    detail later in this section.\n\n    The ``QuerySet`` class has two public attributes you can use for\n    introspection:\n\n    .. attribute:: ordered\n\n        ``True`` if the ``QuerySet`` is ordered — i.e. has an\n        :meth:`order_by()` clause or a default ordering on the model.\n        ``False`` otherwise.\n\n    .. attribute:: db\n\n        The database that will be used if this query is executed now.\n\n    .. note::\n\n        The ``query`` parameter to :class:`QuerySet` exists so that specialized\n        query subclasses can reconstruct internal query state. The value of the\n        parameter is an opaque representation of that query state and is not\n        part of a public API. To put it another way: if you need to ask, you\n        don't need to use it.\n\n.. currentmodule:: django.db.models.query.QuerySet\n\nMethods that return new ``QuerySet``\\s\n--------------------------------------\n\nDjango provides a range of ``QuerySet`` refinement methods that modify either\nthe types of results returned by the ``QuerySet`` or the way its SQL query is\nexecuted.\n\n``filter()``\n~~~~~~~~~~~~\n\n.. method:: filter(**kwargs)\n\nReturns a new ``QuerySet`` containing objects that match the given lookup\nparameters.\n\nThe lookup parameters (``**kwargs``) should be in the format described in\n`Field lookups`_ below. Multiple parameters are joined via ``AND`` in the\nunderlying SQL statement.\n\nIf you need to execute more complex queries (for example, queries with ``OR`` statements),\nyou can use :class:`Q objects <django.db.models.Q>`.\n\n``exclude()``\n~~~~~~~~~~~~~\n\n.. method:: exclude(**kwargs)\n\nReturns a new ``QuerySet`` containing objects that do *not* match the given\nlookup parameters.\n\nThe lookup parameters (``**kwargs``) should be in the format described in\n`Field lookups`_ below. Multiple parameters are joined via ``AND`` in the\nunderlying SQL statement, and the whole thing is enclosed in a ``NOT()``.\n\nThis example excludes all entries whose ``pub_date`` is later than 2005-1-3\nAND whose ``headline`` is \"Hello\"::\n\n    Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3), headline='Hello')\n\nIn SQL terms, that evaluates to:\n\n.. code-block:: sql\n\n    SELECT ...\n    WHERE NOT (pub_date > '2005-1-3' AND headline = 'Hello')\n\nThis example excludes all entries whose ``pub_date`` is later than 2005-1-3\nOR whose headline is \"Hello\"::\n\n    Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3)).exclude(headline='Hello')\n\nIn SQL terms, that evaluates to:\n\n.. code-block:: sql\n\n    SELECT ...\n    WHERE NOT pub_date > '2005-1-3'\n    AND NOT headline = 'Hello'\n\nNote the second example is more restrictive.\n\nIf you need to execute more complex queries (for example, queries with ``OR`` statements),\nyou can use :class:`Q objects <django.db.models.Q>`.\n\n``annotate()``\n~~~~~~~~~~~~~~\n\n.. method:: annotate(*args, **kwargs)\n\nAnnotates each object in the ``QuerySet`` with the provided list of :doc:`query\nexpressions </ref/models/expressions>`. An expression may be a simple value, a\nreference to a field on the model (or any related models), or an aggregate\nexpression (averages, sums, etc.) that has been computed over the objects that\nare related to the objects in the ``QuerySet``.\n\nEach argument to ``annotate()`` is an annotation that will be added\nto each object in the ``QuerySet`` that is returned.\n\nThe aggregation functions that are provided by Django are described\nin `Aggregation Functions`_ below.\n\nAnnotations specified using keyword arguments will use the keyword as\nthe alias for the annotation. Anonymous arguments will have an alias\ngenerated for them based upon the name of the aggregate function and\nthe model field that is being aggregated. Only aggregate expressions\nthat reference a single field can be anonymous arguments. Everything\nelse must be a keyword argument.\n\nFor example, if you were manipulating a list of blogs, you may want\nto determine how many entries have been made in each blog::\n\n    >>> from django.db.models import Count\n    >>> q = Blog.objects.annotate(Count('entry'))\n    # The name of the first blog\n    >>> q[0].name\n    'Blogasaurus'\n    # The number of entries on the first blog\n    >>> q[0].entry__count\n    42\n\nThe ``Blog`` model doesn't define an ``entry__count`` attribute by itself,\nbut by using a keyword argument to specify the aggregate function, you can\ncontrol the name of the annotation::\n\n    >>> q = Blog.objects.annotate(number_of_entries=Count('entry'))\n    # The number of entries on the first blog, using the name provided\n    >>> q[0].number_of_entries\n    42\n\nFor an in-depth discussion of aggregation, see :doc:`the topic guide on\nAggregation </topics/db/aggregation>`.\n\n``order_by()``\n~~~~~~~~~~~~~~\n\n.. method:: order_by(*fields)\n\nBy default, results returned by a ``QuerySet`` are ordered by the ordering\ntuple given by the ``ordering`` option in the model's ``Meta``. You can\noverride this on a per-``QuerySet`` basis by using the ``order_by`` method.\n\nExample::\n\n    Entry.objects.filter(pub_date__year=2005).order_by('-pub_date', 'headline')\n\nThe result above will be ordered by ``pub_date`` descending, then by\n``headline`` ascending. The negative sign in front of ``\"-pub_date\"`` indicates\n*descending* order. Ascending order is implied. To order randomly, use ``\"?\"``,\nlike so::\n\n    Entry.objects.order_by('?')\n\nNote: ``order_by('?')`` queries may be expensive and slow, depending on the\ndatabase backend you're using.\n\nTo order by a field in a different model, use the same syntax as when you are\nquerying across model relations. That is, the name of the field, followed by a\ndouble underscore (``__``), followed by the name of the field in the new model,\nand so on for as many models as you want to join. For example::\n\n    Entry.objects.order_by('blog__name', 'headline')\n\nIf you try to order by a field that is a relation to another model, Django will\nuse the default ordering on the related model, or order by the related model's\nprimary key if there is no :attr:`Meta.ordering\n<django.db.models.Options.ordering>` specified. For example, since the ``Blog``\nmodel has no default ordering specified::\n\n    Entry.objects.order_by('blog')\n\n...is identical to::\n\n    Entry.objects.order_by('blog__id')\n\nIf ``Blog`` had ``ordering = ['name']``, then the first queryset would be\nidentical to::\n\n    Entry.objects.order_by('blog__name')\n\nYou can also order by :doc:`query expressions </ref/models/expressions>` by\ncalling :meth:`~.Expression.asc` or :meth:`~.Expression.desc` on the\nexpression::\n\n    Entry.objects.order_by(Coalesce('summary', 'headline').desc())\n\n:meth:`~.Expression.asc` and :meth:`~.Expression.desc` have arguments\n(``nulls_first`` and ``nulls_last``) that control how null values are sorted.\n\nBe cautious when ordering by fields in related models if you are also using\n:meth:`distinct()`. See the note in :meth:`distinct` for an explanation of how\nrelated model ordering can change the expected results.\n\n.. note::\n    It is permissible to specify a multi-valued field to order the results by\n    (for example, a :class:`~django.db.models.ManyToManyField` field, or the\n    reverse relation of a :class:`~django.db.models.ForeignKey` field).\n\n    Consider this case::\n\n         class Event(Model):\n            parent = models.ForeignKey(\n                'self',\n                on_delete=models.CASCADE,\n                related_name='children',\n            )\n            date = models.DateField()\n\n         Event.objects.order_by('children__date')\n\n    Here, there could potentially be multiple ordering data for each ``Event``;\n    each ``Event`` with multiple ``children`` will be returned multiple times\n    into the new ``QuerySet`` that ``order_by()`` creates. In other words,\n    using ``order_by()`` on the ``QuerySet`` could return more items than you\n    were working on to begin with - which is probably neither expected nor\n    useful.\n\n    Thus, take care when using multi-valued field to order the results. **If**\n    you can be sure that there will only be one ordering piece of data for each\n    of the items you're ordering, this approach should not present problems. If\n    not, make sure the results are what you expect.\n\nThere's no way to specify whether ordering should be case sensitive. With\nrespect to case-sensitivity, Django will order results however your database\nbackend normally orders them.\n\nYou can order by a field converted to lowercase with\n:class:`~django.db.models.functions.Lower` which will achieve case-consistent\nordering::\n\n    Entry.objects.order_by(Lower('headline').desc())\n\nIf you don't want any ordering to be applied to a query, not even the default\nordering, call :meth:`order_by()` with no parameters.\n\nYou can tell if a query is ordered or not by checking the\n:attr:`.QuerySet.ordered` attribute, which will be ``True`` if the\n``QuerySet`` has been ordered in any way.\n\nEach ``order_by()`` call will clear any previous ordering. For example, this\nquery will be ordered by ``pub_date`` and not ``headline``::\n\n    Entry.objects.order_by('headline').order_by('pub_date')\n\n.. warning::\n\n    Ordering is not a free operation. Each field you add to the ordering\n    incurs a cost to your database. Each foreign key you add will\n    implicitly include all of its default orderings as well.\n\n    If a query doesn't have an ordering specified, results are returned from\n    the database in an unspecified order. A particular ordering is guaranteed\n    only when ordering by a set of fields that uniquely identify each object in\n    the results. For example, if a ``name`` field isn't unique, ordering by it\n    won't guarantee objects with the same name always appear in the same order.\n\n``reverse()``\n~~~~~~~~~~~~~\n\n.. method:: reverse()\n\nUse the ``reverse()`` method to reverse the order in which a queryset's\nelements are returned. Calling ``reverse()`` a second time restores the\nordering back to the normal direction.\n\nTo retrieve the \"last\" five items in a queryset, you could do this::\n\n    my_queryset.reverse()[:5]\n\nNote that this is not quite the same as slicing from the end of a sequence in\nPython. The above example will return the last item first, then the\npenultimate item and so on. If we had a Python sequence and looked at\n``seq[-5:]``, we would see the fifth-last item first. Django doesn't support\nthat mode of access (slicing from the end), because it's not possible to do it\nefficiently in SQL.\n\nAlso, note that ``reverse()`` should generally only be called on a ``QuerySet``\nwhich has a defined ordering (e.g., when querying against a model which defines\na default ordering, or when using :meth:`order_by()`). If no such ordering is\ndefined for a given ``QuerySet``, calling ``reverse()`` on it has no real\neffect (the ordering was undefined prior to calling ``reverse()``, and will\nremain undefined afterward).\n\n``distinct()``\n~~~~~~~~~~~~~~\n\n.. method:: distinct(*fields)\n\nReturns a new ``QuerySet`` that uses ``SELECT DISTINCT`` in its SQL query. This\neliminates duplicate rows from the query results.\n\nBy default, a ``QuerySet`` will not eliminate duplicate rows. In practice, this\nis rarely a problem, because simple queries such as ``Blog.objects.all()``\ndon't introduce the possibility of duplicate result rows. However, if your\nquery spans multiple tables, it's possible to get duplicate results when a\n``QuerySet`` is evaluated. That's when you'd use ``distinct()``.\n\n.. note::\n    Any fields used in an :meth:`order_by` call are included in the SQL\n    ``SELECT`` columns. This can sometimes lead to unexpected results when used\n    in conjunction with ``distinct()``. If you order by fields from a related\n    model, those fields will be added to the selected columns and they may make\n    otherwise duplicate rows appear to be distinct. Since the extra columns\n    don't appear in the returned results (they are only there to support\n    ordering), it sometimes looks like non-distinct results are being returned.\n\n    Similarly, if you use a :meth:`values()` query to restrict the columns\n    selected, the columns used in any :meth:`order_by()` (or default model\n    ordering) will still be involved and may affect uniqueness of the results.\n\n    The moral here is that if you are using ``distinct()`` be careful about\n    ordering by related models. Similarly, when using ``distinct()`` and\n    :meth:`values()` together, be careful when ordering by fields not in the\n    :meth:`values()` call.\n\nOn PostgreSQL only, you can pass positional arguments (``*fields``) in order to\nspecify the names of fields to which the ``DISTINCT`` should apply. This\ntranslates to a ``SELECT DISTINCT ON`` SQL query. Here's the difference. For a\nnormal ``distinct()`` call, the database compares *each* field in each row when\ndetermining which rows are distinct. For a ``distinct()`` call with specified\nfield names, the database will only compare the specified field names.\n\n.. note::\n    When you specify field names, you *must* provide an ``order_by()`` in the\n    ``QuerySet``, and the fields in ``order_by()`` must start with the fields in\n    ``distinct()``, in the same order.\n\n    For example, ``SELECT DISTINCT ON (a)`` gives you the first row for each\n    value in column ``a``. If you don't specify an order, you'll get some\n    arbitrary row.\n\nExamples (those after the first will only work on PostgreSQL)::\n\n    >>> Author.objects.distinct()\n    [...]\n\n    >>> Entry.objects.order_by('pub_date').distinct('pub_date')\n    [...]\n\n    >>> Entry.objects.order_by('blog').distinct('blog')\n    [...]\n\n    >>> Entry.objects.order_by('author', 'pub_date').distinct('author', 'pub_date')\n    [...]\n\n    >>> Entry.objects.order_by('blog__name', 'mod_date').distinct('blog__name', 'mod_date')\n    [...]\n\n    >>> Entry.objects.order_by('author', 'pub_date').distinct('author')\n    [...]\n\n.. note::\n    Keep in mind that :meth:`order_by` uses any default related model ordering\n    that has been defined. You might have to explicitly order by the relation\n    ``_id`` or referenced field to make sure the ``DISTINCT ON`` expressions\n    match those at the beginning of the ``ORDER BY`` clause. For example, if\n    the ``Blog`` model defined an :attr:`~django.db.models.Options.ordering` by\n    ``name``::\n\n        Entry.objects.order_by('blog').distinct('blog')\n\n    ...wouldn't work because the query would be ordered by ``blog__name`` thus\n    mismatching the ``DISTINCT ON`` expression. You'd have to explicitly order\n    by the relation ``_id`` field (``blog_id`` in this case) or the referenced\n    one (``blog__pk``) to make sure both expressions match.\n\n``values()``\n~~~~~~~~~~~~\n\n.. method:: values(*fields, **expressions)\n\nReturns a ``QuerySet`` that returns dictionaries, rather than model instances,\nwhen used as an iterable.\n\nEach of those dictionaries represents an object, with the keys corresponding to\nthe attribute names of model objects.\n\nThis example compares the dictionaries of ``values()`` with the normal model\nobjects::\n\n    # This list contains a Blog object.\n    >>> Blog.objects.filter(name__startswith='Beatles')\n    <QuerySet [<Blog: Beatles Blog>]>\n\n    # This list contains a dictionary.\n    >>> Blog.objects.filter(name__startswith='Beatles').values()\n    <QuerySet [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]>\n\nThe ``values()`` method takes optional positional arguments, ``*fields``, which\nspecify field names to which the ``SELECT`` should be limited. If you specify\nthe fields, each dictionary will contain only the field keys/values for the\nfields you specify. If you don't specify the fields, each dictionary will\ncontain a key and value for every field in the database table.\n\nExample::\n\n    >>> Blog.objects.values()\n    <QuerySet [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]>\n    >>> Blog.objects.values('id', 'name')\n    <QuerySet [{'id': 1, 'name': 'Beatles Blog'}]>\n\nThe ``values()`` method also takes optional keyword arguments,\n``**expressions``, which are passed through to :meth:`annotate`::\n\n    >>> from django.db.models.functions import Lower\n    >>> Blog.objects.values(lower_name=Lower('name'))\n    <QuerySet [{'lower_name': 'beatles blog'}]>\n\nYou can use built-in and :doc:`custom lookups </howto/custom-lookups>` in\nordering. For example::\n\n    >>> from django.db.models import CharField\n    >>> from django.db.models.functions import Lower\n    >>> CharField.register_lookup(Lower)\n    >>> Blog.objects.values('name__lower')\n    <QuerySet [{'name__lower': 'beatles blog'}]>\n\nAn aggregate within a ``values()`` clause is applied before other arguments\nwithin the same ``values()`` clause. If you need to group by another value,\nadd it to an earlier ``values()`` clause instead. For example::\n\n    >>> from django.db.models import Count\n    >>> Blog.objects.values('entry__authors', entries=Count('entry'))\n    <QuerySet [{'entry__authors': 1, 'entries': 20}, {'entry__authors': 1, 'entries': 13}]>\n    >>> Blog.objects.values('entry__authors').annotate(entries=Count('entry'))\n    <QuerySet [{'entry__authors': 1, 'entries': 33}]>\n\nA few subtleties that are worth mentioning:\n\n* If you have a field called ``foo`` that is a\n  :class:`~django.db.models.ForeignKey`, the default ``values()`` call\n  will return a dictionary key called ``foo_id``, since this is the name\n  of the hidden model attribute that stores the actual value (the ``foo``\n  attribute refers to the related model). When you are calling\n  ``values()`` and passing in field names, you can pass in either ``foo``\n  or ``foo_id`` and you will get back the same thing (the dictionary key\n  will match the field name you passed in).\n\n  For example::\n\n    >>> Entry.objects.values()\n    <QuerySet [{'blog_id': 1, 'headline': 'First Entry', ...}, ...]>\n\n    >>> Entry.objects.values('blog')\n    <QuerySet [{'blog': 1}, ...]>\n\n    >>> Entry.objects.values('blog_id')\n    <QuerySet [{'blog_id': 1}, ...]>\n\n* When using ``values()`` together with :meth:`distinct()`, be aware that\n  ordering can affect the results. See the note in :meth:`distinct` for\n  details.\n\n* If you use a ``values()`` clause after an :meth:`extra()` call,\n  any fields defined by a ``select`` argument in the :meth:`extra()` must\n  be explicitly included in the ``values()`` call. Any :meth:`extra()` call\n  made after a ``values()`` call will have its extra selected fields\n  ignored.\n\n* Calling :meth:`only()` and :meth:`defer()` after ``values()`` doesn't make\n  sense, so doing so will raise a ``NotImplementedError``.\n\n* Combining transforms and aggregates requires the use of two :meth:`annotate`\n  calls, either explicitly or as keyword arguments to :meth:`values`. As above,\n  if the transform has been registered on the relevant field type the first\n  :meth:`annotate` can be omitted, thus the following examples are equivalent::\n\n    >>> from django.db.models import CharField, Count\n    >>> from django.db.models.functions import Lower\n    >>> CharField.register_lookup(Lower)\n    >>> Blog.objects.values('entry__authors__name__lower').annotate(entries=Count('entry'))\n    <QuerySet [{'entry__authors__name__lower': 'test author', 'entries': 33}]>\n    >>> Blog.objects.values(\n    ...     entry__authors__name__lower=Lower('entry__authors__name')\n    ... ).annotate(entries=Count('entry'))\n    <QuerySet [{'entry__authors__name__lower': 'test author', 'entries': 33}]>\n    >>> Blog.objects.annotate(\n    ...     entry__authors__name__lower=Lower('entry__authors__name')\n    ... ).values('entry__authors__name__lower').annotate(entries=Count('entry'))\n    <QuerySet [{'entry__authors__name__lower': 'test author', 'entries': 33}]>\n\nIt is useful when you know you're only going to need values from a small number\nof the available fields and you won't need the functionality of a model\ninstance object. It's more efficient to select only the fields you need to use.\n\nFinally, note that you can call ``filter()``, ``order_by()``, etc. after the\n``values()`` call, that means that these two calls are identical::\n\n    Blog.objects.values().order_by('id')\n    Blog.objects.order_by('id').values()\n\nThe people who made Django prefer to put all the SQL-affecting methods first,\nfollowed (optionally) by any output-affecting methods (such as ``values()``),\nbut it doesn't really matter. This is your chance to really flaunt your\nindividualism.\n\nYou can also refer to fields on related models with reverse relations through\n``OneToOneField``, ``ForeignKey`` and ``ManyToManyField`` attributes::\n\n    >>> Blog.objects.values('name', 'entry__headline')\n    <QuerySet [{'name': 'My blog', 'entry__headline': 'An entry'},\n         {'name': 'My blog', 'entry__headline': 'Another entry'}, ...]>\n\n.. warning::\n\n   Because :class:`~django.db.models.ManyToManyField` attributes and reverse\n   relations can have multiple related rows, including these can have a\n   multiplier effect on the size of your result set. This will be especially\n   pronounced if you include multiple such fields in your ``values()`` query,\n   in which case all possible combinations will be returned.\n\n``values_list()``\n~~~~~~~~~~~~~~~~~\n\n.. method:: values_list(*fields, flat=False, named=False)\n\nThis is similar to ``values()`` except that instead of returning dictionaries,\nit returns tuples when iterated over. Each tuple contains the value from the\nrespective field or expression passed into the ``values_list()`` call — so the\nfirst item is the first field, etc. For example::\n\n    >>> Entry.objects.values_list('id', 'headline')\n    <QuerySet [(1, 'First entry'), ...]>\n    >>> from django.db.models.functions import Lower\n    >>> Entry.objects.values_list('id', Lower('headline'))\n    <QuerySet [(1, 'first entry'), ...]>\n\nIf you only pass in a single field, you can also pass in the ``flat``\nparameter. If ``True``, this will mean the returned results are single values,\nrather than one-tuples. An example should make the difference clearer::\n\n    >>> Entry.objects.values_list('id').order_by('id')\n    <QuerySet[(1,), (2,), (3,), ...]>\n\n    >>> Entry.objects.values_list('id', flat=True).order_by('id')\n    <QuerySet [1, 2, 3, ...]>\n\nIt is an error to pass in ``flat`` when there is more than one field.\n\nYou can pass ``named=True`` to get results as a\n:func:`~python:collections.namedtuple`::\n\n    >>> Entry.objects.values_list('id', 'headline', named=True)\n    <QuerySet [Row(id=1, headline='First entry'), ...]>\n\nUsing a named tuple may make use of the results more readable, at the expense\nof a small performance penalty for transforming the results into a named tuple.\n\nIf you don't pass any values to ``values_list()``, it will return all the\nfields in the model, in the order they were declared.\n\nA common need is to get a specific field value of a certain model instance. To\nachieve that, use ``values_list()`` followed by a ``get()`` call::\n\n    >>> Entry.objects.values_list('headline', flat=True).get(pk=1)\n    'First entry'\n\n``values()`` and ``values_list()`` are both intended as optimizations for a\nspecific use case: retrieving a subset of data without the overhead of creating\na model instance. This metaphor falls apart when dealing with many-to-many and\nother multivalued relations (such as the one-to-many relation of a reverse\nforeign key) because the \"one row, one object\" assumption doesn't hold.\n\nFor example, notice the behavior when querying across a\n:class:`~django.db.models.ManyToManyField`::\n\n    >>> Author.objects.values_list('name', 'entry__headline')\n    <QuerySet [('Noam Chomsky', 'Impressions of Gaza'),\n     ('George Orwell', 'Why Socialists Do Not Believe in Fun'),\n     ('George Orwell', 'In Defence of English Cooking'),\n     ('Don Quixote', None)]>\n\nAuthors with multiple entries appear multiple times and authors without any\nentries have ``None`` for the entry headline.\n\nSimilarly, when querying a reverse foreign key, ``None`` appears for entries\nnot having any author::\n\n    >>> Entry.objects.values_list('authors')\n    <QuerySet [('Noam Chomsky',), ('George Orwell',), (None,)]>\n\n``dates()``\n~~~~~~~~~~~\n\n.. method:: dates(field, kind, order='ASC')\n\nReturns a ``QuerySet`` that evaluates to a list of :class:`datetime.date`\nobjects representing all available dates of a particular kind within the\ncontents of the ``QuerySet``.\n\n``field`` should be the name of a ``DateField`` of your model.\n``kind`` should be either ``\"year\"``, ``\"month\"``, ``\"week\"``, or ``\"day\"``.\nEach :class:`datetime.date` object in the result list is \"truncated\" to the\ngiven ``type``.\n\n* ``\"year\"`` returns a list of all distinct year values for the field.\n* ``\"month\"`` returns a list of all distinct year/month values for the\n  field.\n* ``\"week\"`` returns a list of all distinct year/week values for the field. All\n  dates will be a Monday.\n* ``\"day\"`` returns a list of all distinct year/month/day values for the\n  field.\n\n``order``, which defaults to ``'ASC'``, should be either ``'ASC'`` or\n``'DESC'``. This specifies how to order the results.\n\nExamples::\n\n    >>> Entry.objects.dates('pub_date', 'year')\n    [datetime.date(2005, 1, 1)]\n    >>> Entry.objects.dates('pub_date', 'month')\n    [datetime.date(2005, 2, 1), datetime.date(2005, 3, 1)]\n    >>> Entry.objects.dates('pub_date', 'week')\n    [datetime.date(2005, 2, 14), datetime.date(2005, 3, 14)]\n    >>> Entry.objects.dates('pub_date', 'day')\n    [datetime.date(2005, 2, 20), datetime.date(2005, 3, 20)]\n    >>> Entry.objects.dates('pub_date', 'day', order='DESC')\n    [datetime.date(2005, 3, 20), datetime.date(2005, 2, 20)]\n    >>> Entry.objects.filter(headline__contains='Lennon').dates('pub_date', 'day')\n    [datetime.date(2005, 3, 20)]\n\n``datetimes()``\n~~~~~~~~~~~~~~~\n\n.. method:: datetimes(field_name, kind, order='ASC', tzinfo=None, is_dst=None)\n\nReturns a ``QuerySet`` that evaluates to a list of :class:`datetime.datetime`\nobjects representing all available dates of a particular kind within the\ncontents of the ``QuerySet``.\n\n``field_name`` should be the name of a ``DateTimeField`` of your model.\n\n``kind`` should be either ``\"year\"``, ``\"month\"``, ``\"week\"``, ``\"day\"``,\n``\"hour\"``, ``\"minute\"``, or ``\"second\"``. Each :class:`datetime.datetime`\nobject in the result list is \"truncated\" to the given ``type``.\n\n``order``, which defaults to ``'ASC'``, should be either ``'ASC'`` or\n``'DESC'``. This specifies how to order the results.\n\n``tzinfo`` defines the time zone to which datetimes are converted prior to\ntruncation. Indeed, a given datetime has different representations depending\non the time zone in use. This parameter must be a :class:`datetime.tzinfo`\nobject. If it's ``None``, Django uses the :ref:`current time zone\n<default-current-time-zone>`. It has no effect when :setting:`USE_TZ` is\n``False``.\n\n``is_dst`` indicates whether or not ``pytz`` should interpret nonexistent and\nambiguous datetimes in daylight saving time. By default (when ``is_dst=None``),\n``pytz`` raises an exception for such datetimes.\n\n.. versionadded:: 3.1\n\n    The ``is_dst`` parameter was added.\n\n.. _database-time-zone-definitions:\n\n.. note::\n\n    This function performs time zone conversions directly in the database.\n    As a consequence, your database must be able to interpret the value of\n    ``tzinfo.tzname(None)``. This translates into the following requirements:\n\n    - SQLite: no requirements. Conversions are performed in Python with pytz_\n      (installed when you install Django).\n    - PostgreSQL: no requirements (see `Time Zones`_).\n    - Oracle: no requirements (see `Choosing a Time Zone File`_).\n    - MySQL: load the time zone tables with `mysql_tzinfo_to_sql`_.\n\n    .. _pytz: http://pytz.sourceforge.net/\n    .. _Time Zones: https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-TIMEZONES\n    .. _Choosing a Time Zone File: https://docs.oracle.com/en/database/oracle/\n       oracle-database/18/nlspg/datetime-data-types-and-time-zone-support.html\n       #GUID-805AB986-DE12-4FEA-AF56-5AABCD2132DF\n    .. _mysql_tzinfo_to_sql: https://dev.mysql.com/doc/refman/en/mysql-tzinfo-to-sql.html\n\n``none()``\n~~~~~~~~~~\n\n.. method:: none()\n\nCalling none() will create a queryset that never returns any objects and no\nquery will be executed when accessing the results. A qs.none() queryset\nis an instance of ``EmptyQuerySet``.\n\nExamples::\n\n    >>> Entry.objects.none()\n    <QuerySet []>\n    >>> from django.db.models.query import EmptyQuerySet\n    >>> isinstance(Entry.objects.none(), EmptyQuerySet)\n    True\n\n``all()``\n~~~~~~~~~\n\n.. method:: all()\n\nReturns a *copy* of the current ``QuerySet`` (or ``QuerySet`` subclass).  This\ncan be useful in situations where you might want to pass in either a model\nmanager or a ``QuerySet`` and do further filtering on the result. After calling\n``all()`` on either object, you'll definitely have a ``QuerySet`` to work with.\n\nWhen a ``QuerySet`` is :ref:`evaluated <when-querysets-are-evaluated>`, it\ntypically caches its results. If the data in the database might have changed\nsince a ``QuerySet`` was evaluated, you can get updated results for the same\nquery by calling ``all()`` on a previously evaluated ``QuerySet``.\n\n``union()``\n~~~~~~~~~~~\n\n.. method:: union(*other_qs, all=False)\n\nUses SQL's ``UNION`` operator to combine the results of two or more\n``QuerySet``\\s. For example:\n\n    >>> qs1.union(qs2, qs3)\n\nThe ``UNION`` operator selects only distinct values by default. To allow\nduplicate values, use the ``all=True`` argument.\n\n``union()``, ``intersection()``, and ``difference()`` return model instances\nof the type of the first ``QuerySet`` even if the arguments are ``QuerySet``\\s\nof other models. Passing different models works as long as the ``SELECT`` list\nis the same in all ``QuerySet``\\s (at least the types, the names don't matter\nas long as the types in the same order). In such cases, you must use the column\nnames from the first ``QuerySet`` in ``QuerySet`` methods applied to the\nresulting ``QuerySet``. For example::\n\n    >>> qs1 = Author.objects.values_list('name')\n    >>> qs2 = Entry.objects.values_list('headline')\n    >>> qs1.union(qs2).order_by('name')\n\nIn addition, only ``LIMIT``, ``OFFSET``, ``COUNT(*)``, ``ORDER BY``, and\nspecifying columns (i.e. slicing, :meth:`count`, :meth:`order_by`, and\n:meth:`values()`/:meth:`values_list()`) are allowed on the resulting\n``QuerySet``. Further, databases place restrictions on what operations are\nallowed in the combined queries. For example, most databases don't allow\n``LIMIT`` or ``OFFSET`` in the combined queries.\n\n``intersection()``\n~~~~~~~~~~~~~~~~~~\n\n.. method:: intersection(*other_qs)\n\nUses SQL's ``INTERSECT`` operator to return the shared elements of two or more\n``QuerySet``\\s. For example:\n\n    >>> qs1.intersection(qs2, qs3)\n\nSee :meth:`union` for some restrictions.\n\n``difference()``\n~~~~~~~~~~~~~~~~\n\n.. method:: difference(*other_qs)\n\nUses SQL's ``EXCEPT`` operator to keep only elements present in the\n``QuerySet`` but not in some other ``QuerySet``\\s. For example::\n\n    >>> qs1.difference(qs2, qs3)\n\nSee :meth:`union` for some restrictions.\n\n``select_related()``\n~~~~~~~~~~~~~~~~~~~~\n\n.. method:: select_related(*fields)\n\nReturns a ``QuerySet`` that will \"follow\" foreign-key relationships, selecting\nadditional related-object data when it executes its query. This is a\nperformance booster which results in a single more complex query but means\nlater use of foreign-key relationships won't require database queries.\n\nThe following examples illustrate the difference between plain lookups and\n``select_related()`` lookups. Here's standard lookup::\n\n    # Hits the database.\n    e = Entry.objects.get(id=5)\n\n    # Hits the database again to get the related Blog object.\n    b = e.blog\n\nAnd here's ``select_related`` lookup::\n\n    # Hits the database.\n    e = Entry.objects.select_related('blog').get(id=5)\n\n    # Doesn't hit the database, because e.blog has been prepopulated\n    # in the previous query.\n    b = e.blog\n\nYou can use ``select_related()`` with any queryset of objects::\n\n    from django.utils import timezone\n\n    # Find all the blogs with entries scheduled to be published in the future.\n    blogs = set()\n\n    for e in Entry.objects.filter(pub_date__gt=timezone.now()).select_related('blog'):\n        # Without select_related(), this would make a database query for each\n        # loop iteration in order to fetch the related blog for each entry.\n        blogs.add(e.blog)\n\nThe order of ``filter()`` and ``select_related()`` chaining isn't important.\nThese querysets are equivalent::\n\n    Entry.objects.filter(pub_date__gt=timezone.now()).select_related('blog')\n    Entry.objects.select_related('blog').filter(pub_date__gt=timezone.now())\n\nYou can follow foreign keys in a similar way to querying them. If you have the\nfollowing models::\n\n    from django.db import models\n\n    class City(models.Model):\n        # ...\n        pass\n\n    class Person(models.Model):\n        # ...\n        hometown = models.ForeignKey(\n            City,\n            on_delete=models.SET_NULL,\n            blank=True,\n            null=True,\n        )\n\n    class Book(models.Model):\n        # ...\n        author = models.ForeignKey(Person, on_delete=models.CASCADE)\n\n... then a call to ``Book.objects.select_related('author__hometown').get(id=4)``\nwill cache the related ``Person`` *and* the related ``City``::\n\n    # Hits the database with joins to the author and hometown tables.\n    b = Book.objects.select_related('author__hometown').get(id=4)\n    p = b.author         # Doesn't hit the database.\n    c = p.hometown       # Doesn't hit the database.\n\n    # Without select_related()...\n    b = Book.objects.get(id=4)  # Hits the database.\n    p = b.author         # Hits the database.\n    c = p.hometown       # Hits the database.\n\nYou can refer to any :class:`~django.db.models.ForeignKey` or\n:class:`~django.db.models.OneToOneField` relation in the list of fields\npassed to ``select_related()``.\n\nYou can also refer to the reverse direction of a\n:class:`~django.db.models.OneToOneField` in the list of fields passed to\n``select_related`` — that is, you can traverse a\n:class:`~django.db.models.OneToOneField` back to the object on which the field\nis defined. Instead of specifying the field name, use the :attr:`related_name\n<django.db.models.ForeignKey.related_name>` for the field on the related object.\n\nThere may be some situations where you wish to call ``select_related()`` with a\nlot of related objects, or where you don't know all of the relations. In these\ncases it is possible to call ``select_related()`` with no arguments. This will\nfollow all non-null foreign keys it can find - nullable foreign keys must be\nspecified. This is not recommended in most cases as it is likely to make the\nunderlying query more complex, and return more data, than is actually needed.\n\nIf you need to clear the list of related fields added by past calls of\n``select_related`` on a ``QuerySet``, you can pass ``None`` as a parameter::\n\n   >>> without_relations = queryset.select_related(None)\n\nChaining ``select_related`` calls works in a similar way to other methods -\nthat is that ``select_related('foo', 'bar')`` is equivalent to\n``select_related('foo').select_related('bar')``.\n\n``prefetch_related()``\n~~~~~~~~~~~~~~~~~~~~~~\n\n.. method:: prefetch_related(*lookups)\n\nReturns a ``QuerySet`` that will automatically retrieve, in a single batch,\nrelated objects for each of the specified lookups.\n\nThis has a similar purpose to ``select_related``, in that both are designed to\nstop the deluge of database queries that is caused by accessing related objects,\nbut the strategy is quite different.\n\n``select_related`` works by creating an SQL join and including the fields of the\nrelated object in the ``SELECT`` statement. For this reason, ``select_related``\ngets the related objects in the same database query. However, to avoid the much\nlarger result set that would result from joining across a 'many' relationship,\n``select_related`` is limited to single-valued relationships - foreign key and\none-to-one.\n\n``prefetch_related``, on the other hand, does a separate lookup for each\nrelationship, and does the 'joining' in Python. This allows it to prefetch\nmany-to-many and many-to-one objects, which cannot be done using\n``select_related``, in addition to the foreign key and one-to-one relationships\nthat are supported by ``select_related``. It also supports prefetching of\n:class:`~django.contrib.contenttypes.fields.GenericRelation` and\n:class:`~django.contrib.contenttypes.fields.GenericForeignKey`, however, it\nmust be restricted to a homogeneous set of results. For example, prefetching\nobjects referenced by a ``GenericForeignKey`` is only supported if the query\nis restricted to one ``ContentType``.\n\nFor example, suppose you have these models::\n\n    from django.db import models\n\n    class Topping(models.Model):\n        name = models.CharField(max_length=30)\n\n    class Pizza(models.Model):\n        name = models.CharField(max_length=50)\n        toppings = models.ManyToManyField(Topping)\n\n        def __str__(self):\n            return \"%s (%s)\" % (\n                self.name,\n                \", \".join(topping.name for topping in self.toppings.all()),\n            )\n\nand run::\n\n    >>> Pizza.objects.all()\n    [\"Hawaiian (ham, pineapple)\", \"Seafood (prawns, smoked salmon)\"...\n\nThe problem with this is that every time ``Pizza.__str__()`` asks for\n``self.toppings.all()`` it has to query the database, so\n``Pizza.objects.all()`` will run a query on the Toppings table for **every**\nitem in the Pizza ``QuerySet``.\n\nWe can reduce to just two queries using ``prefetch_related``:\n\n    >>> Pizza.objects.all().prefetch_related('toppings')\n\nThis implies a ``self.toppings.all()`` for each ``Pizza``; now each time\n``self.toppings.all()`` is called, instead of having to go to the database for\nthe items, it will find them in a prefetched ``QuerySet`` cache that was\npopulated in a single query.\n\nThat is, all the relevant toppings will have been fetched in a single query,\nand used to make ``QuerySets`` that have a pre-filled cache of the relevant\nresults; these ``QuerySets`` are then used in the ``self.toppings.all()`` calls.\n\nThe additional queries in ``prefetch_related()`` are executed after the\n``QuerySet`` has begun to be evaluated and the primary query has been executed.\n\nIf you have an iterable of model instances, you can prefetch related attributes\non those instances using the :func:`~django.db.models.prefetch_related_objects`\nfunction.\n\nNote that the result cache of the primary ``QuerySet`` and all specified related\nobjects will then be fully loaded into memory. This changes the typical\nbehavior of ``QuerySets``, which normally try to avoid loading all objects into\nmemory before they are needed, even after a query has been executed in the\ndatabase.\n\n.. note::\n\n    Remember that, as always with ``QuerySets``, any subsequent chained methods\n    which imply a different database query will ignore previously cached\n    results, and retrieve data using a fresh database query. So, if you write\n    the following:\n\n        >>> pizzas = Pizza.objects.prefetch_related('toppings')\n        >>> [list(pizza.toppings.filter(spicy=True)) for pizza in pizzas]\n\n    ...then the fact that ``pizza.toppings.all()`` has been prefetched will not\n    help you. The ``prefetch_related('toppings')`` implied\n    ``pizza.toppings.all()``, but ``pizza.toppings.filter()`` is a new and\n    different query. The prefetched cache can't help here; in fact it hurts\n    performance, since you have done a database query that you haven't used. So\n    use this feature with caution!\n\n    Also, if you call the database-altering methods\n    :meth:`~django.db.models.fields.related.RelatedManager.add`,\n    :meth:`~django.db.models.fields.related.RelatedManager.remove`,\n    :meth:`~django.db.models.fields.related.RelatedManager.clear` or\n    :meth:`~django.db.models.fields.related.RelatedManager.set`, on\n    :class:`related managers<django.db.models.fields.related.RelatedManager>`,\n    any prefetched cache for the relation will be cleared.\n\nYou can also use the normal join syntax to do related fields of related\nfields. Suppose we have an additional model to the example above::\n\n    class Restaurant(models.Model):\n        pizzas = models.ManyToManyField(Pizza, related_name='restaurants')\n        best_pizza = models.ForeignKey(Pizza, related_name='championed_by', on_delete=models.CASCADE)\n\nThe following are all legal:\n\n    >>> Restaurant.objects.prefetch_related('pizzas__toppings')\n\nThis will prefetch all pizzas belonging to restaurants, and all toppings\nbelonging to those pizzas. This will result in a total of 3 database queries -\none for the restaurants, one for the pizzas, and one for the toppings.\n\n    >>> Restaurant.objects.prefetch_related('best_pizza__toppings')\n\nThis will fetch the best pizza and all the toppings for the best pizza for each\nrestaurant. This will be done in 3 database queries - one for the restaurants,\none for the 'best pizzas', and one for the toppings.\n\nThe ``best_pizza`` relationship could also be fetched using ``select_related``\nto reduce the query count to 2::\n\n    >>> Restaurant.objects.select_related('best_pizza').prefetch_related('best_pizza__toppings')\n\nSince the prefetch is executed after the main query (which includes the joins\nneeded by ``select_related``), it is able to detect that the ``best_pizza``\nobjects have already been fetched, and it will skip fetching them again.\n\nChaining ``prefetch_related`` calls will accumulate the lookups that are\nprefetched. To clear any ``prefetch_related`` behavior, pass ``None`` as a\nparameter:\n\n   >>> non_prefetched = qs.prefetch_related(None)\n\nOne difference to note when using ``prefetch_related`` is that objects created\nby a query can be shared between the different objects that they are related to\ni.e. a single Python model instance can appear at more than one point in the\ntree of objects that are returned. This will normally happen with foreign key\nrelationships. Typically this behavior will not be a problem, and will in fact\nsave both memory and CPU time.\n\nWhile ``prefetch_related`` supports prefetching ``GenericForeignKey``\nrelationships, the number of queries will depend on the data. Since a\n``GenericForeignKey`` can reference data in multiple tables, one query per table\nreferenced is needed, rather than one query for all the items. There could be\nadditional queries on the ``ContentType`` table if the relevant rows have not\nalready been fetched.\n\n``prefetch_related`` in most cases will be implemented using an SQL query that\nuses the 'IN' operator. This means that for a large ``QuerySet`` a large 'IN' clause\ncould be generated, which, depending on the database, might have performance\nproblems of its own when it comes to parsing or executing the SQL query. Always\nprofile for your use case!\n\nNote that if you use ``iterator()`` to run the query, ``prefetch_related()``\ncalls will be ignored since these two optimizations do not make sense together.\n\nYou can use the :class:`~django.db.models.Prefetch` object to further control\nthe prefetch operation.\n\nIn its simplest form ``Prefetch`` is equivalent to the traditional string based\nlookups:\n\n    >>> from django.db.models import Prefetch\n    >>> Restaurant.objects.prefetch_related(Prefetch('pizzas__toppings'))\n\nYou can provide a custom queryset with the optional ``queryset`` argument.\nThis can be used to change the default ordering of the queryset:\n\n    >>> Restaurant.objects.prefetch_related(\n    ...     Prefetch('pizzas__toppings', queryset=Toppings.objects.order_by('name')))\n\nOr to call :meth:`~django.db.models.query.QuerySet.select_related()` when\napplicable to reduce the number of queries even further:\n\n    >>> Pizza.objects.prefetch_related(\n    ...     Prefetch('restaurants', queryset=Restaurant.objects.select_related('best_pizza')))\n\nYou can also assign the prefetched result to a custom attribute with the optional\n``to_attr`` argument. The result will be stored directly in a list.\n\nThis allows prefetching the same relation multiple times with a different\n``QuerySet``; for instance:\n\n    >>> vegetarian_pizzas = Pizza.objects.filter(vegetarian=True)\n    >>> Restaurant.objects.prefetch_related(\n    ...     Prefetch('pizzas', to_attr='menu'),\n    ...     Prefetch('pizzas', queryset=vegetarian_pizzas, to_attr='vegetarian_menu'))\n\nLookups created with custom ``to_attr`` can still be traversed as usual by other\nlookups:\n\n    >>> vegetarian_pizzas = Pizza.objects.filter(vegetarian=True)\n    >>> Restaurant.objects.prefetch_related(\n    ...     Prefetch('pizzas', queryset=vegetarian_pizzas, to_attr='vegetarian_menu'),\n    ...     'vegetarian_menu__toppings')\n\nUsing ``to_attr`` is recommended when filtering down the prefetch result as it is\nless ambiguous than storing a filtered result in the related manager's cache:\n\n    >>> queryset = Pizza.objects.filter(vegetarian=True)\n    >>>\n    >>> # Recommended:\n    >>> restaurants = Restaurant.objects.prefetch_related(\n    ...     Prefetch('pizzas', queryset=queryset, to_attr='vegetarian_pizzas'))\n    >>> vegetarian_pizzas = restaurants[0].vegetarian_pizzas\n    >>>\n    >>> # Not recommended:\n    >>> restaurants = Restaurant.objects.prefetch_related(\n    ...     Prefetch('pizzas', queryset=queryset))\n    >>> vegetarian_pizzas = restaurants[0].pizzas.all()\n\nCustom prefetching also works with single related relations like\nforward ``ForeignKey`` or ``OneToOneField``. Generally you'll want to use\n:meth:`select_related()` for these relations, but there are a number of cases\nwhere prefetching with a custom ``QuerySet`` is useful:\n\n* You want to use a ``QuerySet`` that performs further prefetching\n  on related models.\n\n* You want to prefetch only a subset of the related objects.\n\n* You want to use performance optimization techniques like\n  :meth:`deferred fields <defer()>`:\n\n    >>> queryset = Pizza.objects.only('name')\n    >>>\n    >>> restaurants = Restaurant.objects.prefetch_related(\n    ...     Prefetch('best_pizza', queryset=queryset))\n\n.. note::\n\n    The ordering of lookups matters.\n\n    Take the following examples:\n\n       >>> prefetch_related('pizzas__toppings', 'pizzas')\n\n    This works even though it's unordered because ``'pizzas__toppings'``\n    already contains all the needed information, therefore the second argument\n    ``'pizzas'`` is actually redundant.\n\n        >>> prefetch_related('pizzas__toppings', Prefetch('pizzas', queryset=Pizza.objects.all()))\n\n    This will raise a ``ValueError`` because of the attempt to redefine the\n    queryset of a previously seen lookup. Note that an implicit queryset was\n    created to traverse ``'pizzas'`` as part of the ``'pizzas__toppings'``\n    lookup.\n\n        >>> prefetch_related('pizza_list__toppings', Prefetch('pizzas', to_attr='pizza_list'))\n\n    This will trigger an ``AttributeError`` because ``'pizza_list'`` doesn't exist yet\n    when ``'pizza_list__toppings'`` is being processed.\n\n    This consideration is not limited to the use of ``Prefetch`` objects. Some\n    advanced techniques may require that the lookups be performed in a\n    specific order to avoid creating extra queries; therefore it's recommended\n    to always carefully order ``prefetch_related`` arguments.\n\n``extra()``\n~~~~~~~~~~~\n\n.. method:: extra(select=None, where=None, params=None, tables=None, order_by=None, select_params=None)\n\nSometimes, the Django query syntax by itself can't easily express a complex\n``WHERE`` clause. For these edge cases, Django provides the ``extra()``\n``QuerySet`` modifier — a hook for injecting specific clauses into the SQL\ngenerated by a ``QuerySet``.\n\n.. admonition:: Use this method as a last resort\n\n    This is an old API that we aim to deprecate at some point in the future.\n    Use it only if you cannot express your query using other queryset methods.\n    If you do need to use it, please `file a ticket\n    <https://code.djangoproject.com/newticket>`_ using the `QuerySet.extra\n    keyword <https://code.djangoproject.com/query?status=assigned&status=new&keywords=~QuerySet.extra>`_\n    with your use case (please check the list of existing tickets first) so\n    that we can enhance the QuerySet API to allow removing ``extra()``. We are\n    no longer improving or fixing bugs for this method.\n\n    For example, this use of ``extra()``::\n\n        >>> qs.extra(\n        ...     select={'val': \"select col from sometable where othercol = %s\"},\n        ...     select_params=(someparam,),\n        ... )\n\n    is equivalent to::\n\n        >>> qs.annotate(val=RawSQL(\"select col from sometable where othercol = %s\", (someparam,)))\n\n    The main benefit of using :class:`~django.db.models.expressions.RawSQL` is\n    that you can set ``output_field`` if needed. The main downside is that if\n    you refer to some table alias of the queryset in the raw SQL, then it is\n    possible that Django might change that alias (for example, when the\n    queryset is used as a subquery in yet another query).\n\n.. warning::\n\n    You should be very careful whenever you use ``extra()``. Every time you use\n    it, you should escape any parameters that the user can control by using\n    ``params`` in order to protect against SQL injection attacks.\n\n    You also must not quote placeholders in the SQL string. This example is\n    vulnerable to SQL injection because of the quotes around ``%s``:\n\n    .. code-block:: sql\n\n        SELECT col FROM sometable WHERE othercol = '%s'  # unsafe!\n\n    You can read more about how Django's :ref:`SQL injection protection\n    <sql-injection-protection>` works.\n\nBy definition, these extra lookups may not be portable to different database\nengines (because you're explicitly writing SQL code) and violate the DRY\nprinciple, so you should avoid them if possible.\n\nSpecify one or more of ``params``, ``select``, ``where`` or ``tables``. None\nof the arguments is required, but you should use at least one of them.\n\n* ``select``\n\n  The ``select`` argument lets you put extra fields in the ``SELECT``\n  clause.  It should be a dictionary mapping attribute names to SQL\n  clauses to use to calculate that attribute.\n\n  Example::\n\n      Entry.objects.extra(select={'is_recent': \"pub_date > '2006-01-01'\"})\n\n  As a result, each ``Entry`` object will have an extra attribute,\n  ``is_recent``, a boolean representing whether the entry's ``pub_date``\n  is greater than Jan. 1, 2006.\n\n  Django inserts the given SQL snippet directly into the ``SELECT``\n  statement, so the resulting SQL of the above example would be something like:\n\n  .. code-block:: sql\n\n      SELECT blog_entry.*, (pub_date > '2006-01-01') AS is_recent\n      FROM blog_entry;\n\n\n  The next example is more advanced; it does a subquery to give each\n  resulting ``Blog`` object an ``entry_count`` attribute, an integer count\n  of associated ``Entry`` objects::\n\n      Blog.objects.extra(\n          select={\n              'entry_count': 'SELECT COUNT(*) FROM blog_entry WHERE blog_entry.blog_id = blog_blog.id'\n          },\n      )\n\n  In this particular case, we're exploiting the fact that the query will\n  already contain the ``blog_blog`` table in its ``FROM`` clause.\n\n  The resulting SQL of the above example would be:\n\n  .. code-block:: sql\n\n      SELECT blog_blog.*, (SELECT COUNT(*) FROM blog_entry WHERE blog_entry.blog_id = blog_blog.id) AS entry_count\n      FROM blog_blog;\n\n  Note that the parentheses required by most database engines around\n  subqueries are not required in Django's ``select`` clauses. Also note\n  that some database backends, such as some MySQL versions, don't support\n  subqueries.\n\n  In some rare cases, you might wish to pass parameters to the SQL\n  fragments in ``extra(select=...)``. For this purpose, use the\n  ``select_params`` parameter.\n\n  This will work, for example::\n\n      Blog.objects.extra(\n          select={'a': '%s', 'b': '%s'},\n          select_params=('one', 'two'),\n      )\n\n  If you need to use a literal ``%s`` inside your select string, use\n  the sequence ``%%s``.\n\n* ``where`` / ``tables``\n\n  You can define explicit SQL ``WHERE`` clauses — perhaps to perform\n  non-explicit joins — by using ``where``. You can manually add tables to\n  the SQL ``FROM`` clause by using ``tables``.\n\n  ``where`` and ``tables`` both take a list of strings. All ``where``\n  parameters are \"AND\"ed to any other search criteria.\n\n  Example::\n\n      Entry.objects.extra(where=[\"foo='a' OR bar = 'a'\", \"baz = 'a'\"])\n\n  ...translates (roughly) into the following SQL:\n\n  .. code-block:: sql\n\n      SELECT * FROM blog_entry WHERE (foo='a' OR bar='a') AND (baz='a')\n\n  Be careful when using the ``tables`` parameter if you're specifying\n  tables that are already used in the query. When you add extra tables\n  via the ``tables`` parameter, Django assumes you want that table\n  included an extra time, if it is already included. That creates a\n  problem, since the table name will then be given an alias. If a table\n  appears multiple times in an SQL statement, the second and subsequent\n  occurrences must use aliases so the database can tell them apart. If\n  you're referring to the extra table you added in the extra ``where``\n  parameter this is going to cause errors.\n\n  Normally you'll only be adding extra tables that don't already appear\n  in the query. However, if the case outlined above does occur, there are\n  a few solutions. First, see if you can get by without including the\n  extra table and use the one already in the query. If that isn't\n  possible, put your ``extra()`` call at the front of the queryset\n  construction so that your table is the first use of that table.\n  Finally, if all else fails, look at the query produced and rewrite your\n  ``where`` addition to use the alias given to your extra table. The\n  alias will be the same each time you construct the queryset in the same\n  way, so you can rely upon the alias name to not change.\n\n* ``order_by``\n\n  If you need to order the resulting queryset using some of the new\n  fields or tables you have included via ``extra()`` use the ``order_by``\n  parameter to ``extra()`` and pass in a sequence of strings. These\n  strings should either be model fields (as in the normal\n  :meth:`order_by()` method on querysets), of the form\n  ``table_name.column_name`` or an alias for a column that you specified\n  in the ``select`` parameter to ``extra()``.\n\n  For example::\n\n      q = Entry.objects.extra(select={'is_recent': \"pub_date > '2006-01-01'\"})\n      q = q.extra(order_by = ['-is_recent'])\n\n  This would sort all the items for which ``is_recent`` is true to the\n  front of the result set (``True`` sorts before ``False`` in a\n  descending ordering).\n\n  This shows, by the way, that you can make multiple calls to ``extra()``\n  and it will behave as you expect (adding new constraints each time).\n\n* ``params``\n\n  The ``where`` parameter described above may use standard Python\n  database string placeholders — ``'%s'`` to indicate parameters the\n  database engine should automatically quote. The ``params`` argument is\n  a list of any extra parameters to be substituted.\n\n  Example::\n\n      Entry.objects.extra(where=['headline=%s'], params=['Lennon'])\n\n  Always use ``params`` instead of embedding values directly into\n  ``where`` because ``params`` will ensure values are quoted correctly\n  according to your particular backend. For example, quotes will be\n  escaped correctly.\n\n  Bad::\n\n      Entry.objects.extra(where=[\"headline='Lennon'\"])\n\n  Good::\n\n      Entry.objects.extra(where=['headline=%s'], params=['Lennon'])\n\n.. warning::\n\n    If you are performing queries on MySQL, note that MySQL's silent type coercion\n    may cause unexpected results when mixing types. If you query on a string\n    type column, but with an integer value, MySQL will coerce the types of all values\n    in the table to an integer before performing the comparison. For example, if your\n    table contains the values ``'abc'``, ``'def'`` and you query for ``WHERE mycolumn=0``,\n    both rows will match. To prevent this, perform the correct typecasting\n    before using the value in a query.\n\n``defer()``\n~~~~~~~~~~~\n\n.. method:: defer(*fields)\n\nIn some complex data-modeling situations, your models might contain a lot of\nfields, some of which could contain a lot of data (for example, text fields),\nor require expensive processing to convert them to Python objects. If you are\nusing the results of a queryset in some situation where you don't know\nif you need those particular fields when you initially fetch the data, you can\ntell Django not to retrieve them from the database.\n\nThis is done by passing the names of the fields to not load to ``defer()``::\n\n    Entry.objects.defer(\"headline\", \"body\")\n\nA queryset that has deferred fields will still return model instances. Each\ndeferred field will be retrieved from the database if you access that field\n(one at a time, not all the deferred fields at once).\n\nYou can make multiple calls to ``defer()``. Each call adds new fields to the\ndeferred set::\n\n    # Defers both the body and headline fields.\n    Entry.objects.defer(\"body\").filter(rating=5).defer(\"headline\")\n\nThe order in which fields are added to the deferred set does not matter.\nCalling ``defer()`` with a field name that has already been deferred is\nharmless (the field will still be deferred).\n\nYou can defer loading of fields in related models (if the related models are\nloading via :meth:`select_related()`) by using the standard double-underscore\nnotation to separate related fields::\n\n    Blog.objects.select_related().defer(\"entry__headline\", \"entry__body\")\n\nIf you want to clear the set of deferred fields, pass ``None`` as a parameter\nto ``defer()``::\n\n    # Load all fields immediately.\n    my_queryset.defer(None)\n\nSome fields in a model won't be deferred, even if you ask for them. You can\nnever defer the loading of the primary key. If you are using\n:meth:`select_related()` to retrieve related models, you shouldn't defer the\nloading of the field that connects from the primary model to the related\none, doing so will result in an error.\n\n.. note::\n\n    The ``defer()`` method (and its cousin, :meth:`only()`, below) are only for\n    advanced use-cases. They provide an optimization for when you have analyzed\n    your queries closely and understand *exactly* what information you need and\n    have measured that the difference between returning the fields you need and\n    the full set of fields for the model will be significant.\n\n    Even if you think you are in the advanced use-case situation, **only use\n    defer() when you cannot, at queryset load time, determine if you will need\n    the extra fields or not**. If you are frequently loading and using a\n    particular subset of your data, the best choice you can make is to\n    normalize your models and put the non-loaded data into a separate model\n    (and database table). If the columns *must* stay in the one table for some\n    reason, create a model with ``Meta.managed = False`` (see the\n    :attr:`managed attribute <django.db.models.Options.managed>` documentation)\n    containing just the fields you normally need to load and use that where you\n    might otherwise call ``defer()``. This makes your code more explicit to the\n    reader, is slightly faster and consumes a little less memory in the Python\n    process.\n\n    For example, both of these models use the same underlying database table::\n\n        class CommonlyUsedModel(models.Model):\n            f1 = models.CharField(max_length=10)\n\n            class Meta:\n                managed = False\n                db_table = 'app_largetable'\n\n        class ManagedModel(models.Model):\n            f1 = models.CharField(max_length=10)\n            f2 = models.CharField(max_length=10)\n\n            class Meta:\n                db_table = 'app_largetable'\n\n        # Two equivalent QuerySets:\n        CommonlyUsedModel.objects.all()\n        ManagedModel.objects.all().defer('f2')\n\n    If many fields need to be duplicated in the unmanaged model, it may be best\n    to create an abstract model with the shared fields and then have the\n    unmanaged and managed models inherit from the abstract model.\n\n.. note::\n\n    When calling :meth:`~django.db.models.Model.save()` for instances with\n    deferred fields, only the loaded fields will be saved. See\n    :meth:`~django.db.models.Model.save()` for more details.\n\n``only()``\n~~~~~~~~~~\n\n.. method:: only(*fields)\n\nThe ``only()`` method is more or less the opposite of :meth:`defer()`. You call\nit with the fields that should *not* be deferred when retrieving a model.  If\nyou have a model where almost all the fields need to be deferred, using\n``only()`` to specify the complementary set of fields can result in simpler\ncode.\n\nSuppose you have a model with fields ``name``, ``age`` and ``biography``. The\nfollowing two querysets are the same, in terms of deferred fields::\n\n    Person.objects.defer(\"age\", \"biography\")\n    Person.objects.only(\"name\")\n\nWhenever you call ``only()`` it *replaces* the set of fields to load\nimmediately. The method's name is mnemonic: **only** those fields are loaded\nimmediately; the remainder are deferred. Thus, successive calls to ``only()``\nresult in only the final fields being considered::\n\n    # This will defer all fields except the headline.\n    Entry.objects.only(\"body\", \"rating\").only(\"headline\")\n\nSince ``defer()`` acts incrementally (adding fields to the deferred list), you\ncan combine calls to ``only()`` and ``defer()`` and things will behave\nlogically::\n\n    # Final result is that everything except \"headline\" is deferred.\n    Entry.objects.only(\"headline\", \"body\").defer(\"body\")\n\n    # Final result loads headline and body immediately (only() replaces any\n    # existing set of fields).\n    Entry.objects.defer(\"body\").only(\"headline\", \"body\")\n\nAll of the cautions in the note for the :meth:`defer` documentation apply to\n``only()`` as well. Use it cautiously and only after exhausting your other\noptions.\n\nUsing :meth:`only` and omitting a field requested using :meth:`select_related`\nis an error as well.\n\n.. note::\n\n    When calling :meth:`~django.db.models.Model.save()` for instances with\n    deferred fields, only the loaded fields will be saved. See\n    :meth:`~django.db.models.Model.save()` for more details.\n\n``using()``\n~~~~~~~~~~~\n\n.. method:: using(alias)\n\nThis method is for controlling which database the ``QuerySet`` will be\nevaluated against if you are using more than one database.  The only argument\nthis method takes is the alias of a database, as defined in\n:setting:`DATABASES`.\n\nFor example::\n\n    # queries the database with the 'default' alias.\n    >>> Entry.objects.all()\n\n    # queries the database with the 'backup' alias\n    >>> Entry.objects.using('backup')\n\n``select_for_update()``\n~~~~~~~~~~~~~~~~~~~~~~~\n\n.. method:: select_for_update(nowait=False, skip_locked=False, of=())\n\nReturns a queryset that will lock rows until the end of the transaction,\ngenerating a ``SELECT ... FOR UPDATE`` SQL statement on supported databases.\n\nFor example::\n\n    from django.db import transaction\n\n    entries = Entry.objects.select_for_update().filter(author=request.user)\n    with transaction.atomic():\n        for entry in entries:\n            ...\n\nWhen the queryset is evaluated (``for entry in entries`` in this case), all\nmatched entries will be locked until the end of the transaction block, meaning\nthat other transactions will be prevented from changing or acquiring locks on\nthem.\n\nUsually, if another transaction has already acquired a lock on one of the\nselected rows, the query will block until the lock is released. If this is\nnot the behavior you want, call ``select_for_update(nowait=True)``. This will\nmake the call non-blocking. If a conflicting lock is already acquired by\nanother transaction, :exc:`~django.db.DatabaseError` will be raised when the\nqueryset is evaluated. You can also ignore locked rows by using\n``select_for_update(skip_locked=True)`` instead. The ``nowait`` and\n``skip_locked`` are mutually exclusive and attempts to call\n``select_for_update()`` with both options enabled will result in a\n:exc:`ValueError`.\n\nBy default, ``select_for_update()`` locks all rows that are selected by the\nquery. For example, rows of related objects specified in :meth:`select_related`\nare locked in addition to rows of the queryset's model. If this isn't desired,\nspecify the related objects you want to lock in ``select_for_update(of=(...))``\nusing the same fields syntax as :meth:`select_related`. Use the value ``'self'``\nto refer to the queryset's model.\n\n.. admonition:: Lock parents models in ``select_for_update(of=(...))``\n\n    If you want to lock parents models when using :ref:`multi-table inheritance\n    <multi-table-inheritance>`, you must specify parent link fields (by default\n    ``<parent_model_name>_ptr``) in the ``of`` argument. For example::\n\n        Restaurant.objects.select_for_update(of=('self', 'place_ptr'))\n\nYou can't use ``select_for_update()`` on nullable relations::\n\n    >>> Person.objects.select_related('hometown').select_for_update()\n    Traceback (most recent call last):\n    ...\n    django.db.utils.NotSupportedError: FOR UPDATE cannot be applied to the nullable side of an outer join\n\nTo avoid that restriction, you can exclude null objects if you don't care about\nthem::\n\n    >>> Person.objects.select_related('hometown').select_for_update().exclude(hometown=None)\n    <QuerySet [<Person: ...)>, ...]>\n\nCurrently, the ``postgresql``, ``oracle``, and ``mysql`` database\nbackends support ``select_for_update()``. However, MariaDB 10.3+ supports only\nthe ``nowait`` argument and MySQL 8.0.1+ supports the ``nowait`` and\n``skip_locked`` arguments. MySQL and MariaDB don't support the ``of`` argument.\n\nPassing ``nowait=True``, ``skip_locked=True``, or ``of`` to\n``select_for_update()`` using database backends that do not support these\noptions, such as MySQL, raises a :exc:`~django.db.NotSupportedError`. This\nprevents code from unexpectedly blocking.\n\nEvaluating a queryset with ``select_for_update()`` in autocommit mode on\nbackends which support ``SELECT ... FOR UPDATE`` is a\n:exc:`~django.db.transaction.TransactionManagementError` error because the\nrows are not locked in that case. If allowed, this would facilitate data\ncorruption and could easily be caused by calling code that expects to be run in\na transaction outside of one.\n\nUsing ``select_for_update()`` on backends which do not support\n``SELECT ... FOR UPDATE`` (such as SQLite) will have no effect.\n``SELECT ... FOR UPDATE`` will not be added to the query, and an error isn't\nraised if ``select_for_update()`` is used in autocommit mode.\n\n.. warning::\n\n    Although ``select_for_update()`` normally fails in autocommit mode, since\n    :class:`~django.test.TestCase` automatically wraps each test in a\n    transaction, calling ``select_for_update()`` in a ``TestCase`` even outside\n    an :func:`~django.db.transaction.atomic()` block will (perhaps unexpectedly)\n    pass without raising a ``TransactionManagementError``. To properly test\n    ``select_for_update()`` you should use\n    :class:`~django.test.TransactionTestCase`.\n\n.. admonition:: Certain expressions may not be supported\n\n    PostgreSQL doesn't support ``select_for_update()`` with\n    :class:`~django.db.models.expressions.Window` expressions.\n\n``raw()``\n~~~~~~~~~\n\n.. method:: raw(raw_query, params=None, translations=None)\n\nTakes a raw SQL query, executes it, and returns a\n``django.db.models.query.RawQuerySet`` instance. This ``RawQuerySet`` instance\ncan be iterated over just like a normal ``QuerySet`` to provide object\ninstances.\n\nSee the :doc:`/topics/db/sql` for more information.\n\n.. warning::\n\n  ``raw()`` always triggers a new query and doesn't account for previous\n  filtering. As such, it should generally be called from the ``Manager`` or\n  from a fresh ``QuerySet`` instance.\n\nOperators that return new ``QuerySet``\\s\n----------------------------------------\n\nCombined querysets must use the same model.\n\nAND (``&``)\n~~~~~~~~~~~\n\nCombines two ``QuerySet``\\s using the SQL ``AND`` operator.\n\nThe following are equivalent::\n\n    Model.objects.filter(x=1) & Model.objects.filter(y=2)\n    Model.objects.filter(x=1, y=2)\n    from django.db.models import Q\n    Model.objects.filter(Q(x=1) & Q(y=2))\n\nSQL equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE x=1 AND y=2\n\nOR (``|``)\n~~~~~~~~~~\n\nCombines two ``QuerySet``\\s using the SQL ``OR`` operator.\n\nThe following are equivalent::\n\n    Model.objects.filter(x=1) | Model.objects.filter(y=2)\n    from django.db.models import Q\n    Model.objects.filter(Q(x=1) | Q(y=2))\n\nSQL equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE x=1 OR y=2\n\nMethods that do not return ``QuerySet``\\s\n-----------------------------------------\n\nThe following ``QuerySet`` methods evaluate the ``QuerySet`` and return\nsomething *other than* a ``QuerySet``.\n\nThese methods do not use a cache (see :ref:`caching-and-querysets`). Rather,\nthey query the database each time they're called.\n\n``get()``\n~~~~~~~~~\n\n.. method:: get(**kwargs)\n\nReturns the object matching the given lookup parameters, which should be in\nthe format described in `Field lookups`_.\n\n``get()`` raises :exc:`~django.core.exceptions.MultipleObjectsReturned` if more\nthan one object was found. The\n:exc:`~django.core.exceptions.MultipleObjectsReturned` exception is an\nattribute of the model class.\n\n``get()`` raises a :exc:`~django.db.models.Model.DoesNotExist` exception if an\nobject wasn't found for the given parameters. This exception is an attribute\nof the model class. Example::\n\n    Entry.objects.get(id='foo') # raises Entry.DoesNotExist\n\nThe :exc:`~django.db.models.Model.DoesNotExist` exception inherits from\n:exc:`django.core.exceptions.ObjectDoesNotExist`, so you can target multiple\n:exc:`~django.db.models.Model.DoesNotExist` exceptions. Example::\n\n    from django.core.exceptions import ObjectDoesNotExist\n    try:\n        e = Entry.objects.get(id=3)\n        b = Blog.objects.get(id=1)\n    except ObjectDoesNotExist:\n        print(\"Either the entry or blog doesn't exist.\")\n\nIf you expect a queryset to return one row, you can use ``get()`` without any\narguments to return the object for that row::\n\n    entry = Entry.objects.filter(...).exclude(...).get()\n\n``create()``\n~~~~~~~~~~~~\n\n.. method:: create(**kwargs)\n\nA convenience method for creating an object and saving it all in one step.  Thus::\n\n    p = Person.objects.create(first_name=\"Bruce\", last_name=\"Springsteen\")\n\nand::\n\n    p = Person(first_name=\"Bruce\", last_name=\"Springsteen\")\n    p.save(force_insert=True)\n\nare equivalent.\n\nThe :ref:`force_insert <ref-models-force-insert>` parameter is documented\nelsewhere, but all it means is that a new object will always be created.\nNormally you won't need to worry about this. However, if your model contains a\nmanual primary key value that you set and if that value already exists in the\ndatabase, a call to ``create()`` will fail with an\n:exc:`~django.db.IntegrityError` since primary keys must be unique. Be\nprepared to handle the exception if you are using manual primary keys.\n\n``get_or_create()``\n~~~~~~~~~~~~~~~~~~~\n\n.. method:: get_or_create(defaults=None, **kwargs)\n\nA convenience method for looking up an object with the given ``kwargs`` (may be\nempty if your model has defaults for all fields), creating one if necessary.\n\nReturns a tuple of ``(object, created)``, where ``object`` is the retrieved or\ncreated object and ``created`` is a boolean specifying whether a new object was\ncreated.\n\nThis is meant to prevent duplicate objects from being created when requests are\nmade in parallel, and as a shortcut to boilerplatish code. For example::\n\n    try:\n        obj = Person.objects.get(first_name='John', last_name='Lennon')\n    except Person.DoesNotExist:\n        obj = Person(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9))\n        obj.save()\n\nHere, with concurrent requests, multiple attempts to save a ``Person`` with\nthe same parameters may be made. To avoid this race condition, the above\nexample can be rewritten using ``get_or_create()`` like so::\n\n    obj, created = Person.objects.get_or_create(\n        first_name='John',\n        last_name='Lennon',\n        defaults={'birthday': date(1940, 10, 9)},\n    )\n\nAny keyword arguments passed to ``get_or_create()`` — *except* an optional one\ncalled ``defaults`` — will be used in a :meth:`get()` call. If an object is\nfound, ``get_or_create()`` returns a tuple of that object and ``False``.\n\n.. warning::\n\n    This method is atomic assuming that the database enforces uniqueness of the\n    keyword arguments (see :attr:`~django.db.models.Field.unique` or\n    :attr:`~django.db.models.Options.unique_together`). If the fields used in the\n    keyword arguments do not have a uniqueness constraint, concurrent calls to\n    this method may result in multiple rows with the same parameters being\n    inserted.\n\nYou can specify more complex conditions for the retrieved object by chaining\n``get_or_create()`` with ``filter()`` and using :class:`Q objects\n<django.db.models.Q>`. For example, to retrieve Robert or Bob Marley if either\nexists, and create the latter otherwise::\n\n    from django.db.models import Q\n\n    obj, created = Person.objects.filter(\n        Q(first_name='Bob') | Q(first_name='Robert'),\n    ).get_or_create(last_name='Marley', defaults={'first_name': 'Bob'})\n\nIf multiple objects are found, ``get_or_create()`` raises\n:exc:`~django.core.exceptions.MultipleObjectsReturned`. If an object is *not*\nfound, ``get_or_create()`` will instantiate and save a new object, returning a\ntuple of the new object and ``True``. The new object will be created roughly\naccording to this algorithm::\n\n    params = {k: v for k, v in kwargs.items() if '__' not in k}\n    params.update({k: v() if callable(v) else v for k, v in defaults.items()})\n    obj = self.model(**params)\n    obj.save()\n\nIn English, that means start with any non-``'defaults'`` keyword argument that\ndoesn't contain a double underscore (which would indicate a non-exact lookup).\nThen add the contents of ``defaults``, overriding any keys if necessary, and\nuse the result as the keyword arguments to the model class. If there are any\ncallables in ``defaults``, evaluate them. As hinted at above, this is a\nsimplification of the algorithm that is used, but it contains all the pertinent\ndetails. The internal implementation has some more error-checking than this and\nhandles some extra edge-conditions; if you're interested, read the code.\n\nIf you have a field named ``defaults`` and want to use it as an exact lookup in\n``get_or_create()``, use ``'defaults__exact'``, like so::\n\n    Foo.objects.get_or_create(defaults__exact='bar', defaults={'defaults': 'baz'})\n\nThe ``get_or_create()`` method has similar error behavior to :meth:`create()`\nwhen you're using manually specified primary keys. If an object needs to be\ncreated and the key already exists in the database, an\n:exc:`~django.db.IntegrityError` will be raised.\n\nFinally, a word on using ``get_or_create()`` in Django views. Please make sure\nto use it only in ``POST`` requests unless you have a good reason not to.\n``GET`` requests shouldn't have any effect on data. Instead, use ``POST``\nwhenever a request to a page has a side effect on your data. For more, see\n:rfc:`Safe methods <7231#section-4.2.1>` in the HTTP spec.\n\n.. warning::\n\n  You can use ``get_or_create()`` through :class:`~django.db.models.ManyToManyField`\n  attributes and reverse relations. In that case you will restrict the queries\n  inside the context of that relation. That could lead you to some integrity\n  problems if you don't use it consistently.\n\n  Being the following models::\n\n      class Chapter(models.Model):\n          title = models.CharField(max_length=255, unique=True)\n\n      class Book(models.Model):\n          title = models.CharField(max_length=256)\n          chapters = models.ManyToManyField(Chapter)\n\n  You can use ``get_or_create()`` through Book's chapters field, but it only\n  fetches inside the context of that book::\n\n      >>> book = Book.objects.create(title=\"Ulysses\")\n      >>> book.chapters.get_or_create(title=\"Telemachus\")\n      (<Chapter: Telemachus>, True)\n      >>> book.chapters.get_or_create(title=\"Telemachus\")\n      (<Chapter: Telemachus>, False)\n      >>> Chapter.objects.create(title=\"Chapter 1\")\n      <Chapter: Chapter 1>\n      >>> book.chapters.get_or_create(title=\"Chapter 1\")\n      # Raises IntegrityError\n\n  This is happening because it's trying to get or create \"Chapter 1\" through the\n  book \"Ulysses\", but it can't do any of them: the relation can't fetch that\n  chapter because it isn't related to that book, but it can't create it either\n  because ``title`` field should be unique.\n\n``update_or_create()``\n~~~~~~~~~~~~~~~~~~~~~~\n\n.. method:: update_or_create(defaults=None, **kwargs)\n\nA convenience method for updating an object with the given ``kwargs``, creating\na new one if necessary. The ``defaults`` is a dictionary of (field, value)\npairs used to update the object. The values in ``defaults`` can be callables.\n\nReturns a tuple of ``(object, created)``, where ``object`` is the created or\nupdated object and ``created`` is a boolean specifying whether a new object was\ncreated.\n\nThe ``update_or_create`` method tries to fetch an object from database based on\nthe given ``kwargs``. If a match is found, it updates the fields passed in the\n``defaults`` dictionary.\n\nThis is meant as a shortcut to boilerplatish code. For example::\n\n    defaults = {'first_name': 'Bob'}\n    try:\n        obj = Person.objects.get(first_name='John', last_name='Lennon')\n        for key, value in defaults.items():\n            setattr(obj, key, value)\n        obj.save()\n    except Person.DoesNotExist:\n        new_values = {'first_name': 'John', 'last_name': 'Lennon'}\n        new_values.update(defaults)\n        obj = Person(**new_values)\n        obj.save()\n\nThis pattern gets quite unwieldy as the number of fields in a model goes up.\nThe above example can be rewritten using ``update_or_create()`` like so::\n\n    obj, created = Person.objects.update_or_create(\n        first_name='John', last_name='Lennon',\n        defaults={'first_name': 'Bob'},\n    )\n\nFor detailed description how names passed in ``kwargs`` are resolved see\n:meth:`get_or_create`.\n\nAs described above in :meth:`get_or_create`, this method is prone to a\nrace-condition which can result in multiple rows being inserted simultaneously\nif uniqueness is not enforced at the database level.\n\nLike :meth:`get_or_create` and :meth:`create`, if you're using manually\nspecified primary keys and an object needs to be created but the key already\nexists in the database, an :exc:`~django.db.IntegrityError` is raised.\n\n``bulk_create()``\n~~~~~~~~~~~~~~~~~\n\n.. method:: bulk_create(objs, batch_size=None, ignore_conflicts=False)\n\nThis method inserts the provided list of objects into the database in an\nefficient manner (generally only 1 query, no matter how many objects there\nare)::\n\n    >>> Entry.objects.bulk_create([\n    ...     Entry(headline='This is a test'),\n    ...     Entry(headline='This is only a test'),\n    ... ])\n\nThis has a number of caveats though:\n\n* The model's ``save()`` method will not be called, and the ``pre_save`` and\n  ``post_save`` signals will not be sent.\n* It does not work with child models in a multi-table inheritance scenario.\n* If the model's primary key is an :class:`~django.db.models.AutoField`, the\n  primary key attribute can only be retrieved on certain databases (currently\n  PostgreSQL and MariaDB 10.5+). On other databases, it will not be set.\n* It does not work with many-to-many relationships.\n* It casts ``objs`` to a list, which fully evaluates ``objs`` if it's a\n  generator. The cast allows inspecting all objects so that any objects with a\n  manually set primary key can be inserted first. If you want to insert objects\n  in batches without evaluating the entire generator at once, you can use this\n  technique as long as the objects don't have any manually set primary keys::\n\n    from itertools import islice\n\n    batch_size = 100\n    objs = (Entry(headline='Test %s' % i) for i in range(1000))\n    while True:\n        batch = list(islice(objs, batch_size))\n        if not batch:\n            break\n        Entry.objects.bulk_create(batch, batch_size)\n\nThe ``batch_size`` parameter controls how many objects are created in a single\nquery. The default is to create all objects in one batch, except for SQLite\nwhere the default is such that at most 999 variables per query are used.\n\nOn databases that support it (all but Oracle), setting the ``ignore_conflicts``\nparameter to ``True`` tells the database to ignore failure to insert any rows\nthat fail constraints such as duplicate unique values. Enabling this parameter\ndisables setting the primary key on each model instance (if the database\nnormally supports it).\n\nReturns ``objs`` as cast to a list, in the same order as provided.\n\n.. versionchanged:: 3.1\n\n    Support for the fetching primary key attributes on MariaDB 10.5+ was added.\n\n``bulk_update()``\n~~~~~~~~~~~~~~~~~\n\n.. method:: bulk_update(objs, fields, batch_size=None)\n\nThis method efficiently updates the given fields on the provided model\ninstances, generally with one query::\n\n    >>> objs = [\n    ...    Entry.objects.create(headline='Entry 1'),\n    ...    Entry.objects.create(headline='Entry 2'),\n    ... ]\n    >>> objs[0].headline = 'This is entry 1'\n    >>> objs[1].headline = 'This is entry 2'\n    >>> Entry.objects.bulk_update(objs, ['headline'])\n\n:meth:`.QuerySet.update` is used to save the changes, so this is more efficient\nthan iterating through the list of models and calling ``save()`` on each of\nthem, but it has a few caveats:\n\n* You cannot update the model's primary key.\n* Each model's ``save()`` method isn't called, and the\n  :attr:`~django.db.models.signals.pre_save` and\n  :attr:`~django.db.models.signals.post_save` signals aren't sent.\n* If updating a large number of columns in a large number of rows, the SQL\n  generated can be very large. Avoid this by specifying a suitable\n  ``batch_size``.\n* Updating fields defined on multi-table inheritance ancestors will incur an\n  extra query per ancestor.\n* If ``objs`` contains duplicates, only the first one is updated.\n\nThe ``batch_size`` parameter controls how many objects are saved in a single\nquery. The default is to update all objects in one batch, except for SQLite\nand Oracle which have restrictions on the number of variables used in a query.\n\n``count()``\n~~~~~~~~~~~\n\n.. method:: count()\n\nReturns an integer representing the number of objects in the database matching\nthe ``QuerySet``.\n\nExample::\n\n    # Returns the total number of entries in the database.\n    Entry.objects.count()\n\n    # Returns the number of entries whose headline contains 'Lennon'\n    Entry.objects.filter(headline__contains='Lennon').count()\n\nA ``count()`` call performs a ``SELECT COUNT(*)`` behind the scenes, so you\nshould always use ``count()`` rather than loading all of the record into Python\nobjects and calling ``len()`` on the result (unless you need to load the\nobjects into memory anyway, in which case ``len()`` will be faster).\n\nNote that if you want the number of items in a ``QuerySet`` and are also\nretrieving model instances from it (for example, by iterating over it), it's\nprobably more efficient to use ``len(queryset)`` which won't cause an extra\ndatabase query like ``count()`` would.\n\n``in_bulk()``\n~~~~~~~~~~~~~\n\n.. method:: in_bulk(id_list=None, field_name='pk')\n\nTakes a list of field values (``id_list``) and the ``field_name`` for those\nvalues, and returns a dictionary mapping each value to an instance of the\nobject with the given field value. If ``id_list`` isn't provided, all objects\nin the queryset are returned. ``field_name`` must be a unique field, and it\ndefaults to the primary key.\n\nExample::\n\n    >>> Blog.objects.in_bulk([1])\n    {1: <Blog: Beatles Blog>}\n    >>> Blog.objects.in_bulk([1, 2])\n    {1: <Blog: Beatles Blog>, 2: <Blog: Cheddar Talk>}\n    >>> Blog.objects.in_bulk([])\n    {}\n    >>> Blog.objects.in_bulk()\n    {1: <Blog: Beatles Blog>, 2: <Blog: Cheddar Talk>, 3: <Blog: Django Weblog>}\n    >>> Blog.objects.in_bulk(['beatles_blog'], field_name='slug')\n    {'beatles_blog': <Blog: Beatles Blog>}\n\nIf you pass ``in_bulk()`` an empty list, you'll get an empty dictionary.\n\n``iterator()``\n~~~~~~~~~~~~~~\n\n.. method:: iterator(chunk_size=2000)\n\nEvaluates the ``QuerySet`` (by performing the query) and returns an iterator\n(see :pep:`234`) over the results. A ``QuerySet`` typically caches its results\ninternally so that repeated evaluations do not result in additional queries. In\ncontrast, ``iterator()`` will read results directly, without doing any caching\nat the ``QuerySet`` level (internally, the default iterator calls ``iterator()``\nand caches the return value). For a ``QuerySet`` which returns a large number of\nobjects that you only need to access once, this can result in better\nperformance and a significant reduction in memory.\n\nNote that using ``iterator()`` on a ``QuerySet`` which has already been\nevaluated will force it to evaluate again, repeating the query.\n\nAlso, use of ``iterator()`` causes previous ``prefetch_related()`` calls to be\nignored since these two optimizations do not make sense together.\n\nDepending on the database backend, query results will either be loaded all at\nonce or streamed from the database using server-side cursors.\n\nWith server-side cursors\n^^^^^^^^^^^^^^^^^^^^^^^^\n\nOracle and :ref:`PostgreSQL <postgresql-server-side-cursors>` use server-side\ncursors to stream results from the database without loading the entire result\nset into memory.\n\nThe Oracle database driver always uses server-side cursors.\n\nWith server-side cursors, the ``chunk_size`` parameter specifies the number of\nresults to cache at the database driver level. Fetching bigger chunks\ndiminishes the number of round trips between the database driver and the\ndatabase, at the expense of memory.\n\nOn PostgreSQL, server-side cursors will only be used when the\n:setting:`DISABLE_SERVER_SIDE_CURSORS <DATABASE-DISABLE_SERVER_SIDE_CURSORS>`\nsetting is ``False``. Read :ref:`transaction-pooling-server-side-cursors` if\nyou're using a connection pooler configured in transaction pooling mode. When\nserver-side cursors are disabled, the behavior is the same as databases that\ndon't support server-side cursors.\n\nWithout server-side cursors\n^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nMySQL doesn't support streaming results, hence the Python database driver loads\nthe entire result set into memory. The result set is then transformed into\nPython row objects by the database adapter using the ``fetchmany()`` method\ndefined in :pep:`249`.\n\nSQLite can fetch results in batches using ``fetchmany()``, but since SQLite\ndoesn't provide isolation between queries within a connection, be careful when\nwriting to the table being iterated over. See :ref:`sqlite-isolation` for\nmore information.\n\nThe ``chunk_size`` parameter controls the size of batches Django retrieves from\nthe database driver. Larger batches decrease the overhead of communicating with\nthe database driver at the expense of a slight increase in memory consumption.\n\nThe default value of ``chunk_size``, 2000, comes from `a calculation on the\npsycopg mailing list <https://www.postgresql.org/message-id/4D2F2C71.8080805%40dndg.it>`_:\n\n    Assuming rows of 10-20 columns with a mix of textual and numeric data, 2000\n    is going to fetch less than 100KB of data, which seems a good compromise\n    between the number of rows transferred and the data discarded if the loop\n    is exited early.\n\n``latest()``\n~~~~~~~~~~~~\n\n.. method:: latest(*fields)\n\nReturns the latest object in the table based on the given field(s).\n\nThis example returns the latest ``Entry`` in the table, according to the\n``pub_date`` field::\n\n    Entry.objects.latest('pub_date')\n\nYou can also choose the latest based on several fields. For example, to select\nthe ``Entry`` with the earliest ``expire_date`` when two entries have the same\n``pub_date``::\n\n    Entry.objects.latest('pub_date', '-expire_date')\n\nThe negative sign in ``'-expire_date'`` means to sort ``expire_date`` in\n*descending* order. Since ``latest()`` gets the last result, the ``Entry`` with\nthe earliest ``expire_date`` is selected.\n\nIf your model's :ref:`Meta <meta-options>` specifies\n:attr:`~django.db.models.Options.get_latest_by`, you can omit any arguments to\n``earliest()`` or ``latest()``. The fields specified in\n:attr:`~django.db.models.Options.get_latest_by` will be used by default.\n\nLike :meth:`get()`, ``earliest()`` and ``latest()`` raise\n:exc:`~django.db.models.Model.DoesNotExist` if there is no object with the\ngiven parameters.\n\nNote that ``earliest()`` and ``latest()`` exist purely for convenience and\nreadability.\n\n.. admonition:: ``earliest()`` and ``latest()`` may return instances with null dates.\n\n    Since ordering is delegated to the database, results on fields that allow\n    null values may be ordered differently if you use different databases. For\n    example, PostgreSQL and MySQL sort null values as if they are higher than\n    non-null values, while SQLite does the opposite.\n\n    You may want to filter out null values::\n\n        Entry.objects.filter(pub_date__isnull=False).latest('pub_date')\n\n``earliest()``\n~~~~~~~~~~~~~~\n\n.. method:: earliest(*fields)\n\nWorks otherwise like :meth:`~django.db.models.query.QuerySet.latest` except\nthe direction is changed.\n\n``first()``\n~~~~~~~~~~~\n\n.. method:: first()\n\nReturns the first object matched by the queryset, or ``None`` if there\nis no matching object. If the ``QuerySet`` has no ordering defined, then the\nqueryset is automatically ordered by the primary key. This can affect\naggregation results as described in :ref:`aggregation-ordering-interaction`.\n\nExample::\n\n    p = Article.objects.order_by('title', 'pub_date').first()\n\nNote that ``first()`` is a convenience method, the following code sample is\nequivalent to the above example::\n\n    try:\n        p = Article.objects.order_by('title', 'pub_date')[0]\n    except IndexError:\n        p = None\n\n``last()``\n~~~~~~~~~~\n\n.. method:: last()\n\nWorks like  :meth:`first()`, but returns the last object in the queryset.\n\n``aggregate()``\n~~~~~~~~~~~~~~~\n\n.. method:: aggregate(*args, **kwargs)\n\nReturns a dictionary of aggregate values (averages, sums, etc.) calculated over\nthe ``QuerySet``. Each argument to ``aggregate()`` specifies a value that will\nbe included in the dictionary that is returned.\n\nThe aggregation functions that are provided by Django are described in\n`Aggregation Functions`_ below. Since aggregates are also :doc:`query\nexpressions </ref/models/expressions>`, you may combine aggregates with other\naggregates or values to create complex aggregates.\n\nAggregates specified using keyword arguments will use the keyword as the name\nfor the annotation. Anonymous arguments will have a name generated for them\nbased upon the name of the aggregate function and the model field that is being\naggregated. Complex aggregates cannot use anonymous arguments and must specify\na keyword argument as an alias.\n\nFor example, when you are working with blog entries, you may want to know the\nnumber of authors that have contributed blog entries::\n\n    >>> from django.db.models import Count\n    >>> q = Blog.objects.aggregate(Count('entry'))\n    {'entry__count': 16}\n\nBy using a keyword argument to specify the aggregate function, you can\ncontrol the name of the aggregation value that is returned::\n\n    >>> q = Blog.objects.aggregate(number_of_entries=Count('entry'))\n    {'number_of_entries': 16}\n\nFor an in-depth discussion of aggregation, see :doc:`the topic guide on\nAggregation </topics/db/aggregation>`.\n\n``exists()``\n~~~~~~~~~~~~\n\n.. method:: exists()\n\nReturns ``True`` if the :class:`.QuerySet` contains any results, and ``False``\nif not. This tries to perform the query in the simplest and fastest way\npossible, but it *does* execute nearly the same query as a normal\n:class:`.QuerySet` query.\n\n:meth:`~.QuerySet.exists` is useful for searches relating to both\nobject membership in a :class:`.QuerySet` and to the existence of any objects in\na :class:`.QuerySet`, particularly in the context of a large :class:`.QuerySet`.\n\nThe most efficient method of finding whether a model with a unique field\n(e.g. ``primary_key``) is a member of a :class:`.QuerySet` is::\n\n    entry = Entry.objects.get(pk=123)\n    if some_queryset.filter(pk=entry.pk).exists():\n        print(\"Entry contained in queryset\")\n\nWhich will be faster than the following which requires evaluating and iterating\nthrough the entire queryset::\n\n    if entry in some_queryset:\n       print(\"Entry contained in QuerySet\")\n\nAnd to find whether a queryset contains any items::\n\n    if some_queryset.exists():\n        print(\"There is at least one object in some_queryset\")\n\nWhich will be faster than::\n\n    if some_queryset:\n        print(\"There is at least one object in some_queryset\")\n\n... but not by a large degree (hence needing a large queryset for efficiency\ngains).\n\nAdditionally, if a ``some_queryset`` has not yet been evaluated, but you know\nthat it will be at some point, then using ``some_queryset.exists()`` will do\nmore overall work (one query for the existence check plus an extra one to later\nretrieve the results) than using ``bool(some_queryset)``, which retrieves the\nresults and then checks if any were returned.\n\n``update()``\n~~~~~~~~~~~~\n\n.. method:: update(**kwargs)\n\nPerforms an SQL update query for the specified fields, and returns\nthe number of rows matched (which may not be equal to the number of rows\nupdated if some rows already have the new value).\n\nFor example, to turn comments off for all blog entries published in 2010,\nyou could do this::\n\n    >>> Entry.objects.filter(pub_date__year=2010).update(comments_on=False)\n\n(This assumes your ``Entry`` model has fields ``pub_date`` and ``comments_on``.)\n\nYou can update multiple fields — there's no limit on how many. For example,\nhere we update the ``comments_on`` and ``headline`` fields::\n\n    >>> Entry.objects.filter(pub_date__year=2010).update(comments_on=False, headline='This is old')\n\nThe ``update()`` method is applied instantly, and the only restriction on the\n:class:`.QuerySet` that is updated is that it can only update columns in the\nmodel's main table, not on related models. You can't do this, for example::\n\n    >>> Entry.objects.update(blog__name='foo') # Won't work!\n\nFiltering based on related fields is still possible, though::\n\n    >>> Entry.objects.filter(blog__id=1).update(comments_on=True)\n\nYou cannot call ``update()`` on a :class:`.QuerySet` that has had a slice taken\nor can otherwise no longer be filtered.\n\nThe ``update()`` method returns the number of affected rows::\n\n    >>> Entry.objects.filter(id=64).update(comments_on=True)\n    1\n\n    >>> Entry.objects.filter(slug='nonexistent-slug').update(comments_on=True)\n    0\n\n    >>> Entry.objects.filter(pub_date__year=2010).update(comments_on=False)\n    132\n\nIf you're just updating a record and don't need to do anything with the model\nobject, the most efficient approach is to call ``update()``, rather than\nloading the model object into memory. For example, instead of doing this::\n\n    e = Entry.objects.get(id=10)\n    e.comments_on = False\n    e.save()\n\n...do this::\n\n    Entry.objects.filter(id=10).update(comments_on=False)\n\nUsing ``update()`` also prevents a race condition wherein something might\nchange in your database in the short period of time between loading the object\nand calling ``save()``.\n\nFinally, realize that ``update()`` does an update at the SQL level and, thus,\ndoes not call any ``save()`` methods on your models, nor does it emit the\n:attr:`~django.db.models.signals.pre_save` or\n:attr:`~django.db.models.signals.post_save` signals (which are a consequence of\ncalling :meth:`Model.save() <django.db.models.Model.save>`). If you want to\nupdate a bunch of records for a model that has a custom\n:meth:`~django.db.models.Model.save()` method, loop over them and call\n:meth:`~django.db.models.Model.save()`, like this::\n\n    for e in Entry.objects.filter(pub_date__year=2010):\n        e.comments_on = False\n        e.save()\n\n``delete()``\n~~~~~~~~~~~~\n\n.. method:: delete()\n\nPerforms an SQL delete query on all rows in the :class:`.QuerySet` and\nreturns the number of objects deleted and a dictionary with the number of\ndeletions per object type.\n\nThe ``delete()`` is applied instantly. You cannot call ``delete()`` on a\n:class:`.QuerySet` that has had a slice taken or can otherwise no longer be\nfiltered.\n\nFor example, to delete all the entries in a particular blog::\n\n    >>> b = Blog.objects.get(pk=1)\n\n    # Delete all the entries belonging to this Blog.\n    >>> Entry.objects.filter(blog=b).delete()\n    (4, {'weblog.Entry': 2, 'weblog.Entry_authors': 2})\n\nBy default, Django's :class:`~django.db.models.ForeignKey` emulates the SQL\nconstraint ``ON DELETE CASCADE`` — in other words, any objects with foreign\nkeys pointing at the objects to be deleted will be deleted along with them.\nFor example::\n\n    >>> blogs = Blog.objects.all()\n\n    # This will delete all Blogs and all of their Entry objects.\n    >>> blogs.delete()\n    (5, {'weblog.Blog': 1, 'weblog.Entry': 2, 'weblog.Entry_authors': 2})\n\nThis cascade behavior is customizable via the\n:attr:`~django.db.models.ForeignKey.on_delete` argument to the\n:class:`~django.db.models.ForeignKey`.\n\nThe ``delete()`` method does a bulk delete and does not call any ``delete()``\nmethods on your models. It does, however, emit the\n:data:`~django.db.models.signals.pre_delete` and\n:data:`~django.db.models.signals.post_delete` signals for all deleted objects\n(including cascaded deletions).\n\nDjango needs to fetch objects into memory to send signals and handle cascades.\nHowever, if there are no cascades and no signals, then Django may take a\nfast-path and delete objects without fetching into memory. For large\ndeletes this can result in significantly reduced memory usage. The amount of\nexecuted queries can be reduced, too.\n\nForeignKeys which are set to :attr:`~django.db.models.ForeignKey.on_delete`\n``DO_NOTHING`` do not prevent taking the fast-path in deletion.\n\nNote that the queries generated in object deletion is an implementation\ndetail subject to change.\n\n``as_manager()``\n~~~~~~~~~~~~~~~~\n\n.. classmethod:: as_manager()\n\nClass method that returns an instance of :class:`~django.db.models.Manager`\nwith a copy of the ``QuerySet``’s methods. See\n:ref:`create-manager-with-queryset-methods` for more details.\n\n``explain()``\n~~~~~~~~~~~~~\n\n.. method:: explain(format=None, **options)\n\nReturns a string of the ``QuerySet``’s execution plan, which details how the\ndatabase would execute the query, including any indexes or joins that would be\nused. Knowing these details may help you improve the performance of slow\nqueries.\n\nFor example, when using PostgreSQL::\n\n    >>> print(Blog.objects.filter(title='My Blog').explain())\n    Seq Scan on blog  (cost=0.00..35.50 rows=10 width=12)\n      Filter: (title = 'My Blog'::bpchar)\n\nThe output differs significantly between databases.\n\n``explain()`` is supported by all built-in database backends except Oracle\nbecause an implementation there isn't straightforward.\n\nThe ``format`` parameter changes the output format from the databases's\ndefault, which is usually text-based. PostgreSQL supports ``'TEXT'``,\n``'JSON'``, ``'YAML'``, and ``'XML'`` formats. MariaDB and MySQL support\n``'TEXT'`` (also called ``'TRADITIONAL'``) and ``'JSON'`` formats. MySQL\n8.0.16+ also supports an improved ``'TREE'`` format, which is similar to\nPostgreSQL's ``'TEXT'`` output and is used by default, if supported.\n\nSome databases accept flags that can return more information about the query.\nPass these flags as keyword arguments. For example, when using PostgreSQL::\n\n    >>> print(Blog.objects.filter(title='My Blog').explain(verbose=True))\n    Seq Scan on public.blog  (cost=0.00..35.50 rows=10 width=12) (actual time=0.004..0.004 rows=10 loops=1)\n      Output: id, title\n      Filter: (blog.title = 'My Blog'::bpchar)\n    Planning time: 0.064 ms\n    Execution time: 0.058 ms\n\nOn some databases, flags may cause the query to be executed which could have\nadverse effects on your database. For example, the ``ANALYZE`` flag supported\nby MariaDB, MySQL 8.0.18+, and PostgreSQL could result in changes to data if\nthere are triggers or if a function is called, even for a ``SELECT`` query.\n\n.. versionchanged:: 3.1\n\n    Support for the ``'TREE'`` format on MySQL 8.0.16+ and ``analyze`` option\n    on MariaDB and MySQL 8.0.18+ were added.\n\n.. _field-lookups:\n\n``Field`` lookups\n-----------------\n\nField lookups are how you specify the meat of an SQL ``WHERE`` clause. They're\nspecified as keyword arguments to the ``QuerySet`` methods :meth:`filter()`,\n:meth:`exclude()` and :meth:`get()`.\n\nFor an introduction, see :ref:`models and database queries documentation\n<field-lookups-intro>`.\n\nDjango's built-in lookups are listed below. It is also possible to write\n:doc:`custom lookups </howto/custom-lookups>` for model fields.\n\nAs a convenience when no lookup type is provided (like in\n``Entry.objects.get(id=14)``) the lookup type is assumed to be :lookup:`exact`.\n\n.. fieldlookup:: exact\n\n``exact``\n~~~~~~~~~\n\nExact match. If the value provided for comparison is ``None``, it will be\ninterpreted as an SQL ``NULL`` (see :lookup:`isnull` for more details).\n\nExamples::\n\n    Entry.objects.get(id__exact=14)\n    Entry.objects.get(id__exact=None)\n\nSQL equivalents:\n\n.. code-block:: sql\n\n    SELECT ... WHERE id = 14;\n    SELECT ... WHERE id IS NULL;\n\n.. admonition:: MySQL comparisons\n\n    In MySQL, a database table's \"collation\" setting determines whether\n    ``exact`` comparisons are case-sensitive. This is a database setting, *not*\n    a Django setting. It's possible to configure your MySQL tables to use\n    case-sensitive comparisons, but some trade-offs are involved. For more\n    information about this, see the :ref:`collation section <mysql-collation>`\n    in the :doc:`databases </ref/databases>` documentation.\n\n.. fieldlookup:: iexact\n\n``iexact``\n~~~~~~~~~~\n\nCase-insensitive exact match. If the value provided for comparison is ``None``,\nit will be interpreted as an SQL ``NULL`` (see :lookup:`isnull` for more\ndetails).\n\nExample::\n\n    Blog.objects.get(name__iexact='beatles blog')\n    Blog.objects.get(name__iexact=None)\n\nSQL equivalents:\n\n.. code-block:: sql\n\n    SELECT ... WHERE name ILIKE 'beatles blog';\n    SELECT ... WHERE name IS NULL;\n\nNote the first query will match ``'Beatles Blog'``, ``'beatles blog'``,\n``'BeAtLes BLoG'``, etc.\n\n.. admonition:: SQLite users\n\n    When using the SQLite backend and non-ASCII strings, bear in mind the\n    :ref:`database note <sqlite-string-matching>` about string comparisons.\n    SQLite does not do case-insensitive matching for non-ASCII strings.\n\n.. fieldlookup:: contains\n\n``contains``\n~~~~~~~~~~~~\n\nCase-sensitive containment test.\n\nExample::\n\n    Entry.objects.get(headline__contains='Lennon')\n\nSQL equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE headline LIKE '%Lennon%';\n\nNote this will match the headline ``'Lennon honored today'`` but not ``'lennon\nhonored today'``.\n\n.. admonition:: SQLite users\n\n    SQLite doesn't support case-sensitive ``LIKE`` statements; ``contains``\n    acts like ``icontains`` for SQLite. See the :ref:`database note\n    <sqlite-string-matching>` for more information.\n\n\n.. fieldlookup:: icontains\n\n``icontains``\n~~~~~~~~~~~~~\n\nCase-insensitive containment test.\n\nExample::\n\n    Entry.objects.get(headline__icontains='Lennon')\n\nSQL equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE headline ILIKE '%Lennon%';\n\n.. admonition:: SQLite users\n\n    When using the SQLite backend and non-ASCII strings, bear in mind the\n    :ref:`database note <sqlite-string-matching>` about string comparisons.\n\n.. fieldlookup:: in\n\n``in``\n~~~~~~\n\nIn a given iterable; often a list, tuple, or queryset. It's not a common use\ncase, but strings (being iterables) are accepted.\n\nExamples::\n\n    Entry.objects.filter(id__in=[1, 3, 4])\n    Entry.objects.filter(headline__in='abc')\n\nSQL equivalents:\n\n.. code-block:: sql\n\n    SELECT ... WHERE id IN (1, 3, 4);\n    SELECT ... WHERE headline IN ('a', 'b', 'c');\n\nYou can also use a queryset to dynamically evaluate the list of values\ninstead of providing a list of literal values::\n\n    inner_qs = Blog.objects.filter(name__contains='Cheddar')\n    entries = Entry.objects.filter(blog__in=inner_qs)\n\nThis queryset will be evaluated as subselect statement:\n\n.. code-block:: sql\n\n    SELECT ... WHERE blog.id IN (SELECT id FROM ... WHERE NAME LIKE '%Cheddar%')\n\nIf you pass in a ``QuerySet`` resulting from ``values()`` or ``values_list()``\nas the value to an ``__in`` lookup, you need to ensure you are only extracting\none field in the result. For example, this will work (filtering on the blog\nnames)::\n\n    inner_qs = Blog.objects.filter(name__contains='Ch').values('name')\n    entries = Entry.objects.filter(blog__name__in=inner_qs)\n\nThis example will raise an exception, since the inner query is trying to\nextract two field values, where only one is expected::\n\n    # Bad code! Will raise a TypeError.\n    inner_qs = Blog.objects.filter(name__contains='Ch').values('name', 'id')\n    entries = Entry.objects.filter(blog__name__in=inner_qs)\n\n.. _nested-queries-performance:\n\n.. admonition:: Performance considerations\n\n    Be cautious about using nested queries and understand your database\n    server's performance characteristics (if in doubt, benchmark!). Some\n    database backends, most notably MySQL, don't optimize nested queries very\n    well. It is more efficient, in those cases, to extract a list of values\n    and then pass that into the second query. That is, execute two queries\n    instead of one::\n\n        values = Blog.objects.filter(\n                name__contains='Cheddar').values_list('pk', flat=True)\n        entries = Entry.objects.filter(blog__in=list(values))\n\n    Note the ``list()`` call around the Blog ``QuerySet`` to force execution of\n    the first query. Without it, a nested query would be executed, because\n    :ref:`querysets-are-lazy`.\n\n.. fieldlookup:: gt\n\n``gt``\n~~~~~~\n\nGreater than.\n\nExample::\n\n    Entry.objects.filter(id__gt=4)\n\nSQL equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE id > 4;\n\n.. fieldlookup:: gte\n\n``gte``\n~~~~~~~\n\nGreater than or equal to.\n\n.. fieldlookup:: lt\n\n``lt``\n~~~~~~\n\nLess than.\n\n.. fieldlookup:: lte\n\n``lte``\n~~~~~~~\n\nLess than or equal to.\n\n.. fieldlookup:: startswith\n\n``startswith``\n~~~~~~~~~~~~~~\n\nCase-sensitive starts-with.\n\nExample::\n\n    Entry.objects.filter(headline__startswith='Lennon')\n\nSQL equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE headline LIKE 'Lennon%';\n\nSQLite doesn't support case-sensitive ``LIKE`` statements; ``startswith`` acts\nlike ``istartswith`` for SQLite.\n\n.. fieldlookup:: istartswith\n\n``istartswith``\n~~~~~~~~~~~~~~~\n\nCase-insensitive starts-with.\n\nExample::\n\n    Entry.objects.filter(headline__istartswith='Lennon')\n\nSQL equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE headline ILIKE 'Lennon%';\n\n.. admonition:: SQLite users\n\n    When using the SQLite backend and non-ASCII strings, bear in mind the\n    :ref:`database note <sqlite-string-matching>` about string comparisons.\n\n.. fieldlookup:: endswith\n\n``endswith``\n~~~~~~~~~~~~\n\nCase-sensitive ends-with.\n\nExample::\n\n    Entry.objects.filter(headline__endswith='Lennon')\n\nSQL equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE headline LIKE '%Lennon';\n\n.. admonition:: SQLite users\n\n    SQLite doesn't support case-sensitive ``LIKE`` statements; ``endswith``\n    acts like ``iendswith`` for SQLite. Refer to the :ref:`database note\n    <sqlite-string-matching>` documentation for more.\n\n.. fieldlookup:: iendswith\n\n``iendswith``\n~~~~~~~~~~~~~\n\nCase-insensitive ends-with.\n\nExample::\n\n    Entry.objects.filter(headline__iendswith='Lennon')\n\nSQL equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE headline ILIKE '%Lennon'\n\n.. admonition:: SQLite users\n\n    When using the SQLite backend and non-ASCII strings, bear in mind the\n    :ref:`database note <sqlite-string-matching>` about string comparisons.\n\n.. fieldlookup:: range\n\n``range``\n~~~~~~~~~\n\nRange test (inclusive).\n\nExample::\n\n    import datetime\n    start_date = datetime.date(2005, 1, 1)\n    end_date = datetime.date(2005, 3, 31)\n    Entry.objects.filter(pub_date__range=(start_date, end_date))\n\nSQL equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE pub_date BETWEEN '2005-01-01' and '2005-03-31';\n\nYou can use ``range`` anywhere you can use ``BETWEEN`` in SQL — for dates,\nnumbers and even characters.\n\n.. warning::\n\n    Filtering a ``DateTimeField`` with dates won't include items on the last\n    day, because the bounds are interpreted as \"0am on the given date\". If\n    ``pub_date`` was a ``DateTimeField``, the above expression would be turned\n    into this SQL:\n\n    .. code-block:: sql\n\n        SELECT ... WHERE pub_date BETWEEN '2005-01-01 00:00:00' and '2005-03-31 00:00:00';\n\n    Generally speaking, you can't mix dates and datetimes.\n\n.. fieldlookup:: date\n\n``date``\n~~~~~~~~\n\nFor datetime fields, casts the value as date. Allows chaining additional field\nlookups. Takes a date value.\n\nExample::\n\n    Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1))\n    Entry.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1))\n\n(No equivalent SQL code fragment is included for this lookup because\nimplementation of the relevant query varies among different database engines.)\n\nWhen :setting:`USE_TZ` is ``True``, fields are converted to the current time\nzone before filtering. This requires :ref:`time zone definitions in the\ndatabase <database-time-zone-definitions>`.\n\n.. fieldlookup:: year\n\n``year``\n~~~~~~~~\n\nFor date and datetime fields, an exact year match. Allows chaining additional\nfield lookups. Takes an integer year.\n\nExample::\n\n    Entry.objects.filter(pub_date__year=2005)\n    Entry.objects.filter(pub_date__year__gte=2005)\n\nSQL equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE pub_date BETWEEN '2005-01-01' AND '2005-12-31';\n    SELECT ... WHERE pub_date >= '2005-01-01';\n\n(The exact SQL syntax varies for each database engine.)\n\nWhen :setting:`USE_TZ` is ``True``, datetime fields are converted to the\ncurrent time zone before filtering. This requires :ref:`time zone definitions\nin the database <database-time-zone-definitions>`.\n\n.. fieldlookup:: iso_year\n\n``iso_year``\n~~~~~~~~~~~~\n\nFor date and datetime fields, an exact ISO 8601 week-numbering year match.\nAllows chaining additional field lookups. Takes an integer year.\n\nExample::\n\n    Entry.objects.filter(pub_date__iso_year=2005)\n    Entry.objects.filter(pub_date__iso_year__gte=2005)\n\n(The exact SQL syntax varies for each database engine.)\n\nWhen :setting:`USE_TZ` is ``True``, datetime fields are converted to the\ncurrent time zone before filtering. This requires :ref:`time zone definitions\nin the database <database-time-zone-definitions>`.\n\n.. fieldlookup:: month\n\n``month``\n~~~~~~~~~\n\nFor date and datetime fields, an exact month match. Allows chaining additional\nfield lookups. Takes an integer 1 (January) through 12 (December).\n\nExample::\n\n    Entry.objects.filter(pub_date__month=12)\n    Entry.objects.filter(pub_date__month__gte=6)\n\nSQL equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE EXTRACT('month' FROM pub_date) = '12';\n    SELECT ... WHERE EXTRACT('month' FROM pub_date) >= '6';\n\n(The exact SQL syntax varies for each database engine.)\n\nWhen :setting:`USE_TZ` is ``True``, datetime fields are converted to the\ncurrent time zone before filtering. This requires :ref:`time zone definitions\nin the database <database-time-zone-definitions>`.\n\n.. fieldlookup:: day\n\n``day``\n~~~~~~~\n\nFor date and datetime fields, an exact day match. Allows chaining additional\nfield lookups. Takes an integer day.\n\nExample::\n\n    Entry.objects.filter(pub_date__day=3)\n    Entry.objects.filter(pub_date__day__gte=3)\n\nSQL equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE EXTRACT('day' FROM pub_date) = '3';\n    SELECT ... WHERE EXTRACT('day' FROM pub_date) >= '3';\n\n(The exact SQL syntax varies for each database engine.)\n\nNote this will match any record with a pub_date on the third day of the month,\nsuch as January 3, July 3, etc.\n\nWhen :setting:`USE_TZ` is ``True``, datetime fields are converted to the\ncurrent time zone before filtering. This requires :ref:`time zone definitions\nin the database <database-time-zone-definitions>`.\n\n.. fieldlookup:: week\n\n``week``\n~~~~~~~~\n\nFor date and datetime fields, return the week number (1-52 or 53) according\nto `ISO-8601 <https://en.wikipedia.org/wiki/ISO-8601>`_, i.e., weeks start\non a Monday and the first week contains the year's first Thursday.\n\nExample::\n\n    Entry.objects.filter(pub_date__week=52)\n    Entry.objects.filter(pub_date__week__gte=32, pub_date__week__lte=38)\n\n(No equivalent SQL code fragment is included for this lookup because\nimplementation of the relevant query varies among different database engines.)\n\nWhen :setting:`USE_TZ` is ``True``, datetime fields are converted to the\ncurrent time zone before filtering. This requires :ref:`time zone definitions\nin the database <database-time-zone-definitions>`.\n\n.. fieldlookup:: week_day\n\n``week_day``\n~~~~~~~~~~~~\n\nFor date and datetime fields, a 'day of the week' match. Allows chaining\nadditional field lookups.\n\nTakes an integer value representing the day of week from 1 (Sunday) to 7\n(Saturday).\n\nExample::\n\n    Entry.objects.filter(pub_date__week_day=2)\n    Entry.objects.filter(pub_date__week_day__gte=2)\n\n(No equivalent SQL code fragment is included for this lookup because\nimplementation of the relevant query varies among different database engines.)\n\nNote this will match any record with a ``pub_date`` that falls on a Monday (day\n2 of the week), regardless of the month or year in which it occurs. Week days\nare indexed with day 1 being Sunday and day 7 being Saturday.\n\nWhen :setting:`USE_TZ` is ``True``, datetime fields are converted to the\ncurrent time zone before filtering. This requires :ref:`time zone definitions\nin the database <database-time-zone-definitions>`.\n\n.. fieldlookup:: iso_week_day\n\n``iso_week_day``\n~~~~~~~~~~~~~~~~\n\n.. versionadded:: 3.1\n\nFor date and datetime fields, an exact ISO 8601 day of the week match. Allows\nchaining additional field lookups.\n\nTakes an integer value representing the day of the week from 1 (Monday) to 7\n(Sunday).\n\nExample::\n\n    Entry.objects.filter(pub_date__iso_week_day=1)\n    Entry.objects.filter(pub_date__iso_week_day__gte=1)\n\n(No equivalent SQL code fragment is included for this lookup because\nimplementation of the relevant query varies among different database engines.)\n\nNote this will match any record with a ``pub_date`` that falls on a Monday (day\n1 of the week), regardless of the month or year in which it occurs. Week days\nare indexed with day 1 being Monday and day 7 being Sunday.\n\nWhen :setting:`USE_TZ` is ``True``, datetime fields are converted to the\ncurrent time zone before filtering. This requires :ref:`time zone definitions\nin the database <database-time-zone-definitions>`.\n\n.. fieldlookup:: quarter\n\n``quarter``\n~~~~~~~~~~~\n\nFor date and datetime fields, a 'quarter of the year' match. Allows chaining\nadditional field lookups. Takes an integer value between 1 and 4 representing\nthe quarter of the year.\n\nExample to retrieve entries in the second quarter (April 1 to June 30)::\n\n    Entry.objects.filter(pub_date__quarter=2)\n\n(No equivalent SQL code fragment is included for this lookup because\nimplementation of the relevant query varies among different database engines.)\n\nWhen :setting:`USE_TZ` is ``True``, datetime fields are converted to the\ncurrent time zone before filtering. This requires :ref:`time zone definitions\nin the database <database-time-zone-definitions>`.\n\n.. fieldlookup:: time\n\n``time``\n~~~~~~~~\n\nFor datetime fields, casts the value as time. Allows chaining additional field\nlookups. Takes a :class:`datetime.time` value.\n\nExample::\n\n    Entry.objects.filter(pub_date__time=datetime.time(14, 30))\n    Entry.objects.filter(pub_date__time__range=(datetime.time(8), datetime.time(17)))\n\n(No equivalent SQL code fragment is included for this lookup because\nimplementation of the relevant query varies among different database engines.)\n\nWhen :setting:`USE_TZ` is ``True``, fields are converted to the current time\nzone before filtering. This requires :ref:`time zone definitions in the\ndatabase <database-time-zone-definitions>`.\n\n.. fieldlookup:: hour\n\n``hour``\n~~~~~~~~\n\nFor datetime and time fields, an exact hour match. Allows chaining additional\nfield lookups. Takes an integer between 0 and 23.\n\nExample::\n\n    Event.objects.filter(timestamp__hour=23)\n    Event.objects.filter(time__hour=5)\n    Event.objects.filter(timestamp__hour__gte=12)\n\nSQL equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE EXTRACT('hour' FROM timestamp) = '23';\n    SELECT ... WHERE EXTRACT('hour' FROM time) = '5';\n    SELECT ... WHERE EXTRACT('hour' FROM timestamp) >= '12';\n\n(The exact SQL syntax varies for each database engine.)\n\nWhen :setting:`USE_TZ` is ``True``, datetime fields are converted to the\ncurrent time zone before filtering. This requires :ref:`time zone definitions\nin the database <database-time-zone-definitions>`.\n\n.. fieldlookup:: minute\n\n``minute``\n~~~~~~~~~~\n\nFor datetime and time fields, an exact minute match. Allows chaining additional\nfield lookups. Takes an integer between 0 and 59.\n\nExample::\n\n    Event.objects.filter(timestamp__minute=29)\n    Event.objects.filter(time__minute=46)\n    Event.objects.filter(timestamp__minute__gte=29)\n\nSQL equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE EXTRACT('minute' FROM timestamp) = '29';\n    SELECT ... WHERE EXTRACT('minute' FROM time) = '46';\n    SELECT ... WHERE EXTRACT('minute' FROM timestamp) >= '29';\n\n(The exact SQL syntax varies for each database engine.)\n\nWhen :setting:`USE_TZ` is ``True``, datetime fields are converted to the\ncurrent time zone before filtering. This requires :ref:`time zone definitions\nin the database <database-time-zone-definitions>`.\n\n.. fieldlookup:: second\n\n``second``\n~~~~~~~~~~\n\nFor datetime and time fields, an exact second match. Allows chaining additional\nfield lookups. Takes an integer between 0 and 59.\n\nExample::\n\n    Event.objects.filter(timestamp__second=31)\n    Event.objects.filter(time__second=2)\n    Event.objects.filter(timestamp__second__gte=31)\n\nSQL equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE EXTRACT('second' FROM timestamp) = '31';\n    SELECT ... WHERE EXTRACT('second' FROM time) = '2';\n    SELECT ... WHERE EXTRACT('second' FROM timestamp) >= '31';\n\n(The exact SQL syntax varies for each database engine.)\n\nWhen :setting:`USE_TZ` is ``True``, datetime fields are converted to the\ncurrent time zone before filtering. This requires :ref:`time zone definitions\nin the database <database-time-zone-definitions>`.\n\n.. fieldlookup:: isnull\n\n``isnull``\n~~~~~~~~~~\n\nTakes either ``True`` or ``False``, which correspond to SQL queries of\n``IS NULL`` and ``IS NOT NULL``, respectively.\n\nExample::\n\n    Entry.objects.filter(pub_date__isnull=True)\n\nSQL equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE pub_date IS NULL;\n\n.. deprecated:: 3.1\n\n    Using non-boolean values as the right-hand side is deprecated, use ``True``\n    or ``False`` instead. In Django 4.0, the exception will be raised.\n\n.. fieldlookup:: regex\n\n``regex``\n~~~~~~~~~\n\nCase-sensitive regular expression match.\n\nThe regular expression syntax is that of the database backend in use.\nIn the case of SQLite, which has no built in regular expression support,\nthis feature is provided by a (Python) user-defined REGEXP function, and\nthe regular expression syntax is therefore that of Python's ``re`` module.\n\nExample::\n\n    Entry.objects.get(title__regex=r'^(An?|The) +')\n\nSQL equivalents:\n\n.. code-block:: sql\n\n    SELECT ... WHERE title REGEXP BINARY '^(An?|The) +'; -- MySQL\n\n    SELECT ... WHERE REGEXP_LIKE(title, '^(An?|The) +', 'c'); -- Oracle\n\n    SELECT ... WHERE title ~ '^(An?|The) +'; -- PostgreSQL\n\n    SELECT ... WHERE title REGEXP '^(An?|The) +'; -- SQLite\n\nUsing raw strings (e.g., ``r'foo'`` instead of ``'foo'``) for passing in the\nregular expression syntax is recommended.\n\n.. fieldlookup:: iregex\n\n``iregex``\n~~~~~~~~~~\n\nCase-insensitive regular expression match.\n\nExample::\n\n    Entry.objects.get(title__iregex=r'^(an?|the) +')\n\nSQL equivalents:\n\n.. code-block:: sql\n\n    SELECT ... WHERE title REGEXP '^(an?|the) +'; -- MySQL\n\n    SELECT ... WHERE REGEXP_LIKE(title, '^(an?|the) +', 'i'); -- Oracle\n\n    SELECT ... WHERE title ~* '^(an?|the) +'; -- PostgreSQL\n\n    SELECT ... WHERE title REGEXP '(?i)^(an?|the) +'; -- SQLite\n\n.. _aggregation-functions:\n\nAggregation functions\n---------------------\n\n.. currentmodule:: django.db.models\n\nDjango provides the following aggregation functions in the\n``django.db.models`` module. For details on how to use these\naggregate functions, see :doc:`the topic guide on aggregation\n</topics/db/aggregation>`. See the :class:`~django.db.models.Aggregate`\ndocumentation to learn how to create your aggregates.\n\n.. warning::\n\n    SQLite can't handle aggregation on date/time fields out of the box.\n    This is because there are no native date/time fields in SQLite and Django\n    currently emulates these features using a text field. Attempts to use\n    aggregation on date/time fields in SQLite will raise\n    ``NotImplementedError``.\n\n.. admonition:: Note\n\n    Aggregation functions return ``None`` when used with an empty\n    ``QuerySet``. For example, the ``Sum`` aggregation function returns ``None``\n    instead of ``0`` if the ``QuerySet`` contains no entries. An exception is\n    ``Count``, which does return ``0`` if the ``QuerySet`` is empty.\n\nAll aggregates have the following parameters in common:\n\n``expressions``\n~~~~~~~~~~~~~~~\n\nStrings that reference fields on the model, or :doc:`query expressions\n</ref/models/expressions>`.\n\n``output_field``\n~~~~~~~~~~~~~~~~\n\nAn optional argument that represents the :doc:`model field </ref/models/fields>`\nof the return value\n\n.. note::\n\n    When combining multiple field types, Django can only determine the\n    ``output_field`` if all fields are of the same type. Otherwise, you\n    must provide the ``output_field`` yourself.\n\n.. _aggregate-filter:\n\n``filter``\n~~~~~~~~~~\n\nAn optional :class:`Q object <django.db.models.Q>` that's used to filter the\nrows that are aggregated.\n\nSee :ref:`conditional-aggregation` and :ref:`filtering-on-annotations` for\nexample usage.\n\n``**extra``\n~~~~~~~~~~~\n\nKeyword arguments that can provide extra context for the SQL generated\nby the aggregate.\n\n``Avg``\n~~~~~~~\n\n.. class:: Avg(expression, output_field=None, distinct=False, filter=None, **extra)\n\n    Returns the mean value of the given expression, which must be numeric\n    unless you specify a different ``output_field``.\n\n    * Default alias: ``<field>__avg``\n    * Return type: ``float`` if input is ``int``, otherwise same as input\n      field, or ``output_field`` if supplied\n\n    Has one optional argument:\n\n    .. attribute:: distinct\n\n        If ``distinct=True``, ``Avg`` returns the mean value of unique values.\n        This is the SQL equivalent of ``AVG(DISTINCT <field>)``. The default\n        value is ``False``.\n\n``Count``\n~~~~~~~~~\n\n.. class:: Count(expression, distinct=False, filter=None, **extra)\n\n    Returns the number of objects that are related through the provided\n    expression.\n\n    * Default alias: ``<field>__count``\n    * Return type: ``int``\n\n    Has one optional argument:\n\n    .. attribute:: distinct\n\n        If ``distinct=True``, the count will only include unique instances.\n        This is the SQL equivalent of ``COUNT(DISTINCT <field>)``. The default\n        value is ``False``.\n\n``Max``\n~~~~~~~\n\n.. class:: Max(expression, output_field=None, filter=None, **extra)\n\n    Returns the maximum value of the given expression.\n\n    * Default alias: ``<field>__max``\n    * Return type: same as input field, or ``output_field`` if supplied\n\n``Min``\n~~~~~~~\n\n.. class:: Min(expression, output_field=None, filter=None, **extra)\n\n    Returns the minimum value of the given expression.\n\n    * Default alias: ``<field>__min``\n    * Return type: same as input field, or ``output_field`` if supplied\n\n``StdDev``\n~~~~~~~~~~\n\n.. class:: StdDev(expression, output_field=None, sample=False, filter=None, **extra)\n\n    Returns the standard deviation of the data in the provided expression.\n\n    * Default alias: ``<field>__stddev``\n    * Return type: ``float`` if input is ``int``, otherwise same as input\n      field, or ``output_field`` if supplied\n\n    Has one optional argument:\n\n    .. attribute:: sample\n\n        By default, ``StdDev`` returns the population standard deviation. However,\n        if ``sample=True``, the return value will be the sample standard deviation.\n\n``Sum``\n~~~~~~~\n\n.. class:: Sum(expression, output_field=None, distinct=False, filter=None, **extra)\n\n    Computes the sum of all values of the given expression.\n\n    * Default alias: ``<field>__sum``\n    * Return type: same as input field, or ``output_field`` if supplied\n\n    Has one optional argument:\n\n    .. attribute:: distinct\n\n        If ``distinct=True``, ``Sum`` returns the sum of unique values. This is\n        the SQL equivalent of ``SUM(DISTINCT <field>)``. The default value is\n        ``False``.\n\n``Variance``\n~~~~~~~~~~~~\n\n.. class:: Variance(expression, output_field=None, sample=False, filter=None, **extra)\n\n    Returns the variance of the data in the provided expression.\n\n    * Default alias: ``<field>__variance``\n    * Return type: ``float`` if input is ``int``, otherwise same as input\n      field, or ``output_field`` if supplied\n\n    Has one optional argument:\n\n    .. attribute:: sample\n\n        By default, ``Variance`` returns the population variance. However,\n        if ``sample=True``, the return value will be the sample variance.\n\nQuery-related tools\n===================\n\nThis section provides reference material for query-related tools not documented\nelsewhere.\n\n``Q()`` objects\n---------------\n\n.. class:: Q\n\nA ``Q()`` object represents an SQL condition that can be used in\ndatabase-related operations. It's similar to how an\n:class:`F() <django.db.models.F>` object represents the value of a model field\nor annotation. They make it possible to define and reuse conditions, and\ncombine them using operators such as ``|`` (``OR``) and ``&`` (``AND``). See\n:ref:`complex-lookups-with-q`.\n\n``Prefetch()`` objects\n----------------------\n\n.. class:: Prefetch(lookup, queryset=None, to_attr=None)\n\nThe ``Prefetch()`` object can be used to control the operation of\n:meth:`~django.db.models.query.QuerySet.prefetch_related()`.\n\nThe ``lookup`` argument describes the relations to follow and works the same\nas the string based lookups passed to\n:meth:`~django.db.models.query.QuerySet.prefetch_related()`. For example:\n\n    >>> from django.db.models import Prefetch\n    >>> Question.objects.prefetch_related(Prefetch('choice_set')).get().choice_set.all()\n    <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>\n    # This will only execute two queries regardless of the number of Question\n    # and Choice objects.\n    >>> Question.objects.prefetch_related(Prefetch('choice_set')).all()\n    <QuerySet [<Question: What's up?>]>\n\nThe ``queryset`` argument supplies a base ``QuerySet`` for the given lookup.\nThis is useful to further filter down the prefetch operation, or to call\n:meth:`~django.db.models.query.QuerySet.select_related()` from the prefetched\nrelation, hence reducing the number of queries even further:\n\n    >>> voted_choices = Choice.objects.filter(votes__gt=0)\n    >>> voted_choices\n    <QuerySet [<Choice: The sky>]>\n    >>> prefetch = Prefetch('choice_set', queryset=voted_choices)\n    >>> Question.objects.prefetch_related(prefetch).get().choice_set.all()\n    <QuerySet [<Choice: The sky>]>\n\nThe ``to_attr`` argument sets the result of the prefetch operation to a custom\nattribute:\n\n    >>> prefetch = Prefetch('choice_set', queryset=voted_choices, to_attr='voted_choices')\n    >>> Question.objects.prefetch_related(prefetch).get().voted_choices\n    [<Choice: The sky>]\n    >>> Question.objects.prefetch_related(prefetch).get().choice_set.all()\n    <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>\n\n.. note::\n\n    When using ``to_attr`` the prefetched result is stored in a list. This can\n    provide a significant speed improvement over traditional\n    ``prefetch_related`` calls which store the cached result within a\n    ``QuerySet`` instance.\n\n``prefetch_related_objects()``\n------------------------------\n\n.. function:: prefetch_related_objects(model_instances, *related_lookups)\n\nPrefetches the given lookups on an iterable of model instances. This is useful\nin code that receives a list of model instances as opposed to a ``QuerySet``;\nfor example, when fetching models from a cache or instantiating them manually.\n\nPass an iterable of model instances (must all be of the same class) and the\nlookups or :class:`Prefetch` objects you want to prefetch for. For example::\n\n    >>> from django.db.models import prefetch_related_objects\n    >>> restaurants = fetch_top_restaurants_from_cache()  # A list of Restaurants\n    >>> prefetch_related_objects(restaurants, 'pizzas__toppings')\n\n``FilteredRelation()`` objects\n------------------------------\n\n.. class:: FilteredRelation(relation_name, *, condition=Q())\n\n    .. attribute:: FilteredRelation.relation_name\n\n        The name of the field on which you'd like to filter the relation.\n\n    .. attribute:: FilteredRelation.condition\n\n        A :class:`~django.db.models.Q` object to control the filtering.\n\n``FilteredRelation`` is used with :meth:`~.QuerySet.annotate()` to create an\n``ON`` clause when a ``JOIN`` is performed. It doesn't act on the default\nrelationship but on the annotation name (``pizzas_vegetarian`` in example\nbelow).\n\nFor example, to find restaurants that have vegetarian pizzas with\n``'mozzarella'`` in the name::\n\n    >>> from django.db.models import FilteredRelation, Q\n    >>> Restaurant.objects.annotate(\n    ...    pizzas_vegetarian=FilteredRelation(\n    ...        'pizzas', condition=Q(pizzas__vegetarian=True),\n    ...    ),\n    ... ).filter(pizzas_vegetarian__name__icontains='mozzarella')\n\nIf there are a large number of pizzas, this queryset performs better than::\n\n    >>> Restaurant.objects.filter(\n    ...     pizzas__vegetarian=True,\n    ...     pizzas__name__icontains='mozzarella',\n    ... )\n\nbecause the filtering in the ``WHERE`` clause of the first queryset will only\noperate on vegetarian pizzas.\n\n``FilteredRelation`` doesn't support:\n\n* Conditions that span relational fields. For example::\n\n    >>> Restaurant.objects.annotate(\n    ...    pizzas_with_toppings_startswith_n=FilteredRelation(\n    ...        'pizzas__toppings',\n    ...        condition=Q(pizzas__toppings__name__startswith='n'),\n    ...    ),\n    ... )\n    Traceback (most recent call last):\n    ...\n    ValueError: FilteredRelation's condition doesn't support nested relations (got 'pizzas__toppings__name__startswith').\n* :meth:`.QuerySet.only` and :meth:`~.QuerySet.prefetch_related`.\n* A :class:`~django.contrib.contenttypes.fields.GenericForeignKey`\n  inherited from a parent model.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":125,"nodeType":"TextFile","repoName":null,"name":"sites.txt","path":"docs/ref/contrib","text":"=====================\nThe \"sites\" framework\n=====================\n\n.. module:: django.contrib.sites\n   :synopsis: Lets you operate multiple websites from the same database and\n              Django project\n\nDjango comes with an optional \"sites\" framework. It's a hook for associating\nobjects and functionality to particular websites, and it's a holding place for\nthe domain names and \"verbose\" names of your Django-powered sites.\n\nUse it if your single Django installation powers more than one site and you\nneed to differentiate between those sites in some way.\n\nThe sites framework is mainly based on this model:\n\n.. class:: models.Site\n\n    A model for storing the ``domain`` and ``name`` attributes of a website.\n\n    .. attribute:: domain\n\n        The fully qualified domain name associated with the website.\n        For example, ``www.example.com``.\n\n    .. attribute:: name\n\n        A human-readable \"verbose\" name for the website.\n\nThe :setting:`SITE_ID` setting specifies the database ID of the\n:class:`~django.contrib.sites.models.Site` object associated with that\nparticular settings file. If the setting is omitted, the\n:func:`~django.contrib.sites.shortcuts.get_current_site` function will\ntry to get the current site by comparing the\n:attr:`~django.contrib.sites.models.Site.domain` with the host name from\nthe :meth:`request.get_host() <django.http.HttpRequest.get_host>` method.\n\nHow you use this is up to you, but Django uses it in a couple of ways\nautomatically via a couple of conventions.\n\nExample usage\n=============\n\nWhy would you use sites? It's best explained through examples.\n\nAssociating content with multiple sites\n---------------------------------------\n\nThe LJWorld.com_ and Lawrence.com_ sites are operated by the same news\norganization -- the Lawrence Journal-World newspaper in Lawrence, Kansas.\nLJWorld.com focused on news, while Lawrence.com focused on local entertainment.\nBut sometimes editors wanted to publish an article on *both* sites.\n\nThe naive way of solving the problem would be to require site producers to\npublish the same story twice: once for LJWorld.com and again for Lawrence.com.\nBut that's inefficient for site producers, and it's redundant to store\nmultiple copies of the same story in the database.\n\nA better solution removes the content duplication: Both sites use the same\narticle database, and an article is associated with one or more sites. In\nDjango model terminology, that's represented by a\n:class:`~django.db.models.ManyToManyField` in the ``Article`` model::\n\n    from django.contrib.sites.models import Site\n    from django.db import models\n\n    class Article(models.Model):\n        headline = models.CharField(max_length=200)\n        # ...\n        sites = models.ManyToManyField(Site)\n\nThis accomplishes several things quite nicely:\n\n* It lets the site producers edit all content -- on both sites -- in a\n  single interface (the Django admin).\n\n* It means the same story doesn't have to be published twice in the\n  database; it only has a single record in the database.\n\n* It lets the site developers use the same Django view code for both sites.\n  The view code that displays a given story checks to make sure the requested\n  story is on the current site. It looks something like this::\n\n      from django.contrib.sites.shortcuts import get_current_site\n\n      def article_detail(request, article_id):\n          try:\n              a = Article.objects.get(id=article_id, sites__id=get_current_site(request).id)\n          except Article.DoesNotExist:\n              raise Http404(\"Article does not exist on this site\")\n          # ...\n\n.. _ljworld.com: http://www.ljworld.com/\n.. _lawrence.com: http://www.lawrence.com/\n\nAssociating content with a single site\n--------------------------------------\n\nSimilarly, you can associate a model to the\n:class:`~django.contrib.sites.models.Site`\nmodel in a many-to-one relationship, using\n:class:`~django.db.models.ForeignKey`.\n\nFor example, if an article is only allowed on a single site, you'd use a model\nlike this::\n\n    from django.contrib.sites.models import Site\n    from django.db import models\n\n    class Article(models.Model):\n        headline = models.CharField(max_length=200)\n        # ...\n        site = models.ForeignKey(Site, on_delete=models.CASCADE)\n\nThis has the same benefits as described in the last section.\n\n.. _hooking-into-current-site-from-views:\n\nHooking into the current site from views\n----------------------------------------\n\nYou can use the sites framework in your Django views to do\nparticular things based on the site in which the view is being called.\nFor example::\n\n    from django.conf import settings\n\n    def my_view(request):\n        if settings.SITE_ID == 3:\n            # Do something.\n            pass\n        else:\n            # Do something else.\n            pass\n\nIt's fragile to hard-code the site IDs like that, in case they change. The\ncleaner way of accomplishing the same thing is to check the current site's\ndomain::\n\n    from django.contrib.sites.shortcuts import get_current_site\n\n    def my_view(request):\n        current_site = get_current_site(request)\n        if current_site.domain == 'foo.com':\n            # Do something\n            pass\n        else:\n            # Do something else.\n            pass\n\nThis has also the advantage of checking if the sites framework is installed,\nand return a :class:`~django.contrib.sites.requests.RequestSite` instance if\nit is not.\n\nIf you don't have access to the request object, you can use the\n``get_current()`` method of the :class:`~django.contrib.sites.models.Site`\nmodel's manager. You should then ensure that your settings file does contain\nthe :setting:`SITE_ID` setting. This example is equivalent to the previous one::\n\n    from django.contrib.sites.models import Site\n\n    def my_function_without_request():\n        current_site = Site.objects.get_current()\n        if current_site.domain == 'foo.com':\n            # Do something\n            pass\n        else:\n            # Do something else.\n            pass\n\nGetting the current domain for display\n--------------------------------------\n\nLJWorld.com and Lawrence.com both have email alert functionality, which lets\nreaders sign up to get notifications when news happens. It's pretty basic: A\nreader signs up on a Web form and immediately gets an email saying,\n\"Thanks for your subscription.\"\n\nIt'd be inefficient and redundant to implement this sign up processing code\ntwice, so the sites use the same code behind the scenes. But the \"thank you for\nsigning up\" notice needs to be different for each site. By using\n:class:`~django.contrib.sites.models.Site`\nobjects, we can abstract the \"thank you\" notice to use the values of the\ncurrent site's :attr:`~django.contrib.sites.models.Site.name` and\n:attr:`~django.contrib.sites.models.Site.domain`.\n\nHere's an example of what the form-handling view looks like::\n\n    from django.contrib.sites.shortcuts import get_current_site\n    from django.core.mail import send_mail\n\n    def register_for_newsletter(request):\n        # Check form values, etc., and subscribe the user.\n        # ...\n\n        current_site = get_current_site(request)\n        send_mail(\n            'Thanks for subscribing to %s alerts' % current_site.name,\n            'Thanks for your subscription. We appreciate it.\\n\\n-The %s team.' % (\n                current_site.name,\n            ),\n            'editor@%s' % current_site.domain,\n            [user.email],\n        )\n\n        # ...\n\nOn Lawrence.com, this email has the subject line \"Thanks for subscribing to\nlawrence.com alerts.\" On LJWorld.com, the email has the subject \"Thanks for\nsubscribing to LJWorld.com alerts.\" Same goes for the email's message body.\n\nNote that an even more flexible (but more heavyweight) way of doing this would\nbe to use Django's template system. Assuming Lawrence.com and LJWorld.com have\ndifferent template directories (:setting:`DIRS <TEMPLATES-DIRS>`), you could\nfarm out to the template system like so::\n\n    from django.core.mail import send_mail\n    from django.template import loader\n\n    def register_for_newsletter(request):\n        # Check form values, etc., and subscribe the user.\n        # ...\n\n        subject = loader.get_template('alerts/subject.txt').render({})\n        message = loader.get_template('alerts/message.txt').render({})\n        send_mail(subject, message, 'editor@ljworld.com', [user.email])\n\n        # ...\n\nIn this case, you'd have to create :file:`subject.txt` and :file:`message.txt`\ntemplate files for both the LJWorld.com and Lawrence.com template directories.\nThat gives you more flexibility, but it's also more complex.\n\nIt's a good idea to exploit the :class:`~django.contrib.sites.models.Site`\nobjects as much as possible, to remove unneeded complexity and redundancy.\n\nGetting the current domain for full URLs\n----------------------------------------\n\nDjango's ``get_absolute_url()`` convention is nice for getting your objects'\nURL without the domain name, but in some cases you might want to display the\nfull URL -- with ``http://`` and the domain and everything -- for an object.\nTo do this, you can use the sites framework. An example::\n\n    >>> from django.contrib.sites.models import Site\n    >>> obj = MyModel.objects.get(id=3)\n    >>> obj.get_absolute_url()\n    '/mymodel/objects/3/'\n    >>> Site.objects.get_current().domain\n    'example.com'\n    >>> 'https://%s%s' % (Site.objects.get_current().domain, obj.get_absolute_url())\n    'https://example.com/mymodel/objects/3/'\n\n.. _enabling-the-sites-framework:\n\nEnabling the sites framework\n============================\n\nTo enable the sites framework, follow these steps:\n\n#. Add ``'django.contrib.sites'`` to your :setting:`INSTALLED_APPS` setting.\n\n#. Define a :setting:`SITE_ID` setting::\n\n    SITE_ID = 1\n\n#. Run :djadmin:`migrate`.\n\n``django.contrib.sites`` registers a\n:data:`~django.db.models.signals.post_migrate` signal handler which creates a\ndefault site named ``example.com`` with the domain ``example.com``. This site\nwill also be created after Django creates the test database. To set the\ncorrect name and domain for your project, you can use a :ref:`data migration\n<data-migrations>`.\n\nIn order to serve different sites in production, you'd create a separate\nsettings file with each ``SITE_ID`` (perhaps importing from a common settings\nfile to avoid duplicating shared settings) and then specify the appropriate\n:envvar:`DJANGO_SETTINGS_MODULE` for each site.\n\nCaching the current ``Site`` object\n===================================\n\nAs the current site is stored in the database, each call to\n``Site.objects.get_current()`` could result in a database query. But Django is a\nlittle cleverer than that: on the first request, the current site is cached, and\nany subsequent call returns the cached data instead of hitting the database.\n\nIf for any reason you want to force a database query, you can tell Django to\nclear the cache using ``Site.objects.clear_cache()``::\n\n    # First call; current site fetched from database.\n    current_site = Site.objects.get_current()\n    # ...\n\n    # Second call; current site fetched from cache.\n    current_site = Site.objects.get_current()\n    # ...\n\n    # Force a database query for the third call.\n    Site.objects.clear_cache()\n    current_site = Site.objects.get_current()\n\nThe ``CurrentSiteManager``\n==========================\n\n.. class:: managers.CurrentSiteManager\n\nIf :class:`~django.contrib.sites.models.Site` plays a key role in your\napplication, consider using the helpful\n:class:`~django.contrib.sites.managers.CurrentSiteManager` in your\nmodel(s). It's a model :doc:`manager </topics/db/managers>` that\nautomatically filters its queries to include only objects associated\nwith the current :class:`~django.contrib.sites.models.Site`.\n\n.. admonition:: Mandatory :setting:`SITE_ID`\n\n    The ``CurrentSiteManager`` is only usable when the :setting:`SITE_ID`\n    setting is defined in your settings.\n\nUse :class:`~django.contrib.sites.managers.CurrentSiteManager` by adding it to\nyour model explicitly. For example::\n\n    from django.contrib.sites.models import Site\n    from django.contrib.sites.managers import CurrentSiteManager\n    from django.db import models\n\n    class Photo(models.Model):\n        photo = models.FileField(upload_to='photos')\n        photographer_name = models.CharField(max_length=100)\n        pub_date = models.DateField()\n        site = models.ForeignKey(Site, on_delete=models.CASCADE)\n        objects = models.Manager()\n        on_site = CurrentSiteManager()\n\nWith this model, ``Photo.objects.all()`` will return all ``Photo`` objects in\nthe database, but ``Photo.on_site.all()`` will return only the ``Photo`` objects\nassociated with the current site, according to the :setting:`SITE_ID` setting.\n\nPut another way, these two statements are equivalent::\n\n    Photo.objects.filter(site=settings.SITE_ID)\n    Photo.on_site.all()\n\nHow did :class:`~django.contrib.sites.managers.CurrentSiteManager`\nknow which field of ``Photo`` was the\n:class:`~django.contrib.sites.models.Site`? By default,\n:class:`~django.contrib.sites.managers.CurrentSiteManager` looks for a\neither a :class:`~django.db.models.ForeignKey` called\n``site`` or a\n:class:`~django.db.models.ManyToManyField` called\n``sites`` to filter on. If you use a field named something other than\n``site`` or ``sites`` to identify which\n:class:`~django.contrib.sites.models.Site` objects your object is\nrelated to, then you need to explicitly pass the custom field name as\na parameter to\n:class:`~django.contrib.sites.managers.CurrentSiteManager` on your\nmodel. The following model, which has a field called ``publish_on``,\ndemonstrates this::\n\n    from django.contrib.sites.models import Site\n    from django.contrib.sites.managers import CurrentSiteManager\n    from django.db import models\n\n    class Photo(models.Model):\n        photo = models.FileField(upload_to='photos')\n        photographer_name = models.CharField(max_length=100)\n        pub_date = models.DateField()\n        publish_on = models.ForeignKey(Site, on_delete=models.CASCADE)\n        objects = models.Manager()\n        on_site = CurrentSiteManager('publish_on')\n\nIf you attempt to use :class:`~django.contrib.sites.managers.CurrentSiteManager`\nand pass a field name that doesn't exist, Django will raise a ``ValueError``.\n\nFinally, note that you'll probably want to keep a normal\n(non-site-specific) ``Manager`` on your model, even if you use\n:class:`~django.contrib.sites.managers.CurrentSiteManager`. As\nexplained in the :doc:`manager documentation </topics/db/managers>`, if\nyou define a manager manually, then Django won't create the automatic\n``objects = models.Manager()`` manager for you. Also note that certain\nparts of Django -- namely, the Django admin site and generic views --\nuse whichever manager is defined *first* in the model, so if you want\nyour admin site to have access to all objects (not just site-specific\nones), put ``objects = models.Manager()`` in your model, before you\ndefine :class:`~django.contrib.sites.managers.CurrentSiteManager`.\n\n.. _site-middleware:\n\nSite middleware\n===============\n\nIf you often use this pattern::\n\n    from django.contrib.sites.models import Site\n\n    def my_view(request):\n        site = Site.objects.get_current()\n        ...\n\nTo avoid repetitions, add\n:class:`django.contrib.sites.middleware.CurrentSiteMiddleware` to\n:setting:`MIDDLEWARE`. The middleware sets the ``site`` attribute on every\nrequest object, so you can use ``request.site`` to get the current site.\n\nHow Django uses the sites framework\n===================================\n\nAlthough it's not required that you use the sites framework, it's strongly\nencouraged, because Django takes advantage of it in a few places. Even if your\nDjango installation is powering only a single site, you should take the two\nseconds to create the site object with your ``domain`` and ``name``, and point\nto its ID in your :setting:`SITE_ID` setting.\n\nHere's how Django uses the sites framework:\n\n* In the :mod:`redirects framework <django.contrib.redirects>`, each\n  redirect object is associated with a particular site. When Django searches\n  for a redirect, it takes into account the current site.\n\n* In the :mod:`flatpages framework <django.contrib.flatpages>`, each\n  flatpage is associated with a particular site. When a flatpage is created,\n  you specify its :class:`~django.contrib.sites.models.Site`, and the\n  :class:`~django.contrib.flatpages.middleware.FlatpageFallbackMiddleware`\n  checks the current site in retrieving flatpages to display.\n\n* In the :mod:`syndication framework <django.contrib.syndication>`, the\n  templates for ``title`` and ``description`` automatically have access to a\n  variable ``{{ site }}``, which is the\n  :class:`~django.contrib.sites.models.Site` object representing the current\n  site. Also, the hook for providing item URLs will use the ``domain`` from\n  the current :class:`~django.contrib.sites.models.Site` object if you don't\n  specify a fully-qualified domain.\n\n* In the :mod:`authentication framework <django.contrib.auth>`,\n  :class:`django.contrib.auth.views.LoginView` passes the current\n  :class:`~django.contrib.sites.models.Site` name to the template as\n  ``{{ site_name }}``.\n\n* The shortcut view (``django.contrib.contenttypes.views.shortcut``)\n  uses the domain of the current\n  :class:`~django.contrib.sites.models.Site` object when calculating\n  an object's URL.\n\n* In the admin framework, the \"view on site\" link uses the current\n  :class:`~django.contrib.sites.models.Site` to work out the domain for the\n  site that it will redirect to.\n\n``RequestSite`` objects\n=======================\n\n.. _requestsite-objects:\n\nSome :doc:`django.contrib </ref/contrib/index>` applications take advantage of\nthe sites framework but are architected in a way that doesn't *require* the\nsites framework to be installed in your database. (Some people don't want to,\nor just aren't *able* to install the extra database table that the sites\nframework requires.) For those cases, the framework provides a\n:class:`django.contrib.sites.requests.RequestSite` class, which can be used as\na fallback when the database-backed sites framework is not available.\n\n.. class:: requests.RequestSite\n\n    A class that shares the primary interface of\n    :class:`~django.contrib.sites.models.Site` (i.e., it has\n    ``domain`` and ``name`` attributes) but gets its data from a Django\n    :class:`~django.http.HttpRequest` object rather than from a database.\n\n    .. method:: __init__(request)\n\n        Sets the ``name`` and ``domain`` attributes to the value of\n        :meth:`~django.http.HttpRequest.get_host`.\n\nA :class:`~django.contrib.sites.requests.RequestSite` object has a similar\ninterface to a normal :class:`~django.contrib.sites.models.Site` object,\nexcept its :meth:`~django.contrib.sites.requests.RequestSite.__init__()`\nmethod takes an :class:`~django.http.HttpRequest` object. It's able to deduce\nthe ``domain`` and ``name`` by looking at the request's domain. It has\n``save()`` and ``delete()`` methods to match the interface of\n:class:`~django.contrib.sites.models.Site`, but the methods raise\n:exc:`NotImplementedError`.\n\n``get_current_site`` shortcut\n=============================\n\nFinally, to avoid repetitive fallback code, the framework provides a\n:func:`django.contrib.sites.shortcuts.get_current_site` function.\n\n.. function:: shortcuts.get_current_site(request)\n\n    A function that checks if ``django.contrib.sites`` is installed and\n    returns either the current :class:`~django.contrib.sites.models.Site`\n    object or a :class:`~django.contrib.sites.requests.RequestSite` object\n    based on the request. It looks up the current site based on\n    :meth:`request.get_host() <django.http.HttpRequest.get_host>` if the\n    :setting:`SITE_ID` setting is not defined.\n\n    Both a domain and a port may be returned by :meth:`request.get_host()\n    <django.http.HttpRequest.get_host>` when the Host header has a port\n    explicitly specified, e.g. ``example.com:80``. In such cases, if the\n    lookup fails because the host does not match a record in the database,\n    the port is stripped and the lookup is retried with the domain part\n    only. This does not apply to\n    :class:`~django.contrib.sites.requests.RequestSite` which will always\n    use the unmodified host.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":126,"nodeType":"TextFile","repoName":null,"name":"geoquerysets.txt","path":"docs/ref/contrib/gis","text":"==========================\nGIS QuerySet API Reference\n==========================\n\n.. currentmodule:: django.contrib.gis.db.models\n\n.. _spatial-lookups:\n\nSpatial Lookups\n===============\n\nThe spatial lookups in this section are available for :class:`GeometryField`\nand :class:`RasterField`.\n\nFor an introduction, see the :ref:`spatial lookups introduction\n<spatial-lookups-intro>`.  For an overview of what lookups are\ncompatible with a particular spatial backend, refer to the\n:ref:`spatial lookup compatibility table <spatial-lookup-compatibility>`.\n\nLookups with rasters\n--------------------\n\nAll examples in the reference below are given for geometry fields and inputs,\nbut the lookups can be used the same way with rasters on both sides. Whenever\na lookup doesn't support raster input, the input is automatically\nconverted to a geometry where necessary using the `ST_Polygon\n<https://postgis.net/docs/RT_ST_Polygon.html>`_ function. See also the\n:ref:`introduction to raster lookups <spatial-lookup-raster>`.\n\nThe database operators used by the lookups can be divided into three categories:\n\n- Native raster support ``N``: the operator accepts rasters natively on both\n  sides of the lookup, and raster input can be mixed with geometry inputs.\n\n- Bilateral raster support ``B``: the operator supports rasters only if both\n  sides of the lookup receive raster inputs. Raster data is automatically\n  converted to geometries for mixed lookups.\n\n- Geometry conversion support ``C``. The lookup does not have native raster\n  support, all raster data is automatically converted to geometries.\n\nThe examples below show the SQL equivalent for the lookups in the different\ntypes of raster support. The same pattern applies to all spatial lookups.\n\n==== ============================== =======================================================\nCase Lookup                         SQL Equivalent\n==== ============================== =======================================================\nN, B ``rast__contains=rst``         ``ST_Contains(rast, rst)``\nN, B ``rast__1__contains=(rst, 2)`` ``ST_Contains(rast, 1, rst, 2)``\nB, C ``rast__contains=geom``        ``ST_Contains(ST_Polygon(rast), geom)``\nB, C ``rast__1__contains=geom``     ``ST_Contains(ST_Polygon(rast, 1), geom)``\nB, C ``poly__contains=rst``         ``ST_Contains(poly, ST_Polygon(rst))``\nB, C ``poly__contains=(rst, 1)``    ``ST_Contains(poly, ST_Polygon(rst, 1))``\nC    ``rast__crosses=rst``          ``ST_Crosses(ST_Polygon(rast), ST_Polygon(rst))``\nC    ``rast__1__crosses=(rst, 2)``  ``ST_Crosses(ST_Polygon(rast, 1), ST_Polygon(rst, 2))``\nC    ``rast__crosses=geom``         ``ST_Crosses(ST_Polygon(rast), geom)``\nC    ``poly__crosses=rst``          ``ST_Crosses(poly, ST_Polygon(rst))``\n==== ============================== =======================================================\n\nSpatial lookups with rasters are only supported for PostGIS backends\n(denominated as PGRaster in this section).\n\n.. fieldlookup:: bbcontains\n\n``bbcontains``\n--------------\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Geometry_Contain.html>`__,\nMariaDB, MySQL, SpatiaLite, PGRaster (Native)\n\nTests if the geometry or raster field's bounding box completely contains the\nlookup geometry's bounding box.\n\nExample::\n\n    Zipcode.objects.filter(poly__bbcontains=geom)\n\n==========  ==========================\nBackend     SQL Equivalent\n==========  ==========================\nPostGIS     ``poly ~ geom``\nMariaDB     ``MBRContains(poly, geom)``\nMySQL       ``MBRContains(poly, geom)``\nSpatiaLite  ``MbrContains(poly, geom)``\n==========  ==========================\n\n.. fieldlookup:: bboverlaps\n\n``bboverlaps``\n--------------\n\n*Availability*: `PostGIS <https://postgis.net/docs/geometry_overlaps.html>`__,\nMariaDB, MySQL, SpatiaLite, PGRaster (Native)\n\nTests if the geometry field's bounding box overlaps the lookup geometry's\nbounding box.\n\nExample::\n\n    Zipcode.objects.filter(poly__bboverlaps=geom)\n\n==========  ==========================\nBackend     SQL Equivalent\n==========  ==========================\nPostGIS     ``poly && geom``\nMariaDB     ``MBROverlaps(poly, geom)``\nMySQL       ``MBROverlaps(poly, geom)``\nSpatiaLite  ``MbrOverlaps(poly, geom)``\n==========  ==========================\n\n.. fieldlookup:: contained\n\n``contained``\n-------------\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Geometry_Contained.html>`__,\nMariaDB, MySQL, SpatiaLite, PGRaster (Native)\n\nTests if the geometry field's bounding box is completely contained by the\nlookup geometry's bounding box.\n\nExample::\n\n    Zipcode.objects.filter(poly__contained=geom)\n\n==========  ==========================\nBackend     SQL Equivalent\n==========  ==========================\nPostGIS     ``poly @ geom``\nMariaDB     ``MBRWithin(poly, geom)``\nMySQL       ``MBRWithin(poly, geom)``\nSpatiaLite  ``MbrWithin(poly, geom)``\n==========  ==========================\n\n.. fieldlookup:: gis-contains\n\n``contains``\n------------\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Contains.html>`__,\nOracle, MariaDB, MySQL, SpatiaLite, PGRaster (Bilateral)\n\nTests if the geometry field spatially contains the lookup geometry.\n\nExample::\n\n    Zipcode.objects.filter(poly__contains=geom)\n\n==========  ============================\nBackend     SQL Equivalent\n==========  ============================\nPostGIS     ``ST_Contains(poly, geom)``\nOracle      ``SDO_CONTAINS(poly, geom)``\nMariaDB     ``ST_Contains(poly, geom)``\nMySQL       ``ST_Contains(poly, geom)``\nSpatiaLite  ``Contains(poly, geom)``\n==========  ============================\n\n.. fieldlookup:: contains_properly\n\n``contains_properly``\n---------------------\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_ContainsProperly.html>`__,\nPGRaster (Bilateral)\n\nReturns true if the lookup geometry intersects the interior of the\ngeometry field, but not the boundary (or exterior).\n\nExample::\n\n    Zipcode.objects.filter(poly__contains_properly=geom)\n\n==========  ===================================\nBackend     SQL Equivalent\n==========  ===================================\nPostGIS     ``ST_ContainsProperly(poly, geom)``\n==========  ===================================\n\n.. fieldlookup:: coveredby\n\n``coveredby``\n-------------\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_CoveredBy.html>`__,\nOracle, PGRaster (Bilateral), SpatiaLite\n\nTests if no point in the geometry field is outside the lookup geometry.\n[#fncovers]_\n\nExample::\n\n    Zipcode.objects.filter(poly__coveredby=geom)\n\n==========  =============================\nBackend     SQL Equivalent\n==========  =============================\nPostGIS     ``ST_CoveredBy(poly, geom)``\nOracle      ``SDO_COVEREDBY(poly, geom)``\nSpatiaLite  ``CoveredBy(poly, geom)``\n==========  =============================\n\n.. fieldlookup:: covers\n\n``covers``\n----------\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Covers.html>`__,\nOracle, PGRaster (Bilateral), SpatiaLite\n\nTests if no point in the lookup geometry is outside the geometry field.\n[#fncovers]_\n\nExample::\n\n    Zipcode.objects.filter(poly__covers=geom)\n\n==========  ==========================\nBackend     SQL Equivalent\n==========  ==========================\nPostGIS     ``ST_Covers(poly, geom)``\nOracle      ``SDO_COVERS(poly, geom)``\nSpatiaLite  ``Covers(poly, geom)``\n==========  ==========================\n\n.. fieldlookup:: crosses\n\n``crosses``\n-----------\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Crosses.html>`__,\nMariaDB, MySQL, SpatiaLite, PGRaster (Conversion)\n\nTests if the geometry field spatially crosses the lookup geometry.\n\nExample::\n\n    Zipcode.objects.filter(poly__crosses=geom)\n\n==========  ==========================\nBackend     SQL Equivalent\n==========  ==========================\nPostGIS     ``ST_Crosses(poly, geom)``\nMariaDB     ``ST_Crosses(poly, geom)``\nMySQL       ``ST_Crosses(poly, geom)``\nSpatiaLite  ``Crosses(poly, geom)``\n==========  ==========================\n\n.. fieldlookup:: disjoint\n\n``disjoint``\n------------\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Disjoint.html>`__,\nOracle, MariaDB, MySQL, SpatiaLite, PGRaster (Bilateral)\n\nTests if the geometry field is spatially disjoint from the lookup geometry.\n\nExample::\n\n    Zipcode.objects.filter(poly__disjoint=geom)\n\n==========  =================================================\nBackend     SQL Equivalent\n==========  =================================================\nPostGIS     ``ST_Disjoint(poly, geom)``\nOracle      ``SDO_GEOM.RELATE(poly, 'DISJOINT', geom, 0.05)``\nMariaDB     ``ST_Disjoint(poly, geom)``\nMySQL       ``ST_Disjoint(poly, geom)``\nSpatiaLite  ``Disjoint(poly, geom)``\n==========  =================================================\n\n.. fieldlookup:: equals\n\n``equals``\n----------\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Equals.html>`__,\nOracle, MariaDB, MySQL, SpatiaLite, PGRaster (Conversion)\n\nTests if the geometry field is spatially equal to the lookup geometry.\n\nExample::\n\n    Zipcode.objects.filter(poly__equals=geom)\n\n==========  =================================================\nBackend     SQL Equivalent\n==========  =================================================\nPostGIS     ``ST_Equals(poly, geom)``\nOracle      ``SDO_EQUAL(poly, geom)``\nMariaDB     ``ST_Equals(poly, geom)``\nMySQL       ``ST_Equals(poly, geom)``\nSpatiaLite  ``Equals(poly, geom)``\n==========  =================================================\n\n.. fieldlookup:: exact\n    :noindex:\n.. fieldlookup:: same_as\n\n``exact``, ``same_as``\n----------------------\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Geometry_Same.html>`__,\nOracle, MariaDB, MySQL, SpatiaLite, PGRaster (Bilateral)\n\nTests if the geometry field is \"equal\" to the lookup geometry. On Oracle,\nMySQL, and SpatiaLite, it tests spatial equality, while on PostGIS it tests\nequality of bounding boxes.\n\nExample::\n\n    Zipcode.objects.filter(poly=geom)\n\n==========  =================================================\nBackend     SQL Equivalent\n==========  =================================================\nPostGIS     ``poly ~= geom``\nOracle      ``SDO_EQUAL(poly, geom)``\nMariaDB     ``ST_Equals(poly, geom)``\nMySQL       ``ST_Equals(poly, geom)``\nSpatiaLite  ``Equals(poly, geom)``\n==========  =================================================\n\n.. fieldlookup:: intersects\n\n``intersects``\n--------------\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Intersects.html>`__,\nOracle, MariaDB, MySQL, SpatiaLite, PGRaster (Bilateral)\n\nTests if the geometry field spatially intersects the lookup geometry.\n\nExample::\n\n    Zipcode.objects.filter(poly__intersects=geom)\n\n==========  =================================================\nBackend     SQL Equivalent\n==========  =================================================\nPostGIS     ``ST_Intersects(poly, geom)``\nOracle      ``SDO_OVERLAPBDYINTERSECT(poly, geom)``\nMariaDB     ``ST_Intersects(poly, geom)``\nMySQL       ``ST_Intersects(poly, geom)``\nSpatiaLite  ``Intersects(poly, geom)``\n==========  =================================================\n\n.. fieldlookup:: isvalid\n\n``isvalid``\n-----------\n\n*Availability*: MySQL (≥ 5.7.5), `PostGIS\n<https://postgis.net/docs/ST_IsValid.html>`__, Oracle, SpatiaLite\n\nTests if the geometry is valid.\n\nExample::\n\n    Zipcode.objects.filter(poly__isvalid=True)\n\n==========================  ================================================================\nBackend                     SQL Equivalent\n==========================  ================================================================\nMySQL, PostGIS, SpatiaLite  ``ST_IsValid(poly)``\nOracle                      ``SDO_GEOM.VALIDATE_GEOMETRY_WITH_CONTEXT(poly, 0.05) = 'TRUE'``\n==========================  ================================================================\n\n.. fieldlookup:: overlaps\n\n``overlaps``\n------------\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Overlaps.html>`__,\nOracle, MariaDB, MySQL, SpatiaLite, PGRaster (Bilateral)\n\nTests if the geometry field spatially overlaps the lookup geometry.\n\n==========  ============================\nBackend     SQL Equivalent\n==========  ============================\nPostGIS     ``ST_Overlaps(poly, geom)``\nOracle      ``SDO_OVERLAPS(poly, geom)``\nMariaDB     ``ST_Overlaps(poly, geom)``\nMySQL       ``ST_Overlaps(poly, geom)``\nSpatiaLite  ``Overlaps(poly, geom)``\n==========  ============================\n\n.. fieldlookup:: relate\n\n``relate``\n----------\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Relate.html>`__,\nMariaDB, Oracle, SpatiaLite, PGRaster (Conversion)\n\nTests if the geometry field is spatially related to the lookup geometry by\nthe values given in the given pattern.  This lookup requires a tuple parameter,\n``(geom, pattern)``; the form of ``pattern`` will depend on the spatial backend:\n\nMariaDB, PostGIS, and SpatiaLite\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nOn these spatial backends the intersection pattern is a string comprising\nnine characters, which  define intersections between  the interior, boundary,\nand exterior of the geometry field and the lookup geometry.\nThe intersection pattern matrix may only use the following characters:\n``1``, ``2``, ``T``, ``F``, or ``*``.  This lookup type allows users to \"fine tune\"\na specific geometric relationship consistent with the DE-9IM model. [#fnde9im]_\n\nGeometry example::\n\n    # A tuple lookup parameter is used to specify the geometry and\n    # the intersection pattern (the pattern here is for 'contains').\n    Zipcode.objects.filter(poly__relate=(geom, 'T*T***FF*'))\n\nPostGIS and MariaDB SQL equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE ST_Relate(poly, geom, 'T*T***FF*')\n\nSpatiaLite SQL equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE Relate(poly, geom, 'T*T***FF*')\n\nRaster example::\n\n    Zipcode.objects.filter(poly__relate=(rast, 1, 'T*T***FF*'))\n    Zipcode.objects.filter(rast__2__relate=(rast, 1, 'T*T***FF*'))\n\nPostGIS SQL equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE ST_Relate(poly, ST_Polygon(rast, 1), 'T*T***FF*')\n    SELECT ... WHERE ST_Relate(ST_Polygon(rast, 2), ST_Polygon(rast, 1), 'T*T***FF*')\n\n.. versionchanged:: 3.1\n\n    MariaDB support was added.\n\nOracle\n~~~~~~\n\nHere the relation pattern is comprised of at least one of the nine relation\nstrings: ``TOUCH``, ``OVERLAPBDYDISJOINT``, ``OVERLAPBDYINTERSECT``,\n``EQUAL``, ``INSIDE``, ``COVEREDBY``, ``CONTAINS``, ``COVERS``, ``ON``, and\n``ANYINTERACT``.   Multiple strings may be combined with the logical Boolean\noperator OR, for example, ``'inside+touch'``. [#fnsdorelate]_  The relation\nstrings are case-insensitive.\n\nExample::\n\n    Zipcode.objects.filter(poly__relate=(geom, 'anyinteract'))\n\nOracle SQL equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE SDO_RELATE(poly, geom, 'anyinteract')\n\n.. fieldlookup:: touches\n\n``touches``\n-----------\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Touches.html>`__,\nOracle, MariaDB, MySQL, SpatiaLite\n\nTests if the geometry field spatially touches the lookup geometry.\n\nExample::\n\n    Zipcode.objects.filter(poly__touches=geom)\n\n==========  ==========================\nBackend     SQL Equivalent\n==========  ==========================\nPostGIS     ``ST_Touches(poly, geom)``\nMariaDB     ``ST_Touches(poly, geom)``\nMySQL       ``ST_Touches(poly, geom)``\nOracle      ``SDO_TOUCH(poly, geom)``\nSpatiaLite  ``Touches(poly, geom)``\n==========  ==========================\n\n.. fieldlookup:: within\n\n``within``\n----------\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Within.html>`__,\nOracle, MariaDB, MySQL, SpatiaLite, PGRaster (Bilateral)\n\nTests if the geometry field is spatially within the lookup geometry.\n\nExample::\n\n    Zipcode.objects.filter(poly__within=geom)\n\n==========  ==========================\nBackend     SQL Equivalent\n==========  ==========================\nPostGIS     ``ST_Within(poly, geom)``\nMariaDB     ``ST_Within(poly, geom)``\nMySQL       ``ST_Within(poly, geom)``\nOracle      ``SDO_INSIDE(poly, geom)``\nSpatiaLite  ``Within(poly, geom)``\n==========  ==========================\n\n.. fieldlookup:: left\n\n``left``\n--------\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Geometry_Left.html>`__,\nPGRaster (Conversion)\n\nTests if the geometry field's bounding box is strictly to the left of the\nlookup geometry's bounding box.\n\nExample::\n\n    Zipcode.objects.filter(poly__left=geom)\n\nPostGIS equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE poly << geom\n\n.. fieldlookup:: right\n\n``right``\n---------\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Geometry_Right.html>`__,\nPGRaster (Conversion)\n\nTests if the geometry field's bounding box is strictly to the right of the\nlookup geometry's bounding box.\n\nExample::\n\n    Zipcode.objects.filter(poly__right=geom)\n\nPostGIS equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE poly >> geom\n\n.. fieldlookup:: overlaps_left\n\n``overlaps_left``\n-----------------\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Geometry_Overleft.html>`__,\nPGRaster (Bilateral)\n\nTests if the geometry field's bounding box overlaps or is to the left of the lookup\ngeometry's bounding box.\n\nExample::\n\n    Zipcode.objects.filter(poly__overlaps_left=geom)\n\nPostGIS equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE poly &< geom\n\n\n.. fieldlookup:: overlaps_right\n\n``overlaps_right``\n------------------\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Geometry_Overright.html>`__,\nPGRaster (Bilateral)\n\nTests if the geometry field's bounding box overlaps or is to the right of the lookup\ngeometry's bounding box.\n\nExample::\n\n    Zipcode.objects.filter(poly__overlaps_right=geom)\n\nPostGIS equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE poly &> geom\n\n.. fieldlookup:: overlaps_above\n\n``overlaps_above``\n------------------\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Geometry_Overabove.html>`__,\nPGRaster (Conversion)\n\nTests if the geometry field's bounding box overlaps or is above the lookup\ngeometry's bounding box.\n\nExample::\n\n    Zipcode.objects.filter(poly__overlaps_above=geom)\n\nPostGIS equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE poly |&> geom\n\n.. fieldlookup:: overlaps_below\n\n``overlaps_below``\n------------------\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Geometry_Overbelow.html>`__,\nPGRaster (Conversion)\n\nTests if the geometry field's bounding box overlaps or is below the lookup\ngeometry's bounding box.\n\nExample::\n\n    Zipcode.objects.filter(poly__overlaps_below=geom)\n\nPostGIS equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE poly &<| geom\n\n.. fieldlookup:: strictly_above\n\n``strictly_above``\n------------------\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Geometry_Above.html>`__,\nPGRaster (Conversion)\n\nTests if the geometry field's bounding box is strictly above the lookup\ngeometry's bounding box.\n\nExample::\n\n    Zipcode.objects.filter(poly__strictly_above=geom)\n\nPostGIS equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE poly |>> geom\n\n.. fieldlookup:: strictly_below\n\n``strictly_below``\n------------------\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Geometry_Below.html>`__,\nPGRaster (Conversion)\n\nTests if the geometry field's bounding box is strictly below the lookup\ngeometry's bounding box.\n\nExample::\n\n    Zipcode.objects.filter(poly__strictly_below=geom)\n\nPostGIS equivalent:\n\n.. code-block:: sql\n\n    SELECT ... WHERE poly <<| geom\n\n\n.. _distance-lookups:\n\nDistance Lookups\n================\n\n*Availability*: PostGIS, Oracle, MariaDB, MySQL, SpatiaLite, PGRaster (Native)\n\nFor an overview on performing distance queries, please refer to\nthe :ref:`distance queries introduction <distance-queries>`.\n\nDistance lookups take the following form::\n\n    <field>__<distance lookup>=(<geometry/raster>, <distance value>[, 'spheroid'])\n    <field>__<distance lookup>=(<raster>, <band_index>, <distance value>[, 'spheroid'])\n    <field>__<band_index>__<distance lookup>=(<raster>, <band_index>, <distance value>[, 'spheroid'])\n\nThe value passed into a distance lookup is a tuple; the first two\nvalues are mandatory, and are the geometry to calculate distances to,\nand a distance value (either a number in units of the field, a\n:class:`~django.contrib.gis.measure.Distance` object, or a :doc:`query\nexpression </ref/models/expressions>`). To pass a band index to the lookup, use\na 3-tuple where the second entry is the band index.\n\nOn every distance lookup except :lookup:`dwithin`, an optional element,\n``'spheroid'``, may be included to use the more accurate spheroid distance\ncalculation functions on fields with a geodetic coordinate system.\n\nOn PostgreSQL, the ``'spheroid'`` option uses `ST_DistanceSpheroid\n<https://postgis.net/docs/ST_Distance_Spheroid.html>`__ instead of\n`ST_DistanceSphere <https://postgis.net/docs/ST_DistanceSphere.html>`__. The\nsimpler `ST_Distance <https://postgis.net/docs/ST_Distance.html>`__ function is\nused with projected coordinate systems. Rasters are converted to geometries for\nspheroid based lookups.\n\n.. fieldlookup:: distance_gt\n\n``distance_gt``\n---------------\n\nReturns models where the distance to the geometry field from the lookup\ngeometry is greater than the given distance value.\n\nExample::\n\n    Zipcode.objects.filter(poly__distance_gt=(geom, D(m=5)))\n\n==========  ==================================================\nBackend     SQL Equivalent\n==========  ==================================================\nPostGIS     ``ST_Distance/ST_Distance_Sphere(poly, geom) > 5``\nMariaDB     ``ST_Distance(poly, geom) > 5``\nMySQL       ``ST_Distance(poly, geom) > 5``\nOracle      ``SDO_GEOM.SDO_DISTANCE(poly, geom, 0.05) > 5``\nSpatiaLite  ``Distance(poly, geom) > 5``\n==========  ==================================================\n\n.. fieldlookup:: distance_gte\n\n``distance_gte``\n----------------\n\nReturns models where the distance to the geometry field from the lookup\ngeometry is greater than or equal to the given distance value.\n\nExample::\n\n    Zipcode.objects.filter(poly__distance_gte=(geom, D(m=5)))\n\n==========  ===================================================\nBackend     SQL Equivalent\n==========  ===================================================\nPostGIS     ``ST_Distance/ST_Distance_Sphere(poly, geom) >= 5``\nMariaDB     ``ST_Distance(poly, geom) >= 5``\nMySQL       ``ST_Distance(poly, geom) >= 5``\nOracle      ``SDO_GEOM.SDO_DISTANCE(poly, geom, 0.05) >= 5``\nSpatiaLite  ``Distance(poly, geom) >= 5``\n==========  ===================================================\n\n.. fieldlookup:: distance_lt\n\n``distance_lt``\n---------------\n\nReturns models where the distance to the geometry field from the lookup\ngeometry is less than the given distance value.\n\nExample::\n\n    Zipcode.objects.filter(poly__distance_lt=(geom, D(m=5)))\n\n==========  ==================================================\nBackend     SQL Equivalent\n==========  ==================================================\nPostGIS     ``ST_Distance/ST_Distance_Sphere(poly, geom) < 5``\nMariaDB     ``ST_Distance(poly, geom) < 5``\nMySQL       ``ST_Distance(poly, geom) < 5``\nOracle      ``SDO_GEOM.SDO_DISTANCE(poly, geom, 0.05) < 5``\nSpatiaLite  ``Distance(poly, geom) < 5``\n==========  ==================================================\n\n.. fieldlookup:: distance_lte\n\n``distance_lte``\n----------------\n\nReturns models where the distance to the geometry field from the lookup\ngeometry is less than or equal to the given distance value.\n\nExample::\n\n    Zipcode.objects.filter(poly__distance_lte=(geom, D(m=5)))\n\n==========  ===================================================\nBackend     SQL Equivalent\n==========  ===================================================\nPostGIS     ``ST_Distance/ST_Distance_Sphere(poly, geom) <= 5``\nMariaDB     ``ST_Distance(poly, geom) <= 5``\nMySQL       ``ST_Distance(poly, geom) <= 5``\nOracle      ``SDO_GEOM.SDO_DISTANCE(poly, geom, 0.05) <= 5``\nSpatiaLite  ``Distance(poly, geom) <= 5``\n==========  ===================================================\n\n.. fieldlookup:: dwithin\n\n``dwithin``\n-----------\n\nReturns models where the distance to the geometry field from the lookup\ngeometry are within the given distance from one another. Note that you can only\nprovide :class:`~django.contrib.gis.measure.Distance` objects if the targeted\ngeometries are in a projected system. For geographic geometries, you should use\nunits of the geometry field (e.g. degrees for ``WGS84``) .\n\nExample::\n\n    Zipcode.objects.filter(poly__dwithin=(geom, D(m=5)))\n\n==========  ======================================\nBackend     SQL Equivalent\n==========  ======================================\nPostGIS     ``ST_DWithin(poly, geom, 5)``\nOracle      ``SDO_WITHIN_DISTANCE(poly, geom, 5)``\nSpatiaLite  ``PtDistWithin(poly, geom, 5)``\n==========  ======================================\n\nAggregate Functions\n-------------------\n\nDjango provides some GIS-specific aggregate functions. For details on how to\nuse these aggregate functions, see :doc:`the topic guide on aggregation\n</topics/db/aggregation>`.\n\n=====================  =====================================================\nKeyword Argument       Description\n=====================  =====================================================\n``tolerance``          This keyword is for Oracle only.  It is for the\n                       tolerance value used by the ``SDOAGGRTYPE``\n                       procedure; the  `Oracle documentation`__ has more\n                       details.\n=====================  =====================================================\n\n__ https://docs.oracle.com/en/database/oracle/oracle-database/18/spatl/\n   spatial-concepts.html#GUID-CE10AB14-D5EA-43BA-A647-DAC9EEF41EE6\n\nExample::\n\n    >>> from django.contrib.gis.db.models import Extent, Union\n    >>> WorldBorder.objects.aggregate(Extent('mpoly'), Union('mpoly'))\n\n``Collect``\n~~~~~~~~~~~\n\n.. class:: Collect(geo_field)\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Collect.html>`__,\nSpatiaLite\n\nReturns a ``GEOMETRYCOLLECTION`` or a ``MULTI`` geometry object from the geometry\ncolumn. This is analogous to a simplified version of the :class:`Union`\naggregate, except it can be several orders of magnitude faster than performing\na union because it rolls up geometries into a collection or multi object, not\ncaring about dissolving boundaries.\n\n``Extent``\n~~~~~~~~~~\n\n.. class:: Extent(geo_field)\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Extent.html>`__,\nOracle, SpatiaLite\n\nReturns the extent of all ``geo_field`` in the ``QuerySet`` as a four-tuple,\ncomprising the lower left coordinate and the upper right coordinate.\n\nExample::\n\n    >>> qs = City.objects.filter(name__in=('Houston', 'Dallas')).aggregate(Extent('poly'))\n    >>> print(qs['poly__extent'])\n    (-96.8016128540039, 29.7633724212646, -95.3631439208984, 32.782058715820)\n\n``Extent3D``\n~~~~~~~~~~~~\n\n.. class:: Extent3D(geo_field)\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_3DExtent.html>`__\n\nReturns the 3D extent of all ``geo_field`` in the ``QuerySet`` as a six-tuple,\ncomprising the lower left coordinate and upper right coordinate (each with x, y,\nand z coordinates).\n\nExample::\n\n    >>> qs = City.objects.filter(name__in=('Houston', 'Dallas')).aggregate(Extent3D('poly'))\n    >>> print(qs['poly__extent3d'])\n    (-96.8016128540039, 29.7633724212646, 0, -95.3631439208984, 32.782058715820, 0)\n\n``MakeLine``\n~~~~~~~~~~~~\n\n.. class:: MakeLine(geo_field)\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_MakeLine.html>`__,\nSpatiaLite\n\nReturns a ``LineString`` constructed from the point field geometries in the\n``QuerySet``. Currently, ordering the queryset has no effect.\n\nExample::\n\n    >>> qs = City.objects.filter(name__in=('Houston', 'Dallas')).aggregate(MakeLine('poly'))\n    >>> print(qs['poly__makeline'])\n    LINESTRING (-95.3631510000000020 29.7633739999999989, -96.8016109999999941 32.7820570000000018)\n\n``Union``\n~~~~~~~~~\n\n.. class:: Union(geo_field)\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Union.html>`__,\nOracle, SpatiaLite\n\nThis method returns a :class:`~django.contrib.gis.geos.GEOSGeometry` object\ncomprising the union of every geometry in the queryset. Please note that use of\n``Union`` is processor intensive and may take a significant amount of time on\nlarge querysets.\n\n.. note::\n\n    If the computation time for using this method is too expensive, consider\n    using :class:`Collect` instead.\n\nExample::\n\n    >>> u = Zipcode.objects.aggregate(Union(poly))  # This may take a long time.\n    >>> u = Zipcode.objects.filter(poly__within=bbox).aggregate(Union(poly))  # A more sensible approach.\n\n.. rubric:: Footnotes\n.. [#fnde9im] *See* `OpenGIS Simple Feature Specification For SQL <http://www.opengis.org/docs/99-049.pdf>`_, at Ch. 2.1.13.2, p. 2-13 (The Dimensionally Extended Nine-Intersection Model).\n.. [#fnsdorelate] *See* `SDO_RELATE documentation <https://docs.oracle.com/en/\n   database/oracle/oracle-database/18/spatl/spatial-operators-reference.html#\n   GUID-97C17C18-F05E-49B4-BE11-E89B972E2A02>`_, from the Oracle Spatial and\n   Graph Developer's Guide.\n.. [#fncovers] For an explanation of this routine, read `Quirks of the \"Contains\" Spatial Predicate <https://lin-ear-th-inking.blogspot.com/2007/06/subtleties-of-ogc-covers-spatial.html>`_ by Martin Davis (a PostGIS developer).\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":127,"nodeType":"TextFile","repoName":null,"name":"db-api.txt","path":"docs/ref/contrib/gis","text":"======================\nGeoDjango Database API\n======================\n\n.. _spatial-backends:\n\nSpatial Backends\n================\n\n.. module:: django.contrib.gis.db.backends\n    :synopsis: GeoDjango's spatial database backends.\n\nGeoDjango currently provides the following spatial database backends:\n\n* ``django.contrib.gis.db.backends.postgis``\n* ``django.contrib.gis.db.backends.mysql``\n* ``django.contrib.gis.db.backends.oracle``\n* ``django.contrib.gis.db.backends.spatialite``\n\n.. _mysql-spatial-limitations:\n\nMySQL Spatial Limitations\n-------------------------\n\nBefore MySQL 5.6.1, spatial extensions only support bounding box operations\n(what MySQL calls minimum bounding rectangles, or MBR). Specifically, MySQL did\nnot conform to the OGC standard. Django supports spatial functions operating on\nreal geometries available in modern MySQL versions. However, the spatial\nfunctions are not as rich as other backends like PostGIS.\n\n.. warning::\n\n    True spatial indexes (R-trees) are only supported with\n    MyISAM tables on MySQL. [#fnmysqlidx]_ In other words, when using\n    MySQL spatial extensions you have to choose between fast spatial\n    lookups and the integrity of your data -- MyISAM tables do\n    not support transactions or foreign key constraints.\n\nRaster Support\n--------------\n\n``RasterField`` is currently only implemented for the PostGIS backend. Spatial\nlookups are available for raster fields, but spatial database functions and\naggregates aren't implemented for raster fields.\n\nCreating and Saving Models with Geometry Fields\n===============================================\n\nHere is an example of how to create a geometry object (assuming the ``Zipcode``\nmodel)::\n\n    >>> from zipcode.models import Zipcode\n    >>> z = Zipcode(code=77096, poly='POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))')\n    >>> z.save()\n\n:class:`~django.contrib.gis.geos.GEOSGeometry` objects may also be used to save geometric models::\n\n    >>> from django.contrib.gis.geos import GEOSGeometry\n    >>> poly = GEOSGeometry('POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))')\n    >>> z = Zipcode(code=77096, poly=poly)\n    >>> z.save()\n\nMoreover, if the ``GEOSGeometry`` is in a different coordinate system (has a\ndifferent SRID value) than that of the field, then it will be implicitly\ntransformed into the SRID of the model's field, using the spatial database's\ntransform procedure::\n\n    >>> poly_3084 = GEOSGeometry('POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))', srid=3084)  # SRID 3084 is 'NAD83(HARN) / Texas Centric Lambert Conformal'\n    >>> z = Zipcode(code=78212, poly=poly_3084)\n    >>> z.save()\n    >>> from django.db import connection\n    >>> print(connection.queries[-1]['sql']) # printing the last SQL statement executed (requires DEBUG=True)\n    INSERT INTO \"geoapp_zipcode\" (\"code\", \"poly\") VALUES (78212, ST_Transform(ST_GeomFromWKB('\\\\001 ... ', 3084), 4326))\n\nThus, geometry parameters may be passed in using the ``GEOSGeometry`` object, WKT\n(Well Known Text [#fnwkt]_), HEXEWKB (PostGIS specific -- a WKB geometry in\nhexadecimal [#fnewkb]_), and GeoJSON (see :rfc:`7946`). Essentially, if the\ninput is not a ``GEOSGeometry`` object, the geometry field will attempt to\ncreate a ``GEOSGeometry`` instance from the input.\n\nFor more information creating :class:`~django.contrib.gis.geos.GEOSGeometry`\nobjects, refer to the :ref:`GEOS tutorial <geos-tutorial>`.\n\n.. _creating-and-saving-raster-models:\n\nCreating and Saving Models with Raster Fields\n=============================================\n\nWhen creating raster models, the raster field will implicitly convert the input\ninto a :class:`~django.contrib.gis.gdal.GDALRaster` using lazy-evaluation.\nThe raster field will therefore accept any input that is accepted by the\n:class:`~django.contrib.gis.gdal.GDALRaster` constructor.\n\nHere is an example of how to create a raster object from a raster file\n``volcano.tif`` (assuming the ``Elevation`` model)::\n\n    >>> from elevation.models import Elevation\n    >>> dem = Elevation(name='Volcano', rast='/path/to/raster/volcano.tif')\n    >>> dem.save()\n\n:class:`~django.contrib.gis.gdal.GDALRaster` objects may also be used to save\nraster models::\n\n    >>> from django.contrib.gis.gdal import GDALRaster\n    >>> rast = GDALRaster({'width': 10, 'height': 10, 'name': 'Canyon', 'srid': 4326,\n    ...                    'scale': [0.1, -0.1], 'bands': [{\"data\": range(100)}]})\n    >>> dem = Elevation(name='Canyon', rast=rast)\n    >>> dem.save()\n\nNote that this equivalent to::\n\n    >>> dem = Elevation.objects.create(\n    ...     name='Canyon',\n    ...     rast={'width': 10, 'height': 10, 'name': 'Canyon', 'srid': 4326,\n    ...           'scale': [0.1, -0.1], 'bands': [{\"data\": range(100)}]},\n    ... )\n\n.. _spatial-lookups-intro:\n\nSpatial Lookups\n===============\n\nGeoDjango's lookup types may be used with any manager method like\n``filter()``, ``exclude()``, etc.  However, the lookup types unique to\nGeoDjango are only available on spatial fields.\n\nFilters on 'normal' fields (e.g. :class:`~django.db.models.CharField`)\nmay be chained with those on geographic fields. Geographic lookups accept\ngeometry and raster input on both sides and input types can be mixed freely.\n\nThe general structure of geographic lookups is described below. A complete\nreference can be found in the :ref:`spatial lookup reference<spatial-lookups>`.\n\nGeometry Lookups\n----------------\n\nGeographic queries with geometries take the following general form (assuming\nthe ``Zipcode`` model used in the :doc:`model-api`)::\n\n    >>> qs = Zipcode.objects.filter(<field>__<lookup_type>=<parameter>)\n    >>> qs = Zipcode.objects.exclude(...)\n\nFor example::\n\n    >>> qs = Zipcode.objects.filter(poly__contains=pnt)\n    >>> qs = Elevation.objects.filter(poly__contains=rst)\n\nIn this case, ``poly`` is the geographic field, :lookup:`contains <gis-contains>`\nis the spatial lookup type, ``pnt`` is the parameter (which may be a\n:class:`~django.contrib.gis.geos.GEOSGeometry` object or a string of\nGeoJSON , WKT, or HEXEWKB), and ``rst`` is a\n:class:`~django.contrib.gis.gdal.GDALRaster` object.\n\n.. _spatial-lookup-raster:\n\nRaster Lookups\n--------------\n\nThe raster lookup syntax is similar to the syntax for geometries. The only\ndifference is that a band index can be specified as additional input. If no band\nindex is specified, the first band is used by default (index ``0``). In that\ncase the syntax is identical to the syntax for geometry lookups.\n\nTo specify the band index, an additional parameter can be specified on both\nsides of the lookup. On the left hand side, the double underscore syntax is\nused to pass a band index. On the right hand side, a tuple of the raster and\nband index can be specified.\n\nThis results in the following general form for lookups involving rasters\n(assuming the ``Elevation`` model used in the :doc:`model-api`)::\n\n    >>> qs = Elevation.objects.filter(<field>__<lookup_type>=<parameter>)\n    >>> qs = Elevation.objects.filter(<field>__<band_index>__<lookup_type>=<parameter>)\n    >>> qs = Elevation.objects.filter(<field>__<lookup_type>=(<raster_input, <band_index>)\n\nFor example::\n\n    >>> qs = Elevation.objects.filter(rast__contains=geom)\n    >>> qs = Elevation.objects.filter(rast__contains=rst)\n    >>> qs = Elevation.objects.filter(rast__1__contains=geom)\n    >>> qs = Elevation.objects.filter(rast__contains=(rst, 1))\n    >>> qs = Elevation.objects.filter(rast__1__contains=(rst, 1))\n\nOn the left hand side of the example, ``rast`` is the geographic raster field\nand :lookup:`contains <gis-contains>` is the spatial lookup type. On the right\nhand side, ``geom`` is a geometry input and ``rst`` is a\n:class:`~django.contrib.gis.gdal.GDALRaster` object. The band index defaults to\n``0`` in the first two queries and is set to ``1`` on the others.\n\nWhile all spatial lookups can be used with raster objects on both sides, not all\nunderlying operators natively accept raster input. For cases where the operator\nexpects geometry input, the raster is automatically converted to a geometry.\nIt's important to keep this in mind when interpreting the lookup results.\n\nThe type of raster support is listed for all lookups in the :ref:`compatibility\ntable <spatial-lookup-compatibility>`. Lookups involving rasters are currently\nonly available for the PostGIS backend.\n\n.. _distance-queries:\n\nDistance Queries\n================\n\nIntroduction\n------------\n\nDistance calculations with spatial data is tricky because, unfortunately,\nthe Earth is not flat.  Some distance queries with fields in a geographic\ncoordinate system may have to be expressed differently because of\nlimitations in PostGIS.  Please see the :ref:`selecting-an-srid` section\nin the :doc:`model-api` documentation for more details.\n\n.. _distance-lookups-intro:\n\nDistance Lookups\n----------------\n\n*Availability*: PostGIS, MariaDB, MySQL, Oracle, SpatiaLite, PGRaster (Native)\n\nThe following distance lookups are available:\n\n* :lookup:`distance_lt`\n* :lookup:`distance_lte`\n* :lookup:`distance_gt`\n* :lookup:`distance_gte`\n* :lookup:`dwithin` (except MariaDB and MySQL)\n\n.. note::\n\n    For *measuring*, rather than querying on distances, use the\n    :class:`~django.contrib.gis.db.models.functions.Distance` function.\n\nDistance lookups take a tuple parameter comprising:\n\n#. A geometry or raster to base calculations from; and\n#. A number or :class:`~django.contrib.gis.measure.Distance` object containing the distance.\n\nIf a :class:`~django.contrib.gis.measure.Distance` object is used,\nit may be expressed in any units (the SQL generated will use units\nconverted to those of the field); otherwise, numeric parameters are assumed\nto be in the units of the field.\n\n.. note::\n\n    In PostGIS, ``ST_Distance_Sphere`` does *not* limit the geometry types\n    geographic distance queries are performed with. [#fndistsphere15]_  However,\n    these queries may take a long time, as great-circle distances must be\n    calculated on the fly for *every* row in the query.  This is because the\n    spatial index on traditional geometry fields cannot be used.\n\n    For much better performance on WGS84 distance queries, consider using\n    :ref:`geography columns <geography-type>` in your database instead because\n    they are able to use their spatial index in distance queries.\n    You can tell GeoDjango to use a geography column by setting ``geography=True``\n    in your field definition.\n\nFor example, let's say we have a ``SouthTexasCity`` model (from the\n:source:`GeoDjango distance tests <tests/gis_tests/distapp/models.py>` ) on a\n*projected* coordinate system valid for cities in southern Texas::\n\n    from django.contrib.gis.db import models\n\n    class SouthTexasCity(models.Model):\n        name = models.CharField(max_length=30)\n        # A projected coordinate system (only valid for South Texas!)\n        # is used, units are in meters.\n        point = models.PointField(srid=32140)\n\nThen distance queries may be performed as follows::\n\n    >>> from django.contrib.gis.geos import GEOSGeometry\n    >>> from django.contrib.gis.measure import D # ``D`` is a shortcut for ``Distance``\n    >>> from geoapp.models import SouthTexasCity\n    # Distances will be calculated from this point, which does not have to be projected.\n    >>> pnt = GEOSGeometry('POINT(-96.876369 29.905320)', srid=4326)\n    # If numeric parameter, units of field (meters in this case) are assumed.\n    >>> qs = SouthTexasCity.objects.filter(point__distance_lte=(pnt, 7000))\n    # Find all Cities within 7 km, > 20 miles away, and > 100 chains away (an obscure unit)\n    >>> qs = SouthTexasCity.objects.filter(point__distance_lte=(pnt, D(km=7)))\n    >>> qs = SouthTexasCity.objects.filter(point__distance_gte=(pnt, D(mi=20)))\n    >>> qs = SouthTexasCity.objects.filter(point__distance_gte=(pnt, D(chain=100)))\n\nRaster queries work the same way by replacing the geometry field ``point`` with\na raster field, or the ``pnt`` object with a raster object, or both. To specify\nthe band index of a raster input on the right hand side, a 3-tuple can be\npassed to the lookup as follows::\n\n    >>> qs = SouthTexasCity.objects.filter(point__distance_gte=(rst, 2, D(km=7)))\n\nWhere the band with index 2 (the third band) of the raster ``rst`` would be\nused for the lookup.\n\n.. _compatibility-table:\n\nCompatibility Tables\n====================\n\n.. _spatial-lookup-compatibility:\n\nSpatial Lookups\n---------------\n\nThe following table provides a summary of what spatial lookups are available\nfor each spatial database backend. The PostGIS Raster (PGRaster) lookups are\ndivided into the three categories described in the :ref:`raster lookup details\n<spatial-lookup-raster>`: native support ``N``, bilateral native support ``B``,\nand geometry conversion support ``C``.\n\n=================================  =========  ======== ========= ============ ========== ========\nLookup Type                        PostGIS    Oracle   MariaDB   MySQL [#]_   SpatiaLite PGRaster\n=================================  =========  ======== ========= ============ ========== ========\n:lookup:`bbcontains`               X                   X         X            X          N\n:lookup:`bboverlaps`               X                   X         X            X          N\n:lookup:`contained`                X                   X         X            X          N\n:lookup:`contains <gis-contains>`  X          X        X         X            X          B\n:lookup:`contains_properly`        X                                                     B\n:lookup:`coveredby`                X          X                               X          B\n:lookup:`covers`                   X          X                               X          B\n:lookup:`crosses`                  X                   X         X            X          C\n:lookup:`disjoint`                 X          X        X         X            X          B\n:lookup:`distance_gt`              X          X        X         X            X          N\n:lookup:`distance_gte`             X          X        X         X            X          N\n:lookup:`distance_lt`              X          X        X         X            X          N\n:lookup:`distance_lte`             X          X        X         X            X          N\n:lookup:`dwithin`                  X          X                               X          B\n:lookup:`equals`                   X          X        X         X            X          C\n:lookup:`exact <same_as>`          X          X        X         X            X          B\n:lookup:`intersects`               X          X        X         X            X          B\n:lookup:`isvalid`                  X          X                  X (≥ 5.7.5)  X (LWGEOM)\n:lookup:`overlaps`                 X          X        X         X            X          B\n:lookup:`relate`                   X          X        X                      X          C\n:lookup:`same_as`                  X          X        X         X            X          B\n:lookup:`touches`                  X          X        X         X            X          B\n:lookup:`within`                   X          X        X         X            X          B\n:lookup:`left`                     X                                                     C\n:lookup:`right`                    X                                                     C\n:lookup:`overlaps_left`            X                                                     B\n:lookup:`overlaps_right`           X                                                     B\n:lookup:`overlaps_above`           X                                                     C\n:lookup:`overlaps_below`           X                                                     C\n:lookup:`strictly_above`           X                                                     C\n:lookup:`strictly_below`           X                                                     C\n=================================  =========  ======== ========= ============ ========== ========\n\n.. _database-functions-compatibility:\n\nDatabase functions\n------------------\n\nThe following table provides a summary of what geography-specific database\nfunctions are available on each spatial backend.\n\n.. currentmodule:: django.contrib.gis.db.models.functions\n\n====================================  =======  ============== ============ =========== ==========\nFunction                              PostGIS  Oracle         MariaDB      MySQL       SpatiaLite\n====================================  =======  ============== ============ =========== ==========\n:class:`Area`                         X        X              X            X           X\n:class:`AsGeoJSON`                    X        X              X (≥ 10.2.4) X (≥ 5.7.5) X\n:class:`AsGML`                        X        X                                       X\n:class:`AsKML`                        X                                                X\n:class:`AsSVG`                        X                                                X\n:class:`AsWKB`                        X        X              X            X           X\n:class:`AsWKT`                        X        X              X            X           X\n:class:`Azimuth`                      X                                                X (LWGEOM)\n:class:`BoundingCircle`               X        X\n:class:`Centroid`                     X        X              X            X           X\n:class:`Difference`                   X        X              X            X           X\n:class:`Distance`                     X        X              X            X           X\n:class:`Envelope`                     X        X              X            X           X\n:class:`ForcePolygonCW`               X                                                X\n:class:`GeoHash`                      X                                    X (≥ 5.7.5) X (LWGEOM)\n:class:`Intersection`                 X        X              X            X           X\n:class:`IsValid`                      X        X                           X (≥ 5.7.5) X (LWGEOM)\n:class:`Length`                       X        X              X            X           X\n:class:`LineLocatePoint`              X                                                X\n:class:`MakeValid`                    X                                                X (LWGEOM)\n:class:`MemSize`                      X\n:class:`NumGeometries`                X        X              X            X           X\n:class:`NumPoints`                    X        X              X            X           X\n:class:`Perimeter`                    X        X                                       X\n:class:`PointOnSurface`               X        X              X                        X\n:class:`Reverse`                      X        X                                       X\n:class:`Scale`                        X                                                X\n:class:`SnapToGrid`                   X                                                X\n:class:`SymDifference`                X        X              X            X           X\n:class:`Transform`                    X        X                                       X\n:class:`Translate`                    X                                                X\n:class:`Union`                        X        X              X            X           X\n====================================  =======  ============== ============ =========== ==========\n\nAggregate Functions\n-------------------\n\nThe following table provides a summary of what GIS-specific aggregate functions\nare available on each spatial backend. Please note that MySQL does not\nsupport any of these aggregates, and is thus excluded from the table.\n\n.. currentmodule:: django.contrib.gis.db.models\n\n=======================  =======  ======  ==========\nAggregate                PostGIS  Oracle  SpatiaLite\n=======================  =======  ======  ==========\n:class:`Collect`         X                X\n:class:`Extent`          X        X       X\n:class:`Extent3D`        X\n:class:`MakeLine`        X                X\n:class:`Union`           X        X       X\n=======================  =======  ======  ==========\n\n.. rubric:: Footnotes\n.. [#fnwkt] *See* Open Geospatial Consortium, Inc., `OpenGIS Simple Feature Specification For SQL <http://www.opengis.org/docs/99-049.pdf>`_, Document 99-049 (May 5, 1999), at  Ch. 3.2.5, p. 3-11 (SQL Textual Representation of Geometry).\n.. [#fnewkb] *See* `PostGIS EWKB, EWKT and Canonical Forms <https://postgis.net/docs/using_postgis_dbmanagement.html#EWKB_EWKT>`_, PostGIS documentation at Ch. 4.1.2.\n.. [#fndistsphere15] *See* `PostGIS documentation <https://postgis.net/docs/ST_DistanceSphere.html>`_ on ``ST_DistanceSphere``.\n.. [#fnmysqlidx] *See* `Creating Spatial Indexes <https://dev.mysql.com/doc/refman/en/creating-spatial-indexes.html>`_\n   in the MySQL Reference Manual:\n\n        For MyISAM tables, ``SPATIAL INDEX`` creates an R-tree index. For storage\n        engines that support nonspatial indexing of spatial columns, the engine\n        creates a B-tree index. A B-tree index on spatial values will be useful\n        for exact-value lookups, but not for range scans.\n\n.. [#] Refer :ref:`mysql-spatial-limitations` section for more details.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":128,"nodeType":"TextFile","repoName":null,"name":"commands.txt","path":"docs/ref/contrib/gis","text":"=============================\nGeoDjango Management Commands\n=============================\n\n``inspectdb``\n=============\n\n.. describe:: django-admin inspectdb\n\nWhen :mod:`django.contrib.gis` is in your :setting:`INSTALLED_APPS`, the\n:djadmin:`inspectdb` management command is overridden with one from GeoDjango.\nThe overridden command is spatially-aware, and places geometry fields in the\nauto-generated model definition, where appropriate.\n\n``ogrinspect``\n==============\n\n.. django-admin:: ogrinspect data_source model_name\n\nThe ``ogrinspect`` management command will inspect the given OGR-compatible\n:class:`~django.contrib.gis.gdal.DataSource` (e.g., a shapefile) and will\noutput a GeoDjango model with the given model name.  There's a detailed example\nof using ``ogrinspect`` :ref:`in the tutorial <ogrinspect-intro>`.\n\n.. django-admin-option:: --blank BLANK\n\n    Use a comma separated list of OGR field names to add the ``blank=True``\n    keyword option to the field definition.  Set with ``true`` to apply\n    to all applicable fields.\n\n.. django-admin-option:: --decimal DECIMAL\n\n    Use a comma separated list of OGR float fields to generate\n    :class:`~django.db.models.DecimalField` instead of the default\n    :class:`~django.db.models.FloatField`. Set to ``true`` to apply to all\n    OGR float fields.\n\n.. django-admin-option:: --geom-name GEOM_NAME\n\n    Specifies the model attribute name to use for the geometry field.\n    Defaults to ``'geom'``.\n\n.. django-admin-option:: --layer LAYER_KEY\n\n    The key for specifying which layer in the OGR\n    :class:`~django.contrib.gis.gdal.DataSource` source to use.\n    Defaults to 0 (the first layer). May be an integer or a string identifier\n    for the :class:`~django.contrib.gis.gdal.Layer`. When inspecting databases,\n    ``layer`` is generally the table name you want to inspect.\n\n.. django-admin-option:: --mapping\n\n    Automatically generate a mapping dictionary for use with\n    :class:`~django.contrib.gis.utils.LayerMapping`.\n\n.. django-admin-option:: --multi-geom\n\n    When generating the geometry field, treat it as a geometry collection.\n    For example, if this setting is enabled then a\n    :class:`~django.contrib.gis.db.models.MultiPolygonField` will be placed\n    in the generated model rather than\n    :class:`~django.contrib.gis.db.models.PolygonField`.\n\n.. django-admin-option:: --name-field NAME_FIELD\n\n    Generates a ``__str__()`` method on the model that returns the given field\n    name.\n\n.. django-admin-option:: --no-imports\n\n    Suppresses the ``from django.contrib.gis.db import models`` import statement.\n\n.. django-admin-option:: --null NULL\n\n    Use a comma separated list of OGR field names to add the ``null=True``\n    keyword option to the field definition.  Set with ``true`` to apply to\n    all applicable fields.\n\n.. django-admin-option:: --srid SRID\n\n    The SRID to use for the geometry field.  If not set, ``ogrinspect`` attempts\n    to automatically determine of the SRID of the data source.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":129,"nodeType":"TextFile","repoName":null,"name":"tutorial.txt","path":"docs/ref/contrib/gis","text":"==================\nGeoDjango Tutorial\n==================\n\nIntroduction\n============\n\nGeoDjango is an included contrib module for Django that turns it into a\nworld-class geographic Web framework.  GeoDjango strives to make it as simple\nas possible to create geographic Web applications, like location-based services.\nIts features include:\n\n* Django model fields for `OGC`_ geometries and raster data.\n* Extensions to Django's ORM for querying and manipulating spatial data.\n* Loosely-coupled, high-level Python interfaces for GIS geometry and raster\n  operations and data manipulation in different formats.\n* Editing geometry fields from the admin.\n\nThis tutorial assumes familiarity with Django; thus, if you're brand new to\nDjango, please read through the :doc:`regular tutorial </intro/tutorial01>` to\nfamiliarize yourself with Django first.\n\n.. note::\n\n    GeoDjango has additional requirements beyond what Django requires --\n    please consult the :doc:`installation documentation <install/index>`\n    for more details.\n\nThis tutorial will guide you through the creation of a geographic web\napplication for viewing the `world borders`_. [#]_ Some of the code\nused in this tutorial is taken from and/or inspired by the `GeoDjango\nbasic apps`_ project. [#]_\n\n.. note::\n\n    Proceed through the tutorial sections sequentially for step-by-step\n    instructions.\n\n.. _OGC: https://www.opengeospatial.org/\n.. _world borders: https://thematicmapping.org/downloads/world_borders.php\n.. _GeoDjango basic apps: https://code.google.com/p/geodjango-basic-apps/\n\nSetting Up\n==========\n\nCreate a Spatial Database\n-------------------------\n\nTypically no special setup is required, so you can create a database as you\nwould for any other project. We provide some tips for selected databases:\n\n* :doc:`install/postgis`\n* :doc:`install/spatialite`\n\nCreate a New Project\n--------------------\n\nUse the standard ``django-admin`` script to create a project called\n``geodjango``:\n\n.. console::\n\n    $ django-admin startproject geodjango\n\nThis will initialize a new project. Now, create a ``world`` Django application\nwithin the ``geodjango`` project:\n\n.. console::\n\n    $ cd geodjango\n    $ python manage.py startapp world\n\nConfigure ``settings.py``\n-------------------------\n\nThe ``geodjango`` project settings are stored in the ``geodjango/settings.py``\nfile. Edit the database connection settings to match your setup::\n\n    DATABASES = {\n        'default': {\n             'ENGINE': 'django.contrib.gis.db.backends.postgis',\n             'NAME': 'geodjango',\n             'USER': 'geo',\n        },\n    }\n\nIn addition, modify the :setting:`INSTALLED_APPS` setting to include\n:mod:`django.contrib.admin`, :mod:`django.contrib.gis`,\nand ``world`` (your newly created application)::\n\n    INSTALLED_APPS = [\n        'django.contrib.admin',\n        'django.contrib.auth',\n        'django.contrib.contenttypes',\n        'django.contrib.sessions',\n        'django.contrib.messages',\n        'django.contrib.staticfiles',\n        'django.contrib.gis',\n        'world',\n    ]\n\nGeographic Data\n===============\n\n.. _worldborders:\n\nWorld Borders\n-------------\n\nThe world borders data is available in this `zip file`__.  Create a ``data``\ndirectory in the ``world`` application, download the world borders data, and\nunzip. On GNU/Linux platforms, use the following commands:\n\n.. console::\n\n    $ mkdir world/data\n    $ cd world/data\n    $ wget https://thematicmapping.org/downloads/TM_WORLD_BORDERS-0.3.zip\n    $ unzip TM_WORLD_BORDERS-0.3.zip\n    $ cd ../..\n\nThe world borders ZIP file contains a set of data files collectively known as\nan `ESRI Shapefile`__, one of the most popular geospatial data formats.  When\nunzipped, the world borders dataset includes files with the following\nextensions:\n\n* ``.shp``: Holds the vector data for the world borders geometries.\n* ``.shx``: Spatial index file for geometries stored in the ``.shp``.\n* ``.dbf``: Database file for holding non-geometric attribute data\n  (e.g., integer and character fields).\n* ``.prj``: Contains the spatial reference information for the geographic\n  data stored in the shapefile.\n\n__ https://thematicmapping.org/downloads/TM_WORLD_BORDERS-0.3.zip\n__ https://en.wikipedia.org/wiki/Shapefile\n\nUse ``ogrinfo`` to examine spatial data\n---------------------------------------\n\nThe GDAL ``ogrinfo`` utility allows examining the metadata of shapefiles or\nother vector data sources:\n\n.. console::\n\n    $ ogrinfo world/data/TM_WORLD_BORDERS-0.3.shp\n    INFO: Open of `world/data/TM_WORLD_BORDERS-0.3.shp'\n          using driver `ESRI Shapefile' successful.\n    1: TM_WORLD_BORDERS-0.3 (Polygon)\n\n``ogrinfo`` tells us that the shapefile has one layer, and that this\nlayer contains polygon data.  To find out more, we'll specify the layer name\nand use the ``-so`` option to get only the important summary information:\n\n.. console::\n\n    $ ogrinfo -so world/data/TM_WORLD_BORDERS-0.3.shp TM_WORLD_BORDERS-0.3\n    INFO: Open of `world/data/TM_WORLD_BORDERS-0.3.shp'\n          using driver `ESRI Shapefile' successful.\n\n    Layer name: TM_WORLD_BORDERS-0.3\n    Geometry: Polygon\n    Feature Count: 246\n    Extent: (-180.000000, -90.000000) - (180.000000, 83.623596)\n    Layer SRS WKT:\n    GEOGCS[\"GCS_WGS_1984\",\n        DATUM[\"WGS_1984\",\n            SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],\n        PRIMEM[\"Greenwich\",0.0],\n        UNIT[\"Degree\",0.0174532925199433]]\n    FIPS: String (2.0)\n    ISO2: String (2.0)\n    ISO3: String (3.0)\n    UN: Integer (3.0)\n    NAME: String (50.0)\n    AREA: Integer (7.0)\n    POP2005: Integer (10.0)\n    REGION: Integer (3.0)\n    SUBREGION: Integer (3.0)\n    LON: Real (8.3)\n    LAT: Real (7.3)\n\nThis detailed summary information tells us the number of features in the layer\n(246), the geographic bounds of the data, the spatial reference system\n(\"SRS WKT\"), as well as type information for each attribute field. For example,\n``FIPS: String (2.0)`` indicates that the ``FIPS`` character field has\na maximum length of 2.  Similarly, ``LON: Real (8.3)`` is a floating-point\nfield that holds a maximum of 8 digits up to three decimal places.\n\nGeographic Models\n=================\n\nDefining a Geographic Model\n---------------------------\n\nNow that you've examined your dataset using ``ogrinfo``, create a GeoDjango\nmodel to represent this data::\n\n    from django.contrib.gis.db import models\n\n    class WorldBorder(models.Model):\n        # Regular Django fields corresponding to the attributes in the\n        # world borders shapefile.\n        name = models.CharField(max_length=50)\n        area = models.IntegerField()\n        pop2005 = models.IntegerField('Population 2005')\n        fips = models.CharField('FIPS Code', max_length=2)\n        iso2 = models.CharField('2 Digit ISO', max_length=2)\n        iso3 = models.CharField('3 Digit ISO', max_length=3)\n        un = models.IntegerField('United Nations Code')\n        region = models.IntegerField('Region Code')\n        subregion = models.IntegerField('Sub-Region Code')\n        lon = models.FloatField()\n        lat = models.FloatField()\n\n        # GeoDjango-specific: a geometry field (MultiPolygonField)\n        mpoly = models.MultiPolygonField()\n\n        # Returns the string representation of the model.\n        def __str__(self):\n            return self.name\n\nNote that the ``models`` module is imported from ``django.contrib.gis.db``.\n\nThe default spatial reference system for geometry fields is WGS84 (meaning\nthe `SRID`__ is 4326) -- in other words, the field coordinates are in\nlongitude, latitude pairs in units of degrees.  To use a different\ncoordinate system, set the SRID of the geometry field with the ``srid``\nargument. Use an integer representing the coordinate system's EPSG code.\n\n__ https://en.wikipedia.org/wiki/SRID\n\nRun ``migrate``\n---------------\n\nAfter defining your model, you need to sync it with the database. First,\ncreate a database migration:\n\n.. console::\n\n    $ python manage.py makemigrations\n    Migrations for 'world':\n      world/migrations/0001_initial.py:\n        - Create model WorldBorder\n\nLet's look at the SQL that will generate the table for the ``WorldBorder``\nmodel:\n\n.. console::\n\n    $ python manage.py sqlmigrate world 0001\n\nThis command should produce the following output:\n\n.. console::\n\n    BEGIN;\n    --\n    -- Create model WorldBorder\n    --\n    CREATE TABLE \"world_worldborder\" (\n        \"id\" serial NOT NULL PRIMARY KEY,\n        \"name\" varchar(50) NOT NULL,\n        \"area\" integer NOT NULL,\n        \"pop2005\" integer NOT NULL,\n        \"fips\" varchar(2) NOT NULL,\n        \"iso2\" varchar(2) NOT NULL,\n        \"iso3\" varchar(3) NOT NULL,\n        \"un\" integer NOT NULL,\n        \"region\" integer NOT NULL,\n        \"subregion\" integer NOT NULL,\n        \"lon\" double precision NOT NULL,\n        \"lat\" double precision NOT NULL\n        \"mpoly\" geometry(MULTIPOLYGON,4326) NOT NULL\n    )\n    ;\n    CREATE INDEX \"world_worldborder_mpoly_id\" ON \"world_worldborder\" USING GIST ( \"mpoly\" );\n    COMMIT;\n\nIf this looks correct, run :djadmin:`migrate` to create this table in the\ndatabase:\n\n.. console::\n\n    $ python manage.py migrate\n    Operations to perform:\n      Apply all migrations: admin, auth, contenttypes, sessions, world\n    Running migrations:\n      ...\n      Applying world.0001_initial... OK\n\nImporting Spatial Data\n======================\n\nThis section will show you how to import the world borders shapefile into the\ndatabase via GeoDjango models using the :doc:`layermapping`.\n\nThere are many different ways to import data into a spatial database --\nbesides the tools included within GeoDjango, you may also use the following:\n\n* `ogr2ogr`_: A command-line utility included with GDAL that\n  can import many vector data formats into PostGIS, MySQL, and Oracle databases.\n* `shp2pgsql`_: This utility included with PostGIS imports ESRI shapefiles into\n  PostGIS.\n\n.. _ogr2ogr: https://gdal.org/programs/ogr2ogr.html\n.. _shp2pgsql: https://postgis.net/docs/using_postgis_dbmanagement.html#shp2pgsql_usage\n\n.. _gdalinterface:\n\nGDAL Interface\n--------------\n\nEarlier, you used ``ogrinfo`` to examine the contents of the world borders\nshapefile.  GeoDjango also includes a Pythonic interface to GDAL's powerful OGR\nlibrary that can work with all the vector data sources that OGR supports.\n\nFirst, invoke the Django shell:\n\n.. console::\n\n    $ python manage.py shell\n\nIf you downloaded the :ref:`worldborders` data earlier in the tutorial, then\nyou can determine its path using Python's :class:`pathlib.Path`::\n\n    >>> from pathlib import Path\n    >>> import world\n    >>> world_shp = Path(world.__file__).resolve().parent / 'data' / 'TM_WORLD_BORDERS-0.3.shp'\n\nNow, open the world borders shapefile using GeoDjango's\n:class:`~django.contrib.gis.gdal.DataSource` interface::\n\n    >>> from django.contrib.gis.gdal import DataSource\n    >>> ds = DataSource(world_shp)\n    >>> print(ds)\n    / ... /geodjango/world/data/TM_WORLD_BORDERS-0.3.shp (ESRI Shapefile)\n\nData source objects can have different layers of geospatial features; however,\nshapefiles are only allowed to have one layer::\n\n    >>> print(len(ds))\n    1\n    >>> lyr = ds[0]\n    >>> print(lyr)\n    TM_WORLD_BORDERS-0.3\n\nYou can see the layer's geometry type and how many features it contains::\n\n    >>> print(lyr.geom_type)\n    Polygon\n    >>> print(len(lyr))\n    246\n\n.. note::\n\n    Unfortunately, the shapefile data format does not allow for greater\n    specificity with regards to geometry types.  This shapefile, like\n    many others, actually includes ``MultiPolygon`` geometries, not Polygons.\n    It's important to use a more general field type in models: a\n    GeoDjango ``MultiPolygonField`` will accept a ``Polygon`` geometry, but a\n    ``PolygonField`` will not accept a ``MultiPolygon`` type geometry.  This\n    is why the ``WorldBorder`` model defined above uses a ``MultiPolygonField``.\n\nThe :class:`~django.contrib.gis.gdal.Layer` may also have a spatial reference\nsystem associated with it.  If it does, the ``srs`` attribute will return a\n:class:`~django.contrib.gis.gdal.SpatialReference` object::\n\n    >>> srs = lyr.srs\n    >>> print(srs)\n    GEOGCS[\"GCS_WGS_1984\",\n        DATUM[\"WGS_1984\",\n            SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],\n        PRIMEM[\"Greenwich\",0.0],\n        UNIT[\"Degree\",0.0174532925199433]]\n    >>> srs.proj # PROJ representation\n    '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs '\n\nThis shapefile is in the popular WGS84 spatial reference\nsystem -- in other words, the data uses longitude, latitude pairs in\nunits of degrees.\n\nIn addition, shapefiles also support attribute fields that may contain\nadditional data.  Here are the fields on the World Borders layer:\n\n    >>> print(lyr.fields)\n    ['FIPS', 'ISO2', 'ISO3', 'UN', 'NAME', 'AREA', 'POP2005', 'REGION', 'SUBREGION', 'LON', 'LAT']\n\nThe following code will let you examine the OGR types (e.g. integer or\nstring) associated with each of the fields:\n\n    >>> [fld.__name__ for fld in lyr.field_types]\n    ['OFTString', 'OFTString', 'OFTString', 'OFTInteger', 'OFTString', 'OFTInteger', 'OFTInteger', 'OFTInteger', 'OFTInteger', 'OFTReal', 'OFTReal']\n\nYou can iterate over each feature in the layer and extract information from both\nthe feature's geometry (accessed via the ``geom`` attribute) as well as the\nfeature's attribute fields (whose **values** are accessed via ``get()``\nmethod)::\n\n    >>> for feat in lyr:\n    ...    print(feat.get('NAME'), feat.geom.num_points)\n    ...\n    Guernsey 18\n    Jersey 26\n    South Georgia South Sandwich Islands 338\n    Taiwan 363\n\n:class:`~django.contrib.gis.gdal.Layer` objects may be sliced::\n\n    >>> lyr[0:2]\n    [<django.contrib.gis.gdal.feature.Feature object at 0x2f47690>, <django.contrib.gis.gdal.feature.Feature object at 0x2f47650>]\n\nAnd individual features may be retrieved by their feature ID::\n\n    >>> feat = lyr[234]\n    >>> print(feat.get('NAME'))\n    San Marino\n\nBoundary geometries may be exported as WKT and GeoJSON::\n\n    >>> geom = feat.geom\n    >>> print(geom.wkt)\n    POLYGON ((12.415798 43.957954,12.450554 ...\n    >>> print(geom.json)\n    { \"type\": \"Polygon\", \"coordinates\": [ [ [ 12.415798, 43.957954 ], [ 12.450554, 43.979721 ], ...\n\n\n``LayerMapping``\n----------------\n\nTo import the data, use a LayerMapping in a Python script.\nCreate a file called ``load.py`` inside the ``world`` application,\nwith the following code::\n\n    from pathlib import Path\n    from django.contrib.gis.utils import LayerMapping\n    from .models import WorldBorder\n\n    world_mapping = {\n        'fips' : 'FIPS',\n        'iso2' : 'ISO2',\n        'iso3' : 'ISO3',\n        'un' : 'UN',\n        'name' : 'NAME',\n        'area' : 'AREA',\n        'pop2005' : 'POP2005',\n        'region' : 'REGION',\n        'subregion' : 'SUBREGION',\n        'lon' : 'LON',\n        'lat' : 'LAT',\n        'mpoly' : 'MULTIPOLYGON',\n    }\n\n    world_shp = Path(__file__).resolve().parent / 'data' / 'TM_WORLD_BORDERS-0.3.shp'\n\n    def run(verbose=True):\n        lm = LayerMapping(WorldBorder, world_shp, world_mapping, transform=False)\n        lm.save(strict=True, verbose=verbose)\n\nA few notes about what's going on:\n\n* Each key in the ``world_mapping`` dictionary corresponds to a field in the\n  ``WorldBorder`` model.  The value is the name of the shapefile field\n  that data will be loaded from.\n* The key ``mpoly`` for the geometry field is ``MULTIPOLYGON``, the\n  geometry type GeoDjango will import the field as.  Even simple polygons in\n  the shapefile will automatically be converted into collections prior to\n  insertion into the database.\n* The path to the shapefile is not absolute -- in other words, if you move the\n  ``world`` application (with ``data`` subdirectory) to a different location,\n  the script will still work.\n* The ``transform`` keyword is set to ``False`` because the data in the\n  shapefile does not need to be converted -- it's already in WGS84 (SRID=4326).\n\nAfterwards, invoke the Django shell from the ``geodjango`` project directory:\n\n.. console::\n\n    $ python manage.py shell\n\nNext, import the ``load`` module, call the ``run`` routine, and watch\n``LayerMapping`` do the work::\n\n    >>> from world import load\n    >>> load.run()\n\n.. _ogrinspect-intro:\n\nTry ``ogrinspect``\n------------------\nNow that you've seen how to define geographic models and import data with the\n:doc:`layermapping`, it's possible to further automate this process with\nuse of the :djadmin:`ogrinspect` management command.  The :djadmin:`ogrinspect`\ncommand  introspects a GDAL-supported vector data source (e.g., a shapefile)\nand generates a model definition and ``LayerMapping`` dictionary automatically.\n\nThe general usage of the command goes as follows:\n\n.. console::\n\n    $ python manage.py ogrinspect [options] <data_source> <model_name> [options]\n\n``data_source`` is the path to the GDAL-supported data source and\n``model_name`` is the name to use for the model.  Command-line options may\nbe used to further define how the model is generated.\n\nFor example, the following command nearly reproduces the ``WorldBorder`` model\nand mapping dictionary created above, automatically:\n\n.. console::\n\n    $ python manage.py ogrinspect world/data/TM_WORLD_BORDERS-0.3.shp WorldBorder \\\n        --srid=4326 --mapping --multi\n\nA few notes about the command-line options given above:\n\n* The ``--srid=4326`` option sets the SRID for the geographic field.\n* The ``--mapping`` option tells ``ogrinspect`` to also generate a\n  mapping dictionary for use with\n  :class:`~django.contrib.gis.utils.LayerMapping`.\n* The ``--multi`` option is specified so that the geographic field is a\n  :class:`~django.contrib.gis.db.models.MultiPolygonField` instead of just a\n  :class:`~django.contrib.gis.db.models.PolygonField`.\n\nThe command produces the following output, which may be copied\ndirectly into the ``models.py`` of a GeoDjango application::\n\n    # This is an auto-generated Django model module created by ogrinspect.\n    from django.contrib.gis.db import models\n\n    class WorldBorder(models.Model):\n        fips = models.CharField(max_length=2)\n        iso2 = models.CharField(max_length=2)\n        iso3 = models.CharField(max_length=3)\n        un = models.IntegerField()\n        name = models.CharField(max_length=50)\n        area = models.IntegerField()\n        pop2005 = models.IntegerField()\n        region = models.IntegerField()\n        subregion = models.IntegerField()\n        lon = models.FloatField()\n        lat = models.FloatField()\n        geom = models.MultiPolygonField(srid=4326)\n\n    # Auto-generated `LayerMapping` dictionary for WorldBorder model\n    worldborders_mapping = {\n        'fips' : 'FIPS',\n        'iso2' : 'ISO2',\n        'iso3' : 'ISO3',\n        'un' : 'UN',\n        'name' : 'NAME',\n        'area' : 'AREA',\n        'pop2005' : 'POP2005',\n        'region' : 'REGION',\n        'subregion' : 'SUBREGION',\n        'lon' : 'LON',\n        'lat' : 'LAT',\n        'geom' : 'MULTIPOLYGON',\n    }\n\nSpatial Queries\n===============\n\nSpatial Lookups\n---------------\nGeoDjango adds spatial lookups to the Django ORM.  For example, you\ncan find the country in the ``WorldBorder`` table that contains\na particular point.  First, fire up the management shell:\n\n.. console::\n\n    $ python manage.py shell\n\nNow, define a point of interest [#]_::\n\n    >>> pnt_wkt = 'POINT(-95.3385 29.7245)'\n\nThe ``pnt_wkt`` string represents the point at -95.3385 degrees longitude,\n29.7245 degrees latitude.  The geometry is in a format known as\nWell Known Text (WKT), a standard issued by the Open Geospatial\nConsortium (OGC). [#]_  Import the ``WorldBorder`` model, and perform\na ``contains`` lookup using the ``pnt_wkt`` as the parameter::\n\n    >>> from world.models import WorldBorder\n    >>> WorldBorder.objects.filter(mpoly__contains=pnt_wkt)\n    <QuerySet [<WorldBorder: United States>]>\n\nHere, you retrieved a ``QuerySet`` with only one model: the border of the\nUnited States (exactly what you would expect).\n\nSimilarly, you may also use a :doc:`GEOS geometry object <geos>`.\nHere, you can combine the ``intersects`` spatial lookup with the ``get``\nmethod to retrieve only the ``WorldBorder`` instance for San Marino instead\nof a queryset::\n\n    >>> from django.contrib.gis.geos import Point\n    >>> pnt = Point(12.4604, 43.9420)\n    >>> WorldBorder.objects.get(mpoly__intersects=pnt)\n    <WorldBorder: San Marino>\n\nThe ``contains`` and ``intersects`` lookups are just a subset of the\navailable queries -- the :doc:`db-api` documentation has more.\n\n.. _automatic-spatial-transformations:\n\nAutomatic Spatial Transformations\n---------------------------------\nWhen doing spatial queries, GeoDjango automatically transforms\ngeometries if they're in a different coordinate system.  In the following\nexample, coordinates will be expressed in `EPSG SRID 32140`__,\na coordinate system specific to south Texas **only** and in units of\n**meters**, not degrees::\n\n    >>> from django.contrib.gis.geos import GEOSGeometry, Point\n    >>> pnt = Point(954158.1, 4215137.1, srid=32140)\n\nNote that ``pnt`` may also be constructed with EWKT, an \"extended\" form of\nWKT that includes the SRID::\n\n    >>> pnt = GEOSGeometry('SRID=32140;POINT(954158.1 4215137.1)')\n\nGeoDjango's ORM will automatically wrap geometry values\nin transformation SQL, allowing the developer to work at a higher level\nof abstraction::\n\n    >>> qs = WorldBorder.objects.filter(mpoly__intersects=pnt)\n    >>> print(qs.query) # Generating the SQL\n    SELECT \"world_worldborder\".\"id\", \"world_worldborder\".\"name\", \"world_worldborder\".\"area\",\n    \"world_worldborder\".\"pop2005\", \"world_worldborder\".\"fips\", \"world_worldborder\".\"iso2\",\n    \"world_worldborder\".\"iso3\", \"world_worldborder\".\"un\", \"world_worldborder\".\"region\",\n    \"world_worldborder\".\"subregion\", \"world_worldborder\".\"lon\", \"world_worldborder\".\"lat\",\n    \"world_worldborder\".\"mpoly\" FROM \"world_worldborder\"\n    WHERE ST_Intersects(\"world_worldborder\".\"mpoly\", ST_Transform(%s, 4326))\n    >>> qs # printing evaluates the queryset\n    <QuerySet [<WorldBorder: United States>]>\n\n__ https://spatialreference.org/ref/epsg/32140/\n\n.. _gis-raw-sql:\n\n.. admonition:: Raw queries\n\n    When using :doc:`raw queries </topics/db/sql>`, you must wrap your geometry\n    fields so that the field value can be recognized by GEOS::\n\n        from django.db import connection\n        # or if you're querying a non-default database:\n        from django.db import connections\n        connection = connections['your_gis_db_alias']\n\n        City.objects.raw('SELECT id, name, %s as point from myapp_city' % (connection.ops.select % 'point'))\n\n    You should only use raw queries when you know exactly what you're doing.\n\nLazy Geometries\n---------------\nGeoDjango loads geometries in a standardized textual representation.  When the\ngeometry field is first accessed, GeoDjango creates a\n:class:`~django.contrib.gis.geos.GEOSGeometry` object, exposing powerful\nfunctionality, such as serialization properties for popular geospatial\nformats::\n\n    >>> sm = WorldBorder.objects.get(name='San Marino')\n    >>> sm.mpoly\n    <MultiPolygon object at 0x24c6798>\n    >>> sm.mpoly.wkt # WKT\n    MULTIPOLYGON (((12.4157980000000006 43.9579540000000009, 12.4505540000000003 43.9797209999999978, ...\n    >>> sm.mpoly.wkb # WKB (as Python binary buffer)\n    <read-only buffer for 0x1fe2c70, size -1, offset 0 at 0x2564c40>\n    >>> sm.mpoly.geojson # GeoJSON\n    '{ \"type\": \"MultiPolygon\", \"coordinates\": [ [ [ [ 12.415798, 43.957954 ], [ 12.450554, 43.979721 ], ...\n\nThis includes access to all of the advanced geometric operations provided by\nthe GEOS library::\n\n    >>> pnt = Point(12.4604, 43.9420)\n    >>> sm.mpoly.contains(pnt)\n    True\n    >>> pnt.contains(sm.mpoly)\n    False\n\nGeographic annotations\n----------------------\n\nGeoDjango also offers a set of geographic annotations to compute distances and\nseveral other operations (intersection, difference, etc.). See the\n:doc:`functions` documentation.\n\n\nPutting your data on the map\n============================\n\nGeographic Admin\n----------------\n\nGeoDjango extends :doc:`Django's admin application </ref/contrib/admin/index>`\nwith support for editing geometry fields.\n\nBasics\n~~~~~~\n\nGeoDjango also supplements the Django admin by allowing users to create\nand modify geometries on a JavaScript slippy map (powered by `OpenLayers`_).\n\nLet's dive right in.  Create a file called ``admin.py`` inside the\n``world`` application with the following code::\n\n    from django.contrib.gis import admin\n    from .models import WorldBorder\n\n    admin.site.register(WorldBorder, admin.GeoModelAdmin)\n\nNext, edit your ``urls.py`` in the ``geodjango`` application folder as follows::\n\n    from django.contrib.gis import admin\n    from django.urls import include, path\n\n    urlpatterns = [\n        path('admin/', admin.site.urls),\n    ]\n\nCreate an admin user:\n\n.. console::\n\n    $ python manage.py createsuperuser\n\nNext, start up the Django development server:\n\n.. console::\n\n    $ python manage.py runserver\n\nFinally, browse to ``http://localhost:8000/admin/``, and log in with the user\nyou just created. Browse to any of the ``WorldBorder`` entries -- the borders\nmay be edited by clicking on a polygon and dragging the vertices to the desired\nposition.\n\n.. _OpenLayers: https://openlayers.org/\n.. _Open Street Map: https://www.openstreetmap.org/\n.. _Vector Map Level 0: https://earth-info.nga.mil/publications/vmap0.html\n.. _OSGeo: https://www.osgeo.org/\n\n.. _osmgeoadmin-intro:\n\n``OSMGeoAdmin``\n~~~~~~~~~~~~~~~\n\nWith the :class:`~django.contrib.gis.admin.OSMGeoAdmin`, GeoDjango uses\na `Open Street Map`_ layer in the admin.\nThis provides more context (including street and thoroughfare details) than\navailable with the :class:`~django.contrib.gis.admin.GeoModelAdmin`\n(which uses the `Vector Map Level 0`_ WMS dataset hosted at `OSGeo`_).\n\nThe PROJ datum shifting files must be installed (see the :ref:`PROJ\ninstallation instructions <proj4>` for more details).\n\nIf you meet this requirement, then substitute the ``OSMGeoAdmin`` option class\nin your ``admin.py`` file::\n\n    admin.site.register(WorldBorder, admin.OSMGeoAdmin)\n\n.. rubric:: Footnotes\n\n.. [#] Special thanks to Bjørn Sandvik of `thematicmapping.org\n       <https://thematicmapping.org/>`_ for providing and maintaining this\n       dataset.\n.. [#] GeoDjango basic apps was written by Dane Springmeyer, Josh Livni, and\n       Christopher Schmidt.\n.. [#] This point is the `University of Houston Law Center\n       <https://www.law.uh.edu/>`_.\n.. [#] Open Geospatial Consortium, Inc., `OpenGIS Simple Feature Specification\n       For SQL <https://www.opengeospatial.org/standards/sfs>`_.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":130,"nodeType":"Package","repoName":null,"name":"docs/ref/contrib/gis/install","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":131,"nodeType":"TextFile","repoName":null,"name":"spatialite.txt","path":"docs/ref/contrib/gis/install","text":"=====================\nInstalling SpatiaLite\n=====================\n\n`SpatiaLite`__ adds spatial support to SQLite, turning it into a full-featured\nspatial database.\n\nFirst, check if you can install SpatiaLite from system packages or binaries.\n\nFor example, on Debian-based distributions that package SpatiaLite 4.2+, try to\ninstall the ``libsqlite3-mod-spatialite`` package. For older releases install\n``spatialite-bin``.\n\nFor macOS, follow the :ref:`instructions below<spatialite_macos>`.\n\nFor Windows, you may find binaries on the `Gaia-SINS`__ home page.\n\nIn any case, you should always be able to :ref:`install from source\n<spatialite_source>`.\n\n__ https://www.gaia-gis.it/fossil/libspatialite\n__ https://www.gaia-gis.it/gaia-sins/\n\n.. _spatialite_source:\n\nInstalling from source\n======================\n\n:doc:`GEOS and PROJ</ref/contrib/gis/install/geolibs>` should be installed\nprior to building SpatiaLite.\n\nSQLite\n------\n\nCheck first if SQLite is compiled with the `R*Tree module`__. Run the sqlite3\ncommand line interface and enter the following query::\n\n    sqlite> CREATE VIRTUAL TABLE testrtree USING rtree(id,minX,maxX,minY,maxY);\n\nIf you obtain an error, you will have to recompile SQLite from source. Otherwise,\nskip this section.\n\nTo install from sources, download the latest amalgamation source archive from\nthe `SQLite download page`__, and extract::\n\n    $ wget https://www.sqlite.org/YYYY/sqlite-amalgamation-XXX0000.zip\n    $ unzip sqlite-amalgamation-XXX0000.zip\n    $ cd sqlite-amalgamation-XXX0000\n\nNext, run the ``configure`` script -- however the ``CFLAGS`` environment variable\nneeds to be customized so that SQLite knows to build the R*Tree module::\n\n    $ CFLAGS=\"-DSQLITE_ENABLE_RTREE=1\" ./configure\n    $ make\n    $ sudo make install\n    $ cd ..\n\n__ https://www.sqlite.org/rtree.html\n__ https://www.sqlite.org/download.html\n\n.. _spatialitebuild:\n\nSpatiaLite library (``libspatialite``)\n--------------------------------------\n\nGet the latest SpatiaLite library source bundle from the\n`download page`__::\n\n    $ wget https://www.gaia-gis.it/gaia-sins/libspatialite-sources/libspatialite-X.Y.Z.tar.gz\n    $ tar xaf libspatialite-X.Y.Z.tar.gz\n    $ cd libspatialite-X.Y.Z\n    $ ./configure\n    $ make\n    $ sudo make install\n\n.. note::\n\n    For macOS users building from source, the SpatiaLite library *and* tools\n    need to have their ``target`` configured::\n\n        $ ./configure --target=macosx\n\n__ https://www.gaia-gis.it/gaia-sins/libspatialite-sources/\n\n.. _spatialite_macos:\n\nmacOS-specific instructions\n==============================\n\nTo install the SpatiaLite library and tools, macOS users can choose between\n:ref:`kyngchaos` and `Homebrew`_.\n\nKyngChaos\n---------\n\nFirst, follow the instructions in the :ref:`kyngchaos` section.\n\nWhen creating a SpatiaLite database, the ``spatialite`` program is required.\nHowever, instead of attempting to compile the SpatiaLite tools from source,\ndownload the `SpatiaLite Tools`__ package for macOS, and install ``spatialite``\nin a location available in your ``PATH``.  For example::\n\n    $ curl -O https://www.kyngchaos.com/files/software/frameworks/Spatialite_Tools-4.3.zip\n    $ unzip Spatialite_Tools-4.3.zip\n    $ cd Spatialite\\ Tools/tools\n    $ sudo cp spatialite /Library/Frameworks/SQLite3.framework/Programs\n\nFinally, for GeoDjango to be able to find the KyngChaos SpatiaLite library,\nadd the following to your ``settings.py``::\n\n    SPATIALITE_LIBRARY_PATH='/Library/Frameworks/SQLite3.framework/SQLite3'\n\n__ https://www.kyngchaos.com/software/frameworks/\n\nHomebrew\n--------\n\n`Homebrew`_ handles all the SpatiaLite related packages on your behalf,\nincluding SQLite, SpatiaLite, PROJ, and GEOS. Install them like this::\n\n    $ brew update\n    $ brew install spatialite-tools\n    $ brew install gdal\n\nFinally, for GeoDjango to be able to find the SpatiaLite library, add the\nfollowing to your ``settings.py``::\n\n    SPATIALITE_LIBRARY_PATH='/usr/local/lib/mod_spatialite.dylib'\n\n.. _Homebrew: https://brew.sh/\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":132,"nodeType":"Package","repoName":null,"name":"docs/ref/contrib/postgres","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":133,"nodeType":"TextFile","repoName":null,"name":"constraints.txt","path":"docs/ref/contrib/postgres","text":"========================================\nPostgreSQL specific database constraints\n========================================\n\n.. module:: django.contrib.postgres.constraints\n   :synopsis: PostgreSQL specific database constraint\n\nPostgreSQL supports additional data integrity constraints available from the\n``django.contrib.postgres.constraints`` module. They are added in the model\n:attr:`Meta.constraints <django.db.models.Options.constraints>` option.\n\n``ExclusionConstraint``\n=======================\n\n.. class:: ExclusionConstraint(*, name, expressions, index_type=None, condition=None, deferrable=None)\n\n    Creates an exclusion constraint in the database. Internally, PostgreSQL\n    implements exclusion constraints using indexes. The default index type is\n    `GiST <https://www.postgresql.org/docs/current/gist.html>`_. To use them,\n    you need to activate the `btree_gist extension\n    <https://www.postgresql.org/docs/current/btree-gist.html>`_ on PostgreSQL.\n    You can install it using the\n    :class:`~django.contrib.postgres.operations.BtreeGistExtension` migration\n    operation.\n\n    If you attempt to insert a new row that conflicts with an existing row, an\n    :exc:`~django.db.IntegrityError` is raised. Similarly, when update\n    conflicts with an existing row.\n\n``name``\n--------\n\n.. attribute:: ExclusionConstraint.name\n\nThe name of the constraint.\n\n``expressions``\n---------------\n\n.. attribute:: ExclusionConstraint.expressions\n\nAn iterable of 2-tuples. The first element is an expression or string. The\nsecond element is an SQL operator represented as a string. To avoid typos, you\nmay use :class:`~django.contrib.postgres.fields.RangeOperators` which maps the\noperators with strings. For example::\n\n    expressions=[\n        ('timespan', RangeOperators.ADJACENT_TO),\n        (F('room'), RangeOperators.EQUAL),\n    ]\n\n.. admonition:: Restrictions on operators.\n\n    Only commutative operators can be used in exclusion constraints.\n\n``index_type``\n--------------\n\n.. attribute:: ExclusionConstraint.index_type\n\nThe index type of the constraint. Accepted values are ``GIST`` or ``SPGIST``.\nMatching is case insensitive. If not provided, the default index type is\n``GIST``.\n\n``condition``\n-------------\n\n.. attribute:: ExclusionConstraint.condition\n\nA :class:`~django.db.models.Q` object that specifies the condition to restrict\na constraint to a subset of rows. For example,\n``condition=Q(cancelled=False)``.\n\nThese conditions have the same database restrictions as\n:attr:`django.db.models.Index.condition`.\n\n``deferrable``\n--------------\n\n.. attribute:: ExclusionConstraint.deferrable\n\n.. versionadded:: 3.1\n\nSet this parameter to create a deferrable exclusion constraint. Accepted values\nare ``Deferrable.DEFERRED`` or ``Deferrable.IMMEDIATE``. For example::\n\n    from django.contrib.postgres.constraints import ExclusionConstraint\n    from django.contrib.postgres.fields import RangeOperators\n    from django.db.models import Deferrable\n\n\n    ExclusionConstraint(\n        name='exclude_overlapping_deferred',\n        expressions=[\n            ('timespan', RangeOperators.OVERLAPS),\n        ],\n        deferrable=Deferrable.DEFERRED,\n    )\n\nBy default constraints are not deferred. A deferred constraint will not be\nenforced until the end of the transaction. An immediate constraint will be\nenforced immediately after every command.\n\n.. warning::\n\n    Deferred exclusion constraints may lead to a `performance penalty\n    <https://www.postgresql.org/docs/current/sql-createtable.html#id-1.9.3.85.9.4>`_.\n\nExamples\n--------\n\nThe following example restricts overlapping reservations in the same room, not\ntaking canceled reservations into account::\n\n    from django.contrib.postgres.constraints import ExclusionConstraint\n    from django.contrib.postgres.fields import DateTimeRangeField, RangeOperators\n    from django.db import models\n    from django.db.models import Q\n\n    class Room(models.Model):\n        number = models.IntegerField()\n\n\n    class Reservation(models.Model):\n        room = models.ForeignKey('Room', on_delete=models.CASCADE)\n        timespan = DateTimeRangeField()\n        cancelled = models.BooleanField(default=False)\n\n        class Meta:\n            constraints = [\n                ExclusionConstraint(\n                    name='exclude_overlapping_reservations',\n                    expressions=[\n                        ('timespan', RangeOperators.OVERLAPS),\n                        ('room', RangeOperators.EQUAL),\n                    ],\n                    condition=Q(cancelled=False),\n                ),\n            ]\n\nIn case your model defines a range using two fields, instead of the native\nPostgreSQL range types, you should write an expression that uses the equivalent\nfunction (e.g. ``TsTzRange()``), and use the delimiters for the field. Most\noften, the delimiters will be ``'[)'``, meaning that the lower bound is\ninclusive and the upper bound is exclusive. You may use the\n:class:`~django.contrib.postgres.fields.RangeBoundary` that provides an\nexpression mapping for the `range boundaries <https://www.postgresql.org/docs/\ncurrent/rangetypes.html#RANGETYPES-INCLUSIVITY>`_. For example::\n\n    from django.contrib.postgres.constraints import ExclusionConstraint\n    from django.contrib.postgres.fields import (\n        DateTimeRangeField,\n        RangeBoundary,\n        RangeOperators,\n    )\n    from django.db import models\n    from django.db.models import Func, Q\n\n\n    class TsTzRange(Func):\n        function = 'TSTZRANGE'\n        output_field = DateTimeRangeField()\n\n\n    class Reservation(models.Model):\n        room = models.ForeignKey('Room', on_delete=models.CASCADE)\n        start = models.DateTimeField()\n        end = models.DateTimeField()\n        cancelled = models.BooleanField(default=False)\n\n        class Meta:\n            constraints = [\n                ExclusionConstraint(\n                    name='exclude_overlapping_reservations',\n                    expressions=(\n                        (TsTzRange('start', 'end', RangeBoundary()), RangeOperators.OVERLAPS),\n                        ('room', RangeOperators.EQUAL),\n                    ),\n                    condition=Q(cancelled=False),\n                ),\n            ]\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":134,"nodeType":"Package","repoName":null,"name":"docs/ref/contrib/admin","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":135,"nodeType":"TextFile","repoName":null,"name":"admindocs.txt","path":"docs/ref/contrib/admin","text":"========================================\nThe Django admin documentation generator\n========================================\n\n.. module:: django.contrib.admindocs\n    :synopsis: Django's admin documentation generator.\n\n.. currentmodule:: django.contrib.admindocs\n\nDjango's :mod:`~django.contrib.admindocs` app pulls documentation from the\ndocstrings of models, views, template tags, and template filters for any app in\n:setting:`INSTALLED_APPS` and makes that documentation available from the\n:mod:`Django admin <django.contrib.admin>`.\n\nOverview\n========\n\nTo activate the :mod:`~django.contrib.admindocs`, you will need to do\nthe following:\n\n* Add :mod:`django.contrib.admindocs` to your :setting:`INSTALLED_APPS`.\n* Add ``path('admin/doc/', include('django.contrib.admindocs.urls'))`` to\n  your ``urlpatterns``. Make sure it's included *before* the\n  ``'admin/'`` entry, so that requests to ``/admin/doc/`` don't get\n  handled by the latter entry.\n* Install the docutils Python module (https://docutils.sourceforge.io/).\n* **Optional:** Using the admindocs bookmarklets requires\n  ``django.contrib.admindocs.middleware.XViewMiddleware`` to be installed.\n\nOnce those steps are complete, you can start browsing the documentation by\ngoing to your admin interface and clicking the \"Documentation\" link in the\nupper right of the page.\n\nDocumentation helpers\n=====================\n\nThe following special markup can be used in your docstrings to easily create\nhyperlinks to other components:\n\n=================   =======================\nDjango Component    reStructuredText roles\n=================   =======================\nModels              ``:model:`app_label.ModelName```\nViews               ``:view:`app_label.view_name```\nTemplate tags       ``:tag:`tagname```\nTemplate filters    ``:filter:`filtername```\nTemplates           ``:template:`path/to/template.html```\n=================   =======================\n\nModel reference\n===============\n\nThe **models** section of the ``admindocs`` page describes each model in the\nsystem along with all the fields, properties, and methods available on it.\nRelationships to other models appear as hyperlinks. Descriptions are pulled\nfrom ``help_text`` attributes on fields or from docstrings on model methods.\n\nA model with useful documentation might look like this::\n\n    class BlogEntry(models.Model):\n        \"\"\"\n        Stores a single blog entry, related to :model:`blog.Blog` and\n        :model:`auth.User`.\n        \"\"\"\n        slug = models.SlugField(help_text=\"A short label, generally used in URLs.\")\n        author = models.ForeignKey(\n            User,\n            models.SET_NULL,\n            blank=True, null=True,\n        )\n        blog = models.ForeignKey(Blog, models.CASCADE)\n        ...\n\n        def publish(self):\n            \"\"\"Makes the blog entry live on the site.\"\"\"\n            ...\n\nView reference\n==============\n\nEach URL in your site has a separate entry in the ``admindocs`` page, and\nclicking on a given URL will show you the corresponding view. Helpful things\nyou can document in your view function docstrings include:\n\n* A short description of what the view does.\n* The **context**, or a list of variables available in the view's template.\n* The name of the template or templates that are used for that view.\n\nFor example::\n\n    from django.shortcuts import render\n\n    from myapp.models import MyModel\n\n    def my_view(request, slug):\n        \"\"\"\n        Display an individual :model:`myapp.MyModel`.\n\n        **Context**\n\n        ``mymodel``\n            An instance of :model:`myapp.MyModel`.\n\n        **Template:**\n\n        :template:`myapp/my_template.html`\n        \"\"\"\n        context = {'mymodel': MyModel.objects.get(slug=slug)}\n        return render(request, 'myapp/my_template.html', context)\n\nTemplate tags and filters reference\n===================================\n\nThe **tags** and **filters** ``admindocs`` sections describe all the tags and\nfilters that come with Django (in fact, the :ref:`built-in tag reference\n<ref-templates-builtins-tags>` and :ref:`built-in filter reference\n<ref-templates-builtins-filters>` documentation come directly from those\npages). Any tags or filters that you create or are added by a third-party app\nwill show up in these sections as well.\n\n\nTemplate reference\n==================\n\nWhile ``admindocs`` does not include a place to document templates by\nthemselves, if you use the ``:template:`path/to/template.html``` syntax in a\ndocstring the resulting page will verify the path of that template with\nDjango's :ref:`template loaders <template-loaders>`. This can be a handy way to\ncheck if the specified template exists and to show where on the filesystem that\ntemplate is stored.\n\n.. _admindocs-bookmarklets:\n\nIncluded Bookmarklets\n=====================\n\nOne bookmarklet is available from the ``admindocs`` page:\n\nDocumentation for this page\n    Jumps you from any page to the documentation for the view that generates\n    that page.\n\nUsing this bookmarklet requires that ``XViewMiddleware`` is installed and that\nyou are logged into the :mod:`Django admin <django.contrib.admin>` as a\n:class:`~django.contrib.auth.models.User` with\n:attr:`~django.contrib.auth.models.User.is_staff` set to ``True``.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":136,"nodeType":"TextFile","repoName":null,"name":"geos.txt","path":"docs/ref/contrib/gis","text":"========\nGEOS API\n========\n\n.. module:: django.contrib.gis.geos\n    :synopsis: GeoDjango's high-level interface to the GEOS library.\n\nBackground\n==========\n\nWhat is GEOS?\n-------------\n\n`GEOS`__ stands for **Geometry Engine - Open Source**,\nand is a C++ library, ported from the  `Java Topology Suite`__.  GEOS\nimplements the OpenGIS `Simple Features for SQL`__ spatial predicate functions\nand spatial operators. GEOS, now an OSGeo project, was initially developed and\nmaintained by `Refractions Research`__ of Victoria, Canada.\n\n__ https://trac.osgeo.org/geos/\n__ https://sourceforge.net/projects/jts-topo-suite/\n__ https://www.opengeospatial.org/standards/sfs\n__ http://www.refractions.net/\n\nFeatures\n--------\n\nGeoDjango implements a high-level Python wrapper for the GEOS library, its\nfeatures include:\n\n* A BSD-licensed interface to the GEOS geometry routines, implemented purely\n  in Python using ``ctypes``.\n* Loosely-coupled to GeoDjango.  For example, :class:`GEOSGeometry` objects\n  may be used outside of a Django project/application.  In other words,\n  no need to have :envvar:`DJANGO_SETTINGS_MODULE` set or use a database, etc.\n* Mutability: :class:`GEOSGeometry` objects may be modified.\n* Cross-platform and tested; compatible with Windows, Linux, Solaris, and\n  macOS platforms.\n\n.. _geos-tutorial:\n\nTutorial\n========\n\nThis section contains a brief introduction and tutorial to using\n:class:`GEOSGeometry` objects.\n\nCreating a Geometry\n-------------------\n\n:class:`GEOSGeometry` objects may be created in a few ways.  The first is\nto simply instantiate the object on some spatial input -- the following\nare examples of creating the same geometry from WKT, HEX, WKB, and GeoJSON::\n\n    >>> from django.contrib.gis.geos import GEOSGeometry\n    >>> pnt = GEOSGeometry('POINT(5 23)') # WKT\n    >>> pnt = GEOSGeometry('010100000000000000000014400000000000003740') # HEX\n    >>> pnt = GEOSGeometry(buffer('\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x14@\\x00\\x00\\x00\\x00\\x00\\x007@'))\n    >>> pnt = GEOSGeometry('{ \"type\": \"Point\", \"coordinates\": [ 5.000000, 23.000000 ] }') # GeoJSON\n\nAnother option is to use the constructor for the specific geometry type\nthat you wish to create.  For example, a :class:`Point` object may be\ncreated by passing in the X and Y coordinates into its constructor::\n\n    >>> from django.contrib.gis.geos import Point\n    >>> pnt = Point(5, 23)\n\nAll these constructors take the keyword argument ``srid``. For example::\n\n    >>> from django.contrib.gis.geos import GEOSGeometry, LineString, Point\n    >>> print(GEOSGeometry('POINT (0 0)', srid=4326))\n    SRID=4326;POINT (0 0)\n    >>> print(LineString((0, 0), (1, 1), srid=4326))\n    SRID=4326;LINESTRING (0 0, 1 1)\n    >>> print(Point(0, 0, srid=32140))\n    SRID=32140;POINT (0 0)\n\nFinally, there is the :func:`fromfile` factory method which returns a\n:class:`GEOSGeometry` object from a file::\n\n    >>> from django.contrib.gis.geos import fromfile\n    >>> pnt = fromfile('/path/to/pnt.wkt')\n    >>> pnt = fromfile(open('/path/to/pnt.wkt'))\n\n.. _geos-exceptions-in-logfile:\n\n.. admonition:: My logs are filled with GEOS-related errors\n\n    You find many ``TypeError`` or ``AttributeError`` exceptions filling your\n    Web server's log files. This generally means that you are creating GEOS\n    objects at the top level of some of your Python modules. Then, due to a race\n    condition in the garbage collector, your module is garbage collected before\n    the GEOS object. To prevent this, create :class:`GEOSGeometry` objects\n    inside the local scope of your functions/methods.\n\nGeometries are Pythonic\n-----------------------\n:class:`GEOSGeometry` objects are 'Pythonic', in other words components may\nbe accessed, modified, and iterated over using standard Python conventions.\nFor example, you can iterate over the coordinates in a :class:`Point`::\n\n    >>> pnt = Point(5, 23)\n    >>> [coord for coord in pnt]\n    [5.0, 23.0]\n\nWith any geometry object, the :attr:`GEOSGeometry.coords` property\nmay be used to get the geometry coordinates as a Python tuple::\n\n    >>> pnt.coords\n    (5.0, 23.0)\n\nYou can get/set geometry components using standard Python indexing\ntechniques.  However, what is returned depends on the geometry type\nof the object.  For example, indexing on a :class:`LineString`\nreturns a coordinate tuple::\n\n    >>> from django.contrib.gis.geos import LineString\n    >>> line = LineString((0, 0), (0, 50), (50, 50), (50, 0), (0, 0))\n    >>> line[0]\n    (0.0, 0.0)\n    >>> line[-2]\n    (50.0, 0.0)\n\nWhereas indexing on a :class:`Polygon` will return the ring\n(a :class:`LinearRing` object) corresponding to the index::\n\n    >>> from django.contrib.gis.geos import Polygon\n    >>> poly = Polygon( ((0.0, 0.0), (0.0, 50.0), (50.0, 50.0), (50.0, 0.0), (0.0, 0.0)) )\n    >>> poly[0]\n    <LinearRing object at 0x1044395b0>\n    >>> poly[0][-2] # second-to-last coordinate of external ring\n    (50.0, 0.0)\n\nIn addition, coordinates/components of the geometry may added or modified,\njust like a Python list::\n\n    >>> line[0] = (1.0, 1.0)\n    >>> line.pop()\n    (0.0, 0.0)\n    >>> line.append((1.0, 1.0))\n    >>> line.coords\n    ((1.0, 1.0), (0.0, 50.0), (50.0, 50.0), (50.0, 0.0), (1.0, 1.0))\n\nGeometries support set-like operators::\n\n    >>> from django.contrib.gis.geos import LineString\n    >>> ls1 = LineString((0, 0), (2, 2))\n    >>> ls2 = LineString((1, 1), (3, 3))\n    >>> print(ls1 | ls2)  # equivalent to `ls1.union(ls2)`\n    MULTILINESTRING ((0 0, 1 1), (1 1, 2 2), (2 2, 3 3))\n    >>> print(ls1 & ls2)  # equivalent to `ls1.intersection(ls2)`\n    LINESTRING (1 1, 2 2)\n    >>> print(ls1 - ls2)  # equivalent to `ls1.difference(ls2)`\n    LINESTRING(0 0, 1 1)\n    >>> print(ls1 ^ ls2)  # equivalent to `ls1.sym_difference(ls2)`\n    MULTILINESTRING ((0 0, 1 1), (2 2, 3 3))\n\n.. admonition:: Equality operator doesn't check spatial equality\n\n    The :class:`~GEOSGeometry` equality operator uses\n    :meth:`~GEOSGeometry.equals_exact`, not :meth:`~GEOSGeometry.equals`, i.e.\n    it requires the compared geometries to have the same coordinates in the\n    same positions with the same SRIDs::\n\n        >>> from django.contrib.gis.geos import LineString\n        >>> ls1 = LineString((0, 0), (1, 1))\n        >>> ls2 = LineString((1, 1), (0, 0))\n        >>> ls3 = LineString((1, 1), (0, 0), srid=4326)\n        >>> ls1.equals(ls2)\n        True\n        >>> ls1 == ls2\n        False\n        >>> ls3 == ls2  # different SRIDs\n        False\n\nGeometry Objects\n================\n\n``GEOSGeometry``\n----------------\n\n.. class:: GEOSGeometry(geo_input, srid=None)\n\n    :param geo_input: Geometry input value (string or buffer)\n    :param srid: spatial reference identifier\n    :type srid: int\n\nThis is the base class for all GEOS geometry objects.  It initializes on the\ngiven ``geo_input`` argument, and then assumes the proper geometry subclass\n(e.g., ``GEOSGeometry('POINT(1 1)')`` will create a :class:`Point` object).\n\nThe ``srid`` parameter, if given, is set as the SRID of the created geometry if\n``geo_input`` doesn't have an SRID. If different SRIDs are provided through the\n``geo_input`` and ``srid`` parameters, ``ValueError`` is raised::\n\n    >>> from django.contrib.gis.geos import GEOSGeometry\n    >>> GEOSGeometry('POINT EMPTY', srid=4326).ewkt\n    'SRID=4326;POINT EMPTY'\n    >>> GEOSGeometry('SRID=4326;POINT EMPTY', srid=4326).ewkt\n    'SRID=4326;POINT EMPTY'\n    >>> GEOSGeometry('SRID=1;POINT EMPTY', srid=4326)\n    Traceback (most recent call last):\n    ...\n    ValueError: Input geometry already has SRID: 1.\n\nThe following input formats, along with their corresponding Python types,\nare accepted:\n\n=======================  ==========\nFormat                   Input Type\n=======================  ==========\nWKT / EWKT               ``str``\nHEX / HEXEWKB            ``str``\nWKB / EWKB               ``buffer``\n:rfc:`GeoJSON <7946>`    ``str``\n=======================  ==========\n\nFor the GeoJSON format, the SRID is set based on the ``crs`` member. If ``crs``\nisn't provided, the SRID defaults to 4326.\n\n.. classmethod:: GEOSGeometry.from_gml(gml_string)\n\n    Constructs a :class:`GEOSGeometry` from the given GML string.\n\nProperties\n~~~~~~~~~~\n\n.. attribute:: GEOSGeometry.coords\n\n    Returns the coordinates of the geometry as a tuple.\n\n.. attribute:: GEOSGeometry.dims\n\n    Returns the dimension of the geometry:\n\n    * ``0`` for :class:`Point`\\s and :class:`MultiPoint`\\s\n    * ``1`` for :class:`LineString`\\s and :class:`MultiLineString`\\s\n    * ``2`` for :class:`Polygon`\\s and :class:`MultiPolygon`\\s\n    * ``-1`` for empty :class:`GeometryCollection`\\s\n    * the maximum dimension of its elements for non-empty\n      :class:`GeometryCollection`\\s\n\n.. attribute:: GEOSGeometry.empty\n\n    Returns whether or not the set of points in the geometry is empty.\n\n.. attribute:: GEOSGeometry.geom_type\n\n    Returns a string corresponding to the type of geometry.  For example::\n\n        >>> pnt = GEOSGeometry('POINT(5 23)')\n        >>> pnt.geom_type\n        'Point'\n\n.. attribute:: GEOSGeometry.geom_typeid\n\n    Returns the GEOS geometry type identification number.  The following table\n    shows the value for each geometry type:\n\n    ===========================  ========\n    Geometry                     ID\n    ===========================  ========\n    :class:`Point`               0\n    :class:`LineString`          1\n    :class:`LinearRing`          2\n    :class:`Polygon`             3\n    :class:`MultiPoint`          4\n    :class:`MultiLineString`     5\n    :class:`MultiPolygon`        6\n    :class:`GeometryCollection`  7\n    ===========================  ========\n\n.. attribute:: GEOSGeometry.num_coords\n\n    Returns the number of coordinates in the geometry.\n\n.. attribute:: GEOSGeometry.num_geom\n\n    Returns the number of geometries in this geometry.  In other words, will\n    return 1 on anything but geometry collections.\n\n.. attribute:: GEOSGeometry.hasz\n\n    Returns a boolean indicating whether the geometry is three-dimensional.\n\n.. attribute:: GEOSGeometry.ring\n\n    Returns a boolean indicating whether the geometry is a ``LinearRing``.\n\n.. attribute:: GEOSGeometry.simple\n\n    Returns a boolean indicating whether the geometry is 'simple'. A geometry\n    is simple if and only if it does not intersect itself (except at boundary\n    points).  For example, a :class:`LineString` object is not simple if it\n    intersects itself. Thus, :class:`LinearRing` and :class:`Polygon` objects\n    are always simple because they do cannot intersect themselves, by\n    definition.\n\n.. attribute:: GEOSGeometry.valid\n\n    Returns a boolean indicating whether the geometry is valid.\n\n.. attribute:: GEOSGeometry.valid_reason\n\n    Returns a string describing the reason why a geometry is invalid.\n\n.. attribute:: GEOSGeometry.srid\n\n    Property that may be used to retrieve or set the SRID associated with the\n    geometry.  For example::\n\n        >>> pnt = Point(5, 23)\n        >>> print(pnt.srid)\n        None\n        >>> pnt.srid = 4326\n        >>> pnt.srid\n        4326\n\nOutput Properties\n~~~~~~~~~~~~~~~~~\n\nThe properties in this section export the :class:`GEOSGeometry` object into\na different.  This output may be in the form of a string, buffer, or even\nanother object.\n\n.. attribute:: GEOSGeometry.ewkt\n\n    Returns the \"extended\" Well-Known Text of the geometry.  This representation\n    is specific to PostGIS and is a superset of the OGC WKT standard. [#fnogc]_\n    Essentially the SRID is prepended to the WKT representation, for example\n    ``SRID=4326;POINT(5 23)``.\n\n    .. note::\n\n        The output from this property does not include the 3dm, 3dz, and 4d\n        information that PostGIS supports in its EWKT representations.\n\n.. attribute:: GEOSGeometry.hex\n\n    Returns the WKB of this Geometry in hexadecimal form.  Please note\n    that the SRID value is not included in this representation\n    because it is not a part of the OGC specification (use the\n    :attr:`GEOSGeometry.hexewkb` property instead).\n\n.. attribute:: GEOSGeometry.hexewkb\n\n    Returns the EWKB of this Geometry in hexadecimal form.  This is an\n    extension of the WKB specification that includes the SRID value\n    that are a part of this geometry.\n\n.. attribute:: GEOSGeometry.json\n\n    Returns the GeoJSON representation of the geometry. Note that the result is\n    not a complete GeoJSON structure but only the ``geometry`` key content of a\n    GeoJSON structure. See also :doc:`/ref/contrib/gis/serializers`.\n\n.. attribute:: GEOSGeometry.geojson\n\n    Alias for :attr:`GEOSGeometry.json`.\n\n.. attribute:: GEOSGeometry.kml\n\n    Returns a `KML`__ (Keyhole Markup Language) representation of the\n    geometry.  This should only be used for geometries with an SRID of\n    4326 (WGS84), but this restriction is not enforced.\n\n.. attribute:: GEOSGeometry.ogr\n\n    Returns an :class:`~django.contrib.gis.gdal.OGRGeometry` object\n    corresponding to the GEOS geometry.\n\n.. _wkb:\n\n.. attribute:: GEOSGeometry.wkb\n\n    Returns the WKB (Well-Known Binary) representation of this Geometry\n    as a Python buffer.  SRID value is not included, use the\n    :attr:`GEOSGeometry.ewkb` property instead.\n\n.. _ewkb:\n\n.. attribute:: GEOSGeometry.ewkb\n\n    Return the EWKB representation of this Geometry as a Python buffer.\n    This is an extension of the WKB specification that includes any SRID\n    value that are a part of this geometry.\n\n.. attribute:: GEOSGeometry.wkt\n\n    Returns the Well-Known Text of the geometry (an OGC standard).\n\n__ https://developers.google.com/kml/documentation/\n\nSpatial Predicate Methods\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\nAll of the following spatial predicate methods take another\n:class:`GEOSGeometry` instance (``other``) as a parameter, and\nreturn a boolean.\n\n.. method:: GEOSGeometry.contains(other)\n\n    Returns ``True`` if :meth:`other.within(this) <GEOSGeometry.within>` returns\n    ``True``.\n\n.. method:: GEOSGeometry.covers(other)\n\n    Returns ``True`` if this geometry covers the specified geometry.\n\n    The ``covers`` predicate has the following equivalent definitions:\n\n    * Every point of the other geometry is a point of this geometry.\n    * The DE-9IM Intersection Matrix for the two geometries is\n      ``T*****FF*``, ``*T****FF*``, ``***T**FF*``, or ``****T*FF*``.\n\n    If either geometry is empty, returns ``False``.\n\n    This predicate is similar to :meth:`GEOSGeometry.contains`, but is more\n    inclusive (i.e. returns ``True`` for more cases). In particular, unlike\n    :meth:`~GEOSGeometry.contains` it does not distinguish between points in the\n    boundary and in the interior of geometries. For most situations,\n    ``covers()`` should be preferred to :meth:`~GEOSGeometry.contains`. As an\n    added benefit, ``covers()`` is more amenable to optimization and hence\n    should outperform :meth:`~GEOSGeometry.contains`.\n\n.. method:: GEOSGeometry.crosses(other)\n\n    Returns ``True`` if the DE-9IM intersection matrix for the two Geometries\n    is ``T*T******`` (for a point and a curve,a point and an area or a line\n    and an area) ``0********`` (for two curves).\n\n.. method:: GEOSGeometry.disjoint(other)\n\n    Returns ``True`` if the DE-9IM intersection matrix for the two geometries\n    is ``FF*FF****``.\n\n.. method:: GEOSGeometry.equals(other)\n\n    Returns ``True`` if the DE-9IM intersection matrix for the two geometries\n    is ``T*F**FFF*``.\n\n.. method:: GEOSGeometry.equals_exact(other, tolerance=0)\n\n    Returns true if the two geometries are exactly equal, up to a\n    specified tolerance.  The ``tolerance`` value should be a floating\n    point number representing the error tolerance in the comparison, e.g.,\n    ``poly1.equals_exact(poly2, 0.001)`` will compare equality to within\n    one thousandth of a unit.\n\n.. method:: GEOSGeometry.intersects(other)\n\n    Returns ``True`` if :meth:`GEOSGeometry.disjoint` is ``False``.\n\n.. method:: GEOSGeometry.overlaps(other)\n\n    Returns true if the DE-9IM intersection matrix for the two geometries\n    is ``T*T***T**`` (for two points or two surfaces) ``1*T***T**``\n    (for two curves).\n\n.. method:: GEOSGeometry.relate_pattern(other, pattern)\n\n    Returns ``True`` if the elements in the DE-9IM intersection matrix\n    for this geometry and the other matches the given ``pattern`` --\n    a string of nine characters from the alphabet: {``T``, ``F``, ``*``, ``0``}.\n\n.. method:: GEOSGeometry.touches(other)\n\n    Returns ``True`` if the DE-9IM intersection matrix for the two geometries\n    is ``FT*******``, ``F**T*****`` or ``F***T****``.\n\n.. method:: GEOSGeometry.within(other)\n\n    Returns ``True`` if the DE-9IM intersection matrix for the two geometries\n    is ``T*F**F***``.\n\nTopological Methods\n~~~~~~~~~~~~~~~~~~~\n\n.. method:: GEOSGeometry.buffer(width, quadsegs=8)\n\n    Returns a :class:`GEOSGeometry` that represents all points whose distance\n    from this geometry is less than or equal to the given ``width``. The\n    optional ``quadsegs`` keyword sets the number of segments used to\n    approximate a quarter circle (defaults is 8).\n\n.. method:: GEOSGeometry.buffer_with_style(width, quadsegs=8, end_cap_style=1, join_style=1, mitre_limit=5.0)\n\n    Same as :meth:`buffer`, but allows customizing the style of the buffer.\n\n    * ``end_cap_style`` can be round (``1``), flat (``2``), or square (``3``).\n    * ``join_style`` can be round (``1``), mitre (``2``), or bevel (``3``).\n    * Mitre ratio limit (``mitre_limit``) only affects mitered join style.\n\n.. method:: GEOSGeometry.difference(other)\n\n    Returns a :class:`GEOSGeometry` representing the points making up this\n    geometry that do not make up other.\n\n.. method:: GEOSGeometry.interpolate(distance)\n.. method:: GEOSGeometry.interpolate_normalized(distance)\n\n    Given a distance (float), returns the point (or closest point) within the\n    geometry (:class:`LineString` or :class:`MultiLineString`) at that distance.\n    The normalized version takes the distance as a float between 0 (origin) and\n    1 (endpoint).\n\n    Reverse of :meth:`GEOSGeometry.project`.\n\n.. method:: GEOSGeometry.intersection(other)\n\n    Returns a :class:`GEOSGeometry` representing the points shared by this\n    geometry and other.\n\n.. method:: GEOSGeometry.project(point)\n.. method:: GEOSGeometry.project_normalized(point)\n\n    Returns the distance (float) from the origin of the geometry\n    (:class:`LineString` or :class:`MultiLineString`) to the point projected on\n    the geometry (that is to a point of the line the closest to the given\n    point). The normalized version returns the distance as a float between 0\n    (origin) and 1 (endpoint).\n\n    Reverse of :meth:`GEOSGeometry.interpolate`.\n\n.. method:: GEOSGeometry.relate(other)\n\n    Returns the DE-9IM intersection matrix (a string) representing the\n    topological relationship between this geometry and the other.\n\n.. method:: GEOSGeometry.simplify(tolerance=0.0, preserve_topology=False)\n\n    Returns a new :class:`GEOSGeometry`, simplified to the specified tolerance\n    using the Douglas-Peucker algorithm. A higher tolerance value implies\n    fewer points in the output. If no tolerance is provided, it defaults to 0.\n\n    By default, this function does not preserve topology. For example,\n    :class:`Polygon` objects can be split, be collapsed into lines, or\n    disappear. :class:`Polygon` holes can be created or disappear, and lines may\n    cross. By specifying ``preserve_topology=True``, the result will have the\n    same dimension and number of components as the input; this is significantly\n    slower, however.\n\n.. method:: GEOSGeometry.sym_difference(other)\n\n    Returns a :class:`GEOSGeometry` combining the points in this geometry\n    not in other, and the points in other not in this geometry.\n\n.. method:: GEOSGeometry.union(other)\n\n    Returns a :class:`GEOSGeometry` representing all the points in this\n    geometry and the other.\n\nTopological Properties\n~~~~~~~~~~~~~~~~~~~~~~\n\n.. attribute:: GEOSGeometry.boundary\n\n    Returns the boundary as a newly allocated Geometry object.\n\n.. attribute:: GEOSGeometry.centroid\n\n    Returns a :class:`Point` object representing the geometric center of\n    the geometry.  The point is not guaranteed to be on the interior\n    of the geometry.\n\n.. attribute:: GEOSGeometry.convex_hull\n\n    Returns the smallest :class:`Polygon` that contains all the points in\n    the geometry.\n\n.. attribute:: GEOSGeometry.envelope\n\n    Returns a :class:`Polygon` that represents the bounding envelope of\n    this geometry. Note that it can also return a :class:`Point` if the input\n    geometry is a point.\n\n.. attribute:: GEOSGeometry.point_on_surface\n\n    Computes and returns a :class:`Point` guaranteed to be on the interior\n    of this geometry.\n\n.. attribute:: GEOSGeometry.unary_union\n\n    Computes the union of all the elements of this geometry.\n\n    The result obeys the following contract:\n\n    * Unioning a set of :class:`LineString`\\s has the effect of fully noding and\n      dissolving the linework.\n\n    * Unioning a set of :class:`Polygon`\\s will always return a :class:`Polygon`\n      or :class:`MultiPolygon` geometry (unlike :meth:`GEOSGeometry.union`,\n      which may return geometries of lower dimension if a topology collapse\n      occurs).\n\nOther Properties & Methods\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. attribute:: GEOSGeometry.area\n\n    This property returns the area of the Geometry.\n\n.. attribute:: GEOSGeometry.extent\n\n    This property returns the extent of this geometry as a 4-tuple,\n    consisting of ``(xmin, ymin, xmax, ymax)``.\n\n.. method:: GEOSGeometry.clone()\n\n    This method returns a :class:`GEOSGeometry` that is a clone of the original.\n\n.. method:: GEOSGeometry.distance(geom)\n\n    Returns the distance between the closest points on this geometry and the\n    given ``geom`` (another :class:`GEOSGeometry` object).\n\n    .. note::\n\n        GEOS distance calculations are  linear -- in other words, GEOS does not\n        perform a spherical calculation even if the SRID specifies a geographic\n        coordinate system.\n\n.. attribute:: GEOSGeometry.length\n\n    Returns the length of this geometry (e.g., 0 for a :class:`Point`,\n    the length of a :class:`LineString`, or the circumference of\n    a :class:`Polygon`).\n\n.. attribute:: GEOSGeometry.prepared\n\n    Returns a GEOS ``PreparedGeometry`` for the contents of this geometry.\n    ``PreparedGeometry`` objects are optimized for the contains, intersects,\n    covers, crosses, disjoint, overlaps, touches and within operations. Refer to\n    the :ref:`prepared-geometries` documentation for more information.\n\n.. attribute:: GEOSGeometry.srs\n\n    Returns a :class:`~django.contrib.gis.gdal.SpatialReference` object\n    corresponding to the SRID of the geometry or ``None``.\n\n.. method:: GEOSGeometry.transform(ct, clone=False)\n\n    Transforms the geometry according to the given coordinate transformation\n    parameter (``ct``), which may be an integer SRID, spatial reference WKT\n    string, a PROJ string, a :class:`~django.contrib.gis.gdal.SpatialReference`\n    object, or a :class:`~django.contrib.gis.gdal.CoordTransform` object. By\n    default, the geometry is transformed in-place and nothing is returned.\n    However if the ``clone`` keyword is set, then the geometry is not modified\n    and a transformed clone of the geometry is returned instead.\n\n    .. note::\n\n        Raises :class:`~django.contrib.gis.geos.GEOSException` if GDAL is not\n        available or if the geometry's SRID is ``None`` or less than 0. It\n        doesn't impose any constraints on the geometry's SRID if called with a\n        :class:`~django.contrib.gis.gdal.CoordTransform` object.\n\n.. method:: GEOSGeometry.normalize()\n\n    Converts this geometry to canonical form::\n\n        >>> g = MultiPoint(Point(0, 0), Point(2, 2), Point(1, 1))\n        >>> print(g)\n        MULTIPOINT (0 0, 2 2, 1 1)\n        >>> g.normalize()\n        >>> print(g)\n        MULTIPOINT (2 2, 1 1, 0 0)\n\n``Point``\n---------\n\n.. class:: Point(x=None, y=None, z=None, srid=None)\n\n    ``Point`` objects are instantiated using arguments that represent the\n    component coordinates of the point or with a single sequence coordinates.\n    For example, the following are equivalent::\n\n        >>> pnt = Point(5, 23)\n        >>> pnt = Point([5, 23])\n\n    Empty ``Point`` objects may be instantiated by passing no arguments or an\n    empty sequence. The following are equivalent::\n\n        >>> pnt = Point()\n        >>> pnt = Point([])\n\n``LineString``\n--------------\n\n.. class:: LineString(*args, **kwargs)\n\n    ``LineString`` objects are instantiated using arguments that are either a\n    sequence of coordinates or :class:`Point` objects. For example, the\n    following are equivalent::\n\n        >>> ls = LineString((0, 0), (1, 1))\n        >>> ls = LineString(Point(0, 0), Point(1, 1))\n\n    In addition, ``LineString`` objects may also be created by passing in a\n    single sequence of coordinate or :class:`Point` objects::\n\n        >>> ls = LineString( ((0, 0), (1, 1)) )\n        >>> ls = LineString( [Point(0, 0), Point(1, 1)] )\n\n    Empty ``LineString`` objects may be instantiated by passing no arguments\n    or an empty sequence. The following are equivalent::\n\n        >>> ls = LineString()\n        >>> ls = LineString([])\n\n    .. attribute:: closed\n\n        Returns whether or not this ``LineString`` is closed.\n\n``LinearRing``\n--------------\n\n.. class:: LinearRing(*args, **kwargs)\n\n    ``LinearRing`` objects are constructed in the exact same way as\n    :class:`LineString` objects, however the coordinates must be *closed*, in\n    other words, the first coordinates must be the same as the last\n    coordinates. For example::\n\n        >>> ls = LinearRing((0, 0), (0, 1), (1, 1), (0, 0))\n\n    Notice that ``(0, 0)`` is the first and last coordinate -- if they were not\n    equal, an error would be raised.\n\n    .. attribute:: is_counterclockwise\n\n        .. versionadded:: 3.1\n\n        Returns whether this ``LinearRing`` is counterclockwise.\n\n``Polygon``\n-----------\n\n.. class:: Polygon(*args, **kwargs)\n\n    ``Polygon`` objects may be instantiated by passing in parameters that\n    represent the rings of the polygon.  The parameters must either be\n    :class:`LinearRing` instances, or a sequence that may be used to construct a\n    :class:`LinearRing`::\n\n        >>> ext_coords = ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))\n        >>> int_coords = ((0.4, 0.4), (0.4, 0.6), (0.6, 0.6), (0.6, 0.4), (0.4, 0.4))\n        >>> poly = Polygon(ext_coords, int_coords)\n        >>> poly = Polygon(LinearRing(ext_coords), LinearRing(int_coords))\n\n    .. classmethod:: from_bbox(bbox)\n\n        Returns a polygon object from the given bounding-box, a 4-tuple\n        comprising ``(xmin, ymin, xmax, ymax)``.\n\n    .. attribute:: num_interior_rings\n\n        Returns the number of interior rings in this geometry.\n\n.. admonition:: Comparing Polygons\n\n    Note that it is possible to compare ``Polygon`` objects directly with ``<``\n    or ``>``, but as the comparison is made through Polygon's\n    :class:`LineString`, it does not mean much (but is consistent and quick).\n    You can always force the comparison with the :attr:`~GEOSGeometry.area`\n    property::\n\n        >>> if poly_1.area > poly_2.area:\n        >>>     pass\n\nGeometry Collections\n====================\n\n``MultiPoint``\n--------------\n\n.. class:: MultiPoint(*args, **kwargs)\n\n    ``MultiPoint`` objects may be instantiated by passing in :class:`Point`\n    objects as arguments, or a single sequence of :class:`Point` objects::\n\n        >>> mp = MultiPoint(Point(0, 0), Point(1, 1))\n        >>> mp = MultiPoint( (Point(0, 0), Point(1, 1)) )\n\n``MultiLineString``\n-------------------\n\n.. class:: MultiLineString(*args, **kwargs)\n\n    ``MultiLineString`` objects may be instantiated by passing in\n    :class:`LineString` objects as arguments, or a single sequence of\n    :class:`LineString` objects::\n\n        >>> ls1 = LineString((0, 0), (1, 1))\n        >>> ls2 = LineString((2, 2), (3, 3))\n        >>> mls = MultiLineString(ls1, ls2)\n        >>> mls = MultiLineString([ls1, ls2])\n\n    .. attribute:: merged\n\n        Returns a :class:`LineString` representing the line merge of\n        all the components in this ``MultiLineString``.\n\n    .. attribute:: closed\n\n        Returns ``True`` if and only if all elements are closed. Requires GEOS 3.5.\n\n``MultiPolygon``\n----------------\n\n.. class:: MultiPolygon(*args, **kwargs)\n\n    ``MultiPolygon`` objects may be instantiated by passing :class:`Polygon`\n    objects as arguments, or a single sequence of :class:`Polygon` objects::\n\n        >>> p1 = Polygon( ((0, 0), (0, 1), (1, 1), (0, 0)) )\n        >>> p2 = Polygon( ((1, 1), (1, 2), (2, 2), (1, 1)) )\n        >>> mp = MultiPolygon(p1, p2)\n        >>> mp = MultiPolygon([p1, p2])\n\n``GeometryCollection``\n----------------------\n\n.. class:: GeometryCollection(*args, **kwargs)\n\n    ``GeometryCollection`` objects may be instantiated by passing in other\n    :class:`GEOSGeometry` as arguments, or a single sequence of\n    :class:`GEOSGeometry` objects::\n\n        >>> poly = Polygon( ((0, 0), (0, 1), (1, 1), (0, 0)) )\n        >>> gc = GeometryCollection(Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly)\n        >>> gc = GeometryCollection((Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly))\n\n.. _prepared-geometries:\n\nPrepared Geometries\n===================\n\nIn order to obtain a prepared geometry, access the\n:attr:`GEOSGeometry.prepared` property.  Once you have a\n``PreparedGeometry`` instance its spatial predicate methods, listed below,\nmay be used with other ``GEOSGeometry`` objects.  An operation with a prepared\ngeometry can be orders of magnitude faster -- the more complex the geometry\nthat is prepared, the larger the speedup in the operation.  For more information,\nplease consult the `GEOS wiki page on prepared geometries <https://trac.osgeo.org/geos/wiki/PreparedGeometry>`_.\n\nFor example::\n\n    >>> from django.contrib.gis.geos import Point, Polygon\n    >>> poly = Polygon.from_bbox((0, 0, 5, 5))\n    >>> prep_poly = poly.prepared\n    >>> prep_poly.contains(Point(2.5, 2.5))\n    True\n\n``PreparedGeometry``\n--------------------\n\n.. class:: PreparedGeometry\n\n    All methods on ``PreparedGeometry`` take an ``other`` argument, which\n    must be a :class:`GEOSGeometry` instance.\n\n    .. method:: contains(other)\n\n    .. method:: contains_properly(other)\n\n    .. method:: covers(other)\n\n    .. method:: crosses(other)\n\n    .. method:: disjoint(other)\n\n    .. method:: intersects(other)\n\n    .. method:: overlaps(other)\n\n    .. method:: touches(other)\n\n    .. method:: within(other)\n\nGeometry Factories\n==================\n\n.. function:: fromfile(file_h)\n\n    :param file_h: input file that contains spatial data\n    :type file_h: a Python ``file`` object or a string path to the file\n    :rtype: a :class:`GEOSGeometry` corresponding to the spatial data in the file\n\n    Example::\n\n        >>> from django.contrib.gis.geos import fromfile\n        >>> g = fromfile('/home/bob/geom.wkt')\n\n.. function:: fromstr(string, srid=None)\n\n    :param string: string that contains spatial data\n    :type string: str\n    :param srid: spatial reference identifier\n    :type srid: int\n    :rtype: a :class:`GEOSGeometry` corresponding to the spatial data in the string\n\n    ``fromstr(string, srid)`` is equivalent to\n    :class:`GEOSGeometry(string, srid) <GEOSGeometry>`.\n\n    Example::\n\n        >>> from django.contrib.gis.geos import fromstr\n        >>> pnt = fromstr('POINT(-90.5 29.5)', srid=4326)\n\nI/O Objects\n===========\n\nReader Objects\n--------------\n\nThe reader I/O classes return a :class:`GEOSGeometry` instance from the WKB\nand/or WKT input given to their ``read(geom)`` method.\n\n.. class:: WKBReader\n\n    Example::\n\n        >>> from django.contrib.gis.geos import WKBReader\n        >>> wkb_r = WKBReader()\n        >>> wkb_r.read('0101000000000000000000F03F000000000000F03F')\n        <Point object at 0x103a88910>\n\n.. class:: WKTReader\n\n    Example::\n\n        >>> from django.contrib.gis.geos import WKTReader\n        >>> wkt_r = WKTReader()\n        >>> wkt_r.read('POINT(1 1)')\n        <Point object at 0x103a88b50>\n\nWriter Objects\n--------------\n\nAll writer objects have a ``write(geom)`` method that returns either the\nWKB or WKT of the given geometry.  In addition, :class:`WKBWriter` objects\nalso have properties that may be used to change the byte order, and or\ninclude the SRID value (in other words, EWKB).\n\n.. class:: WKBWriter(dim=2)\n\n    ``WKBWriter`` provides the most control over its output.  By default it\n    returns OGC-compliant WKB when its ``write`` method is called.  However,\n    it has properties that allow for the creation of EWKB, a superset of the\n    WKB standard that includes additional information. See the\n    :attr:`WKBWriter.outdim` documentation for more details about the ``dim``\n    argument.\n\n    .. method:: WKBWriter.write(geom)\n\n    Returns the WKB of the given geometry as a Python ``buffer`` object.\n    Example::\n\n        >>> from django.contrib.gis.geos import Point, WKBWriter\n        >>> pnt = Point(1, 1)\n        >>> wkb_w = WKBWriter()\n        >>> wkb_w.write(pnt)\n        <read-only buffer for 0x103a898f0, size -1, offset 0 at 0x103a89930>\n\n    .. method:: WKBWriter.write_hex(geom)\n\n    Returns WKB of the geometry in hexadecimal.  Example::\n\n        >>> from django.contrib.gis.geos import Point, WKBWriter\n        >>> pnt = Point(1, 1)\n        >>> wkb_w = WKBWriter()\n        >>> wkb_w.write_hex(pnt)\n        '0101000000000000000000F03F000000000000F03F'\n\n    .. attribute:: WKBWriter.byteorder\n\n    This property may be set to change the byte-order of the geometry\n    representation.\n\n    =============== =================================================\n    Byteorder Value Description\n    =============== =================================================\n    0               Big Endian (e.g., compatible with RISC systems)\n    1               Little Endian (e.g., compatible with x86 systems)\n    =============== =================================================\n\n    Example::\n\n        >>> from django.contrib.gis.geos import Point, WKBWriter\n        >>> wkb_w = WKBWriter()\n        >>> pnt = Point(1, 1)\n        >>> wkb_w.write_hex(pnt)\n        '0101000000000000000000F03F000000000000F03F'\n        >>> wkb_w.byteorder = 0\n        '00000000013FF00000000000003FF0000000000000'\n\n    .. attribute:: WKBWriter.outdim\n\n    This property may be set to change the output dimension of the geometry\n    representation.  In other words, if you have a 3D geometry then set to 3\n    so that the Z value is included in the WKB.\n\n    ============ ===========================\n    Outdim Value Description\n    ============ ===========================\n    2            The default, output 2D WKB.\n    3            Output 3D WKB.\n    ============ ===========================\n\n    Example::\n\n        >>> from django.contrib.gis.geos import Point, WKBWriter\n        >>> wkb_w = WKBWriter()\n        >>> wkb_w.outdim\n        2\n        >>> pnt = Point(1, 1, 1)\n        >>> wkb_w.write_hex(pnt) # By default, no Z value included:\n        '0101000000000000000000F03F000000000000F03F'\n        >>> wkb_w.outdim = 3 # Tell writer to include Z values\n        >>> wkb_w.write_hex(pnt)\n        '0101000080000000000000F03F000000000000F03F000000000000F03F'\n\n    .. attribute:: WKBWriter.srid\n\n    Set this property with a boolean to indicate whether the SRID of the\n    geometry should be included with the WKB representation.  Example::\n\n        >>> from django.contrib.gis.geos import Point, WKBWriter\n        >>> wkb_w = WKBWriter()\n        >>> pnt = Point(1, 1, srid=4326)\n        >>> wkb_w.write_hex(pnt) # By default, no SRID included:\n        '0101000000000000000000F03F000000000000F03F'\n        >>> wkb_w.srid = True # Tell writer to include SRID\n        >>> wkb_w.write_hex(pnt)\n        '0101000020E6100000000000000000F03F000000000000F03F'\n\n.. class:: WKTWriter(dim=2, trim=False, precision=None)\n\n    This class allows outputting the WKT representation of a geometry. See the\n    :attr:`WKBWriter.outdim`, :attr:`trim`, and :attr:`precision` attributes for\n    details about the constructor arguments.\n\n    .. method:: WKTWriter.write(geom)\n\n    Returns the WKT of the given geometry. Example::\n\n        >>> from django.contrib.gis.geos import Point, WKTWriter\n        >>> pnt = Point(1, 1)\n        >>> wkt_w = WKTWriter()\n        >>> wkt_w.write(pnt)\n        'POINT (1.0000000000000000 1.0000000000000000)'\n\n    .. attribute:: WKTWriter.outdim\n\n        See :attr:`WKBWriter.outdim`.\n\n    .. attribute:: WKTWriter.trim\n\n    This property is used to enable or disable trimming of\n    unnecessary decimals.\n\n        >>> from django.contrib.gis.geos import Point, WKTWriter\n        >>> pnt = Point(1, 1)\n        >>> wkt_w = WKTWriter()\n        >>> wkt_w.trim\n        False\n        >>> wkt_w.write(pnt)\n        'POINT (1.0000000000000000 1.0000000000000000)'\n        >>> wkt_w.trim = True\n        >>> wkt_w.write(pnt)\n        'POINT (1 1)'\n\n    .. attribute:: WKTWriter.precision\n\n    This property controls the rounding precision of coordinates;\n    if set to ``None`` rounding is disabled.\n\n        >>> from django.contrib.gis.geos import Point, WKTWriter\n        >>> pnt = Point(1.44, 1.66)\n        >>> wkt_w = WKTWriter()\n        >>> print(wkt_w.precision)\n        None\n        >>> wkt_w.write(pnt)\n        'POINT (1.4399999999999999 1.6599999999999999)'\n        >>> wkt_w.precision = 0\n        >>> wkt_w.write(pnt)\n        'POINT (1 2)'\n        >>> wkt_w.precision = 1\n        >>> wkt_w.write(pnt)\n        'POINT (1.4 1.7)'\n\n.. rubric:: Footnotes\n.. [#fnogc] *See* `PostGIS EWKB, EWKT and Canonical Forms <https://postgis.net/docs/using_postgis_dbmanagement.html#EWKB_EWKT>`_, PostGIS documentation at Ch. 4.1.2.\n\nSettings\n========\n\n.. setting:: GEOS_LIBRARY_PATH\n\n``GEOS_LIBRARY_PATH``\n---------------------\n\nA string specifying the location of the GEOS C library.  Typically,\nthis setting is only used if the GEOS C library is in a non-standard\nlocation (e.g., ``/home/bob/lib/libgeos_c.so``).\n\n.. note::\n\n    The setting must be the *full* path to the **C** shared library; in\n    other words you want to use ``libgeos_c.so``, not ``libgeos.so``.\n\nExceptions\n==========\n\n.. exception:: GEOSException\n\n    The base GEOS exception, indicates a GEOS-related error.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":137,"nodeType":"TextFile","repoName":null,"name":"validators.txt","path":"docs/ref/contrib/postgres","text":"==========\nValidators\n==========\n\n.. module:: django.contrib.postgres.validators\n\nThese validators are available from the ``django.contrib.postgres.validators``\nmodule.\n\n``KeysValidator``\n=================\n\n.. class:: KeysValidator(keys, strict=False, messages=None)\n\n    Validates that the given keys are contained in the value. If ``strict`` is\n    ``True``, then it also checks that there are no other keys present.\n\n    The ``messages`` passed should be a dict containing the keys\n    ``missing_keys`` and/or ``extra_keys``.\n\n    .. note::\n        Note that this checks only for the existence of a given key, not that\n        the value of a key is non-empty.\n\nRange validators\n================\n\n``RangeMaxValueValidator``\n--------------------------\n\n.. class:: RangeMaxValueValidator(limit_value, message=None)\n\n    Validates that the upper bound of the range is not greater than\n    ``limit_value``.\n\n``RangeMinValueValidator``\n--------------------------\n\n.. class:: RangeMinValueValidator(limit_value, message=None)\n\n    Validates that the lower bound of the range is not less than the\n    ``limit_value``.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":138,"nodeType":"TextFile","repoName":null,"name":"aggregates.txt","path":"docs/ref/contrib/postgres","text":"=========================================\nPostgreSQL specific aggregation functions\n=========================================\n\n.. module:: django.contrib.postgres.aggregates\n   :synopsis: PostgreSQL specific aggregation functions\n\nThese functions are available from the ``django.contrib.postgres.aggregates``\nmodule. They are described in more detail in the `PostgreSQL docs\n<https://www.postgresql.org/docs/current/functions-aggregate.html>`_.\n\n.. note::\n\n    All functions come without default aliases, so you must explicitly provide\n    one. For example::\n\n        >>> SomeModel.objects.aggregate(arr=ArrayAgg('somefield'))\n        {'arr': [0, 1, 2]}\n\n.. admonition:: Common aggregate options\n\n    All aggregates have the :ref:`filter <aggregate-filter>` keyword\n    argument.\n\nGeneral-purpose aggregation functions\n=====================================\n\n``ArrayAgg``\n------------\n\n.. class:: ArrayAgg(expression, distinct=False, filter=None, ordering=(), **extra)\n\n    Returns a list of values, including nulls, concatenated into an array.\n\n    .. attribute:: distinct\n\n        An optional boolean argument that determines if array values\n        will be distinct. Defaults to ``False``.\n\n    .. attribute:: ordering\n\n        An optional string of a field name (with an optional ``\"-\"`` prefix\n        which indicates descending order) or an expression (or a tuple or list\n        of strings and/or expressions) that specifies the ordering of the\n        elements in the result list.\n\n        Examples::\n\n            'some_field'\n            '-some_field'\n            from django.db.models import F\n            F('some_field').desc()\n\n``BitAnd``\n----------\n\n.. class:: BitAnd(expression, filter=None, **extra)\n\n    Returns an ``int`` of the bitwise ``AND`` of all non-null input values, or\n    ``None`` if all values are null.\n\n``BitOr``\n---------\n\n.. class:: BitOr(expression, filter=None, **extra)\n\n    Returns an ``int`` of the bitwise ``OR`` of all non-null input values, or\n    ``None`` if all values are null.\n\n``BoolAnd``\n-----------\n\n.. class:: BoolAnd(expression, filter=None, **extra)\n\n    Returns ``True``, if all input values are true, ``None`` if all values are\n    null or if there are no values, otherwise ``False`` .\n\n``BoolOr``\n----------\n\n.. class:: BoolOr(expression, filter=None, **extra)\n\n    Returns ``True`` if at least one input value is true, ``None`` if all\n    values are null or if there are no values, otherwise ``False``.\n\n``JSONBAgg``\n------------\n\n.. class:: JSONBAgg(expressions, filter=None, **extra)\n\n    Returns the input values as a ``JSON`` array.\n\n``StringAgg``\n-------------\n\n.. class:: StringAgg(expression, delimiter, distinct=False, filter=None, ordering=())\n\n    Returns the input values concatenated into a string, separated by\n    the ``delimiter`` string.\n\n    .. attribute:: delimiter\n\n        Required argument. Needs to be a string.\n\n    .. attribute:: distinct\n\n        An optional boolean argument that determines if concatenated values\n        will be distinct. Defaults to ``False``.\n\n    .. attribute:: ordering\n\n        An optional string of a field name (with an optional ``\"-\"`` prefix\n        which indicates descending order) or an expression (or a tuple or list\n        of strings and/or expressions) that specifies the ordering of the\n        elements in the result string.\n\n        Examples are the same as for :attr:`ArrayAgg.ordering`.\n\nAggregate functions for statistics\n==================================\n\n``y`` and ``x``\n---------------\n\nThe arguments ``y`` and ``x`` for all these functions can be the name of a\nfield or an expression returning a numeric data. Both are required.\n\n``Corr``\n--------\n\n.. class:: Corr(y, x, filter=None)\n\n    Returns the correlation coefficient as a ``float``, or ``None`` if there\n    aren't any matching rows.\n\n``CovarPop``\n------------\n\n.. class:: CovarPop(y, x, sample=False, filter=None)\n\n    Returns the population covariance as a ``float``, or ``None`` if there\n    aren't any matching rows.\n\n    Has one optional argument:\n\n    .. attribute:: sample\n\n        By default ``CovarPop`` returns the general population covariance.\n        However, if ``sample=True``, the return value will be the sample\n        population covariance.\n\n``RegrAvgX``\n------------\n\n.. class:: RegrAvgX(y, x, filter=None)\n\n    Returns the average of the independent variable (``sum(x)/N``) as a\n    ``float``, or ``None`` if there aren't any matching rows.\n\n``RegrAvgY``\n------------\n\n.. class:: RegrAvgY(y, x, filter=None)\n\n    Returns the average of the dependent variable (``sum(y)/N``) as a\n    ``float``, or ``None`` if there aren't any matching rows.\n\n``RegrCount``\n-------------\n\n.. class:: RegrCount(y, x, filter=None)\n\n    Returns an ``int`` of the number of input rows in which both expressions\n    are not null.\n\n``RegrIntercept``\n-----------------\n\n.. class:: RegrIntercept(y, x, filter=None)\n\n    Returns the y-intercept of the least-squares-fit linear equation determined\n    by the ``(x, y)`` pairs as a ``float``, or ``None`` if there aren't any\n    matching rows.\n\n``RegrR2``\n----------\n\n.. class:: RegrR2(y, x, filter=None)\n\n    Returns the square of the correlation coefficient as a ``float``, or\n    ``None`` if there aren't any matching rows.\n\n``RegrSlope``\n-------------\n\n.. class:: RegrSlope(y, x, filter=None)\n\n    Returns the slope of the least-squares-fit linear equation determined\n    by the ``(x, y)`` pairs as a ``float``, or ``None`` if there aren't any\n    matching rows.\n\n``RegrSXX``\n-----------\n\n.. class:: RegrSXX(y, x, filter=None)\n\n    Returns ``sum(x^2) - sum(x)^2/N`` (\"sum of squares\" of the independent\n    variable) as a ``float``, or ``None`` if there aren't any matching rows.\n\n``RegrSXY``\n-----------\n\n.. class:: RegrSXY(y, x, filter=None)\n\n    Returns ``sum(x*y) - sum(x) * sum(y)/N`` (\"sum of products\" of independent\n    times dependent variable) as a ``float``, or ``None`` if there aren't any\n    matching rows.\n\n``RegrSYY``\n-----------\n\n.. class:: RegrSYY(y, x, filter=None)\n\n    Returns ``sum(y^2) - sum(y)^2/N`` (\"sum of squares\" of the dependent\n    variable)  as a ``float``, or ``None`` if there aren't any matching rows.\n\nUsage examples\n==============\n\nWe will use this example table::\n\n    | FIELD1 | FIELD2 | FIELD3 |\n    |--------|--------|--------|\n    |    foo |      1 |     13 |\n    |    bar |      2 | (null) |\n    |   test |      3 |     13 |\n\n\nHere's some examples of some of the general-purpose aggregation functions::\n\n    >>> TestModel.objects.aggregate(result=StringAgg('field1', delimiter=';'))\n    {'result': 'foo;bar;test'}\n    >>> TestModel.objects.aggregate(result=ArrayAgg('field2'))\n    {'result': [1, 2, 3]}\n    >>> TestModel.objects.aggregate(result=ArrayAgg('field1'))\n    {'result': ['foo', 'bar', 'test']}\n\nThe next example shows the usage of statistical aggregate functions. The\nunderlying math will be not described (you can read about this, for example, at\n`wikipedia <https://en.wikipedia.org/wiki/Regression_analysis>`_)::\n\n    >>> TestModel.objects.aggregate(count=RegrCount(y='field3', x='field2'))\n    {'count': 2}\n    >>> TestModel.objects.aggregate(avgx=RegrAvgX(y='field3', x='field2'),\n    ...                             avgy=RegrAvgY(y='field3', x='field2'))\n    {'avgx': 2, 'avgy': 13}\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":139,"nodeType":"TextFile","repoName":null,"name":"indexes.txt","path":"docs/ref/contrib/postgres","text":"=================================\nPostgreSQL specific model indexes\n=================================\n\n.. module:: django.contrib.postgres.indexes\n\nThe following are PostgreSQL specific :doc:`indexes </ref/models/indexes>`\navailable from the ``django.contrib.postgres.indexes`` module.\n\n``BloomIndex``\n==============\n\n.. class:: BloomIndex(length=None, columns=(), **options)\n\n    .. versionadded:: 3.1\n\n    Creates a bloom_ index.\n\n    To use this index access you need to activate the bloom_ extension on\n    PostgreSQL. You can install it using the\n    :class:`~django.contrib.postgres.operations.BloomExtension` migration\n    operation.\n\n    Provide an integer number of bits from 1 to 4096 to the ``length``\n    parameter to specify the length of each index entry. PostgreSQL's default\n    is 80.\n\n    The ``columns`` argument takes a tuple or list of up to 32 values that are\n    integer number of bits from 1 to 4095.\n\n    .. _bloom: https://www.postgresql.org/docs/current/bloom.html\n\n``BrinIndex``\n=============\n\n.. class:: BrinIndex(autosummarize=None, pages_per_range=None, **options)\n\n    Creates a `BRIN index\n    <https://www.postgresql.org/docs/current/brin-intro.html>`_.\n\n    Set the ``autosummarize`` parameter to ``True`` to enable `automatic\n    summarization`_ to be performed by autovacuum.\n\n    The ``pages_per_range`` argument takes a positive integer.\n\n    .. _automatic summarization: https://www.postgresql.org/docs/current/brin-intro.html#BRIN-OPERATION\n\n``BTreeIndex``\n==============\n\n.. class:: BTreeIndex(fillfactor=None, **options)\n\n    Creates a B-Tree index.\n\n    Provide an integer value from 10 to 100 to the fillfactor_ parameter to\n    tune how packed the index pages will be. PostgreSQL's default is 90.\n\n    .. _fillfactor: https://www.postgresql.org/docs/current/sql-createindex.html#SQL-CREATEINDEX-STORAGE-PARAMETERS\n\n``GinIndex``\n============\n\n.. class:: GinIndex(fastupdate=None, gin_pending_list_limit=None, **options)\n\n    Creates a `gin index <https://www.postgresql.org/docs/current/gin.html>`_.\n\n    To use this index on data types not in the `built-in operator classes\n    <https://www.postgresql.org/docs/current/gin-builtin-opclasses.html>`_,\n    you need to activate the `btree_gin extension\n    <https://www.postgresql.org/docs/current/btree-gin.html>`_ on\n    PostgreSQL. You can install it using the\n    :class:`~django.contrib.postgres.operations.BtreeGinExtension` migration\n    operation.\n\n    Set the ``fastupdate`` parameter to ``False`` to disable the `GIN Fast\n    Update Technique`_ that's enabled by default in PostgreSQL.\n\n    Provide an integer number of bytes to the gin_pending_list_limit_ parameter\n    to tune the maximum size of the GIN pending list which is used when\n    ``fastupdate`` is enabled.\n\n    .. _GIN Fast Update Technique: https://www.postgresql.org/docs/current/gin-implementation.html#GIN-FAST-UPDATE\n    .. _gin_pending_list_limit: https://www.postgresql.org/docs/current/runtime-config-client.html#GUC-GIN-PENDING-LIST-LIMIT\n\n``GistIndex``\n=============\n\n.. class:: GistIndex(buffering=None, fillfactor=None, **options)\n\n    Creates a `GiST index\n    <https://www.postgresql.org/docs/current/gist.html>`_. These indexes are\n    automatically created on spatial fields with :attr:`spatial_index=True\n    <django.contrib.gis.db.models.BaseSpatialField.spatial_index>`. They're\n    also useful on other types, such as\n    :class:`~django.contrib.postgres.fields.HStoreField` or the :ref:`range\n    fields <range-fields>`.\n\n    To use this index on data types not in the built-in `gist operator classes\n    <https://www.postgresql.org/docs/current/gist-builtin-opclasses.html>`_,\n    you need to activate the `btree_gist extension\n    <https://www.postgresql.org/docs/current/btree-gist.html>`_ on PostgreSQL.\n    You can install it using the\n    :class:`~django.contrib.postgres.operations.BtreeGistExtension` migration\n    operation.\n\n    Set the ``buffering`` parameter to ``True`` or ``False`` to manually enable\n    or disable `buffering build`_ of the index.\n\n    Provide an integer value from 10 to 100 to the fillfactor_ parameter to\n    tune how packed the index pages will be. PostgreSQL's default is 90.\n\n    .. _buffering build: https://www.postgresql.org/docs/current/gist-implementation.html#GIST-BUFFERING-BUILD\n    .. _fillfactor: https://www.postgresql.org/docs/current/sql-createindex.html#SQL-CREATEINDEX-STORAGE-PARAMETERS\n\n``HashIndex``\n=============\n\n.. class:: HashIndex(fillfactor=None, **options)\n\n    Creates a hash index.\n\n    Provide an integer value from 10 to 100 to the fillfactor_ parameter to\n    tune how packed the index pages will be. PostgreSQL's default is 90.\n\n    .. admonition:: Use this index only on PostgreSQL 10 and later\n\n        Hash indexes have been available in PostgreSQL for a long time, but\n        they suffer from a number of data integrity issues in older versions.\n\n    .. _fillfactor: https://www.postgresql.org/docs/current/sql-createindex.html#SQL-CREATEINDEX-STORAGE-PARAMETERS\n\n``SpGistIndex``\n===============\n\n.. class:: SpGistIndex(fillfactor=None, **options)\n\n    Creates an `SP-GiST index\n    <https://www.postgresql.org/docs/current/spgist.html>`_.\n\n    Provide an integer value from 10 to 100 to the fillfactor_ parameter to\n    tune how packed the index pages will be. PostgreSQL's default is 90.\n\n    .. _fillfactor: https://www.postgresql.org/docs/current/sql-createindex.html#SQL-CREATEINDEX-STORAGE-PARAMETERS\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":140,"nodeType":"TextFile","repoName":null,"name":"postgis.txt","path":"docs/ref/contrib/gis/install","text":"==================\nInstalling PostGIS\n==================\n\n`PostGIS`_ adds geographic object support to PostgreSQL, turning it\ninto a spatial database. :ref:`geosbuild`, :ref:`proj4` and\n:ref:`gdalbuild` should be installed prior to building PostGIS. You\nmight also need additional libraries, see `PostGIS requirements`_.\n\nThe `psycopg2`_ module is required for use as the database adapter when using\nGeoDjango with PostGIS.\n\nOn Debian/Ubuntu, you are advised to install the following packages:\npostgresql-x.x, postgresql-x.x-postgis, postgresql-server-dev-x.x,\npython-psycopg2 (x.x matching the PostgreSQL version you want to install).\nAlternately, you can `build from source`_. Consult the platform-specific\ninstructions if you are on :ref:`macos` or :ref:`windows`.\n\n.. _PostGIS: https://postgis.net/\n.. _psycopg2: https://www.psycopg.org/\n.. _PostGIS requirements: https://postgis.net/docs/postgis_installation.html#install_requirements\n.. _build from source: https://postgis.net/docs/postgis_installation.html#install_short_version\n\nPost-installation\n=================\n\n.. _spatialdb_template:\n\nCreating a spatial database\n---------------------------\n\nPostGIS 2 includes an extension for PostgreSQL that's used to enable spatial\nfunctionality::\n\n    $ createdb  <db name>\n    $ psql <db name>\n    > CREATE EXTENSION postgis;\n\nThe database user must be a superuser in order to run\n``CREATE EXTENSION postgis;``. The command is run during the :djadmin:`migrate`\nprocess. An alternative is to use a migration operation in your project::\n\n    from django.contrib.postgres.operations import CreateExtension\n    from django.db import migrations\n\n    class Migration(migrations.Migration):\n\n        operations = [\n            CreateExtension('postgis'),\n            ...\n        ]\n\nIf you plan to use PostGIS raster functionality on PostGIS 3+, you should also\nactivate the ``postgis_raster`` extension. You can install the extension using\nthe :class:`~django.contrib.postgres.operations.CreateExtension` migration\noperation, or directly by running ``CREATE EXTENSION postgis_raster;``.\n\nGeoDjango does not currently leverage any `PostGIS topology functionality`__.\nIf you plan to use those features at some point, you can also install the\n``postgis_topology`` extension by issuing ``CREATE EXTENSION\npostgis_topology;``.\n\n__ https://postgis.net/docs/Topology.html\n\nManaging the database\n---------------------\n\nTo administer the database, you can either use the pgAdmin III program\n(:menuselection:`Start --> PostgreSQL 9.x --> pgAdmin III`) or the\nSQL Shell (:menuselection:`Start --> PostgreSQL 9.x --> SQL Shell`).\nFor example, to create a ``geodjango`` spatial database and user, the following\nmay be executed from the SQL Shell as the ``postgres`` user::\n\n    postgres# CREATE USER geodjango PASSWORD 'my_passwd';\n    postgres# CREATE DATABASE geodjango OWNER geodjango;\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":141,"nodeType":"TextFile","repoName":null,"name":"javascript.txt","path":"docs/ref/contrib/admin","text":"======================================\nJavaScript customizations in the admin\n======================================\n\n.. _admin-javascript-inline-form-events:\n\nInline form events\n==================\n\nYou may want to execute some JavaScript when an inline form is added or removed\nin the admin change form. The ``formset:added`` and ``formset:removed`` jQuery\nevents allow this. The event handler is passed three arguments:\n\n* ``event`` is the ``jQuery`` event.\n* ``$row`` is the newly added (or removed) row.\n* ``formsetName`` is the formset the row belongs to.\n\nThe event is fired using the :ref:`django.jQuery namespace\n<contrib-admin-jquery>`.\n\nIn your custom ``change_form.html`` template, extend the\n``admin_change_form_document_ready`` block and add the event listener code:\n\n.. code-block:: html+django\n\n    {% extends 'admin/change_form.html' %}\n    {% load static %}\n\n    {% block admin_change_form_document_ready %}\n    {{ block.super }}\n    <script src=\"{% static 'app/formset_handlers.js' %}\"></script>\n    {% endblock %}\n\n.. code-block:: javascript\n    :caption: app/static/app/formset_handlers.js\n\n    (function($) {\n        $(document).on('formset:added', function(event, $row, formsetName) {\n            if (formsetName == 'author_set') {\n                // Do something\n            }\n        });\n\n        $(document).on('formset:removed', function(event, $row, formsetName) {\n            // Row removed\n        });\n    })(django.jQuery);\n\nTwo points to keep in mind:\n\n* The JavaScript code must go in a template block if you are inheriting\n  ``admin/change_form.html`` or it won't be rendered in the final HTML.\n* ``{{ block.super }}`` is added because Django's\n  ``admin_change_form_document_ready`` block contains JavaScript code to handle\n  various operations in the change form and we need that to be rendered too.\n\nSometimes you'll need to work with ``jQuery`` plugins that are not registered\nin the ``django.jQuery`` namespace. To do that, change how the code listens for\nevents. Instead of wrapping the listener in the ``django.jQuery`` namespace,\nlisten to the event triggered from there. For example:\n\n.. code-block:: html+django\n\n    {% extends 'admin/change_form.html' %}\n    {% load static %}\n\n    {% block admin_change_form_document_ready %}\n    {{ block.super }}\n    <script src=\"{% static 'app/unregistered_handlers.js' %}\"></script>\n    {% endblock %}\n\n.. code-block:: javascript\n    :caption: app/static/app/unregistered_handlers.js\n\n    django.jQuery(document).on('formset:added', function(event, $row, formsetName) {\n        // Row added\n    });\n\n    django.jQuery(document).on('formset:removed', function(event, $row, formsetName) {\n        // Row removed\n    });\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":142,"nodeType":"TextFile","repoName":null,"name":"lookups.txt","path":"docs/ref/contrib/postgres","text":"===========================\nPostgreSQL specific lookups\n===========================\n\nTrigram similarity\n==================\n\n.. fieldlookup:: trigram_similar\n\nThe ``trigram_similar`` lookup allows you to perform trigram lookups,\nmeasuring the number of trigrams (three consecutive characters) shared, using a\ndedicated PostgreSQL extension. A trigram lookup is given an expression and\nreturns results that have a similarity measurement greater than the current\nsimilarity threshold.\n\nTo use it, add ``'django.contrib.postgres'`` in your :setting:`INSTALLED_APPS`\nand activate the `pg_trgm extension\n<https://www.postgresql.org/docs/current/pgtrgm.html>`_ on PostgreSQL. You can\ninstall the extension using the\n:class:`~django.contrib.postgres.operations.TrigramExtension` migration\noperation.\n\nThe ``trigram_similar`` lookup can be used on\n:class:`~django.db.models.CharField` and :class:`~django.db.models.TextField`::\n\n    >>> City.objects.filter(name__trigram_similar=\"Middlesborough\")\n    ['<City: Middlesbrough>']\n\n``Unaccent``\n============\n\n.. fieldlookup:: unaccent\n\nThe ``unaccent`` lookup allows you to perform accent-insensitive lookups using\na dedicated PostgreSQL extension.\n\nThis lookup is implemented using :class:`~django.db.models.Transform`, so it\ncan be chained with other lookup functions. To use it, you need to add\n``'django.contrib.postgres'`` in your :setting:`INSTALLED_APPS` and activate\nthe `unaccent extension on PostgreSQL`_. The\n:class:`~django.contrib.postgres.operations.UnaccentExtension` migration\noperation is available if you want to perform this activation using migrations).\n\n.. _unaccent extension on PostgreSQL: https://www.postgresql.org/docs/current/unaccent.html\n\nThe ``unaccent`` lookup can be used on\n:class:`~django.db.models.CharField` and :class:`~django.db.models.TextField`::\n\n    >>> City.objects.filter(name__unaccent=\"México\")\n    ['<City: Mexico>']\n\n    >>> User.objects.filter(first_name__unaccent__startswith=\"Jerem\")\n    ['<User: Jeremy>', '<User: Jérémy>', '<User: Jérémie>', '<User: Jeremie>']\n\n.. warning::\n\n    ``unaccent`` lookups should perform fine in most use cases. However, queries\n    using this filter will generally perform full table scans, which can be slow\n    on large tables. In those cases, using dedicated full text indexing tools\n    might be appropriate.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":143,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/ref/contrib/gis/install","text":"======================\nGeoDjango Installation\n======================\n\n.. highlight:: console\n\nOverview\n========\nIn general, GeoDjango installation requires:\n\n#. :ref:`Python and Django <django>`\n#. :ref:`spatial_database`\n#. :doc:`geolibs`\n\nDetails for each of the requirements and installation instructions\nare provided in the sections below. In addition, platform-specific\ninstructions are available for:\n\n* :ref:`macos`\n* :ref:`windows`\n\n.. admonition:: Use the Source\n\n    Because GeoDjango takes advantage of the latest in the open source geospatial\n    software technology, recent versions of the libraries are necessary.\n    If binary packages aren't available for your platform, installation from\n    source may be required. When compiling the libraries from source, please\n    follow the directions closely, especially if you're a beginner.\n\nRequirements\n============\n\n.. _django:\n\nPython and Django\n-----------------\n\nBecause GeoDjango is included with Django, please refer to Django's\n:ref:`installation instructions <installing-official-release>` for details on\nhow to install.\n\n.. _spatial_database:\n\nSpatial database\n----------------\nPostgreSQL (with PostGIS), MySQL (mostly with MyISAM engine), Oracle, and SQLite\n(with SpatiaLite) are the spatial databases currently supported.\n\n.. note::\n\n    PostGIS is recommended, because it is the most mature and feature-rich\n    open source spatial database.\n\nThe geospatial libraries required for a GeoDjango installation depends\non the spatial database used.  The following lists the library requirements,\nsupported versions, and any notes for each of the supported database backends:\n\n==================  ==============================  ==================  =========================================\nDatabase            Library Requirements            Supported Versions  Notes\n==================  ==============================  ==================  =========================================\nPostgreSQL          GEOS, GDAL, PROJ, PostGIS       9.6+                Requires PostGIS.\nMySQL               GEOS, GDAL                      5.7+                :ref:`Limited functionality <mysql-spatial-limitations>`.\nOracle              GEOS, GDAL                      12.2+               XE not supported.\nSQLite              GEOS, GDAL, PROJ, SpatiaLite    3.8.3+              Requires SpatiaLite 4.3+\n==================  ==============================  ==================  =========================================\n\nSee also `this comparison matrix`__ on the OSGeo Wiki for\nPostgreSQL/PostGIS/GEOS/GDAL possible combinations.\n\n__ https://trac.osgeo.org/postgis/wiki/UsersWikiPostgreSQLPostGIS\n\nInstallation\n============\n\nGeospatial libraries\n--------------------\n\n.. toctree::\n    :maxdepth: 1\n\n    geolibs\n\nDatabase installation\n---------------------\n\n.. toctree::\n    :maxdepth: 1\n\n    postgis\n    spatialite\n\n:setting:`DATABASES` configuration\n----------------------------------\n\nSet the :setting:`ENGINE <DATABASE-ENGINE>` setting to one of the :ref:`spatial\nbackends <spatial-backends>`.\n\nAdd ``django.contrib.gis`` to :setting:`INSTALLED_APPS`\n-------------------------------------------------------\n\nLike other Django contrib applications, you will *only* need to add\n:mod:`django.contrib.gis` to :setting:`INSTALLED_APPS` in your settings.\nThis is so that the ``gis`` templates can be located -- if not done, then\nfeatures such as the geographic admin or KML sitemaps will not function properly.\n\nTroubleshooting\n===============\n\nIf you can't find the solution to your problem here then participate in the\ncommunity!  You can:\n\n* Join the ``#geodjango`` IRC channel on Freenode. Please be patient and polite\n  -- while you may not get an immediate response, someone will attempt to answer\n  your question as soon as they see it.\n* Ask your question on the `GeoDjango`__ mailing list.\n* File a ticket on the `Django trac`__ if you think there's a bug.  Make\n  sure to provide a complete description of the problem, versions used,\n  and specify the component as \"GIS\".\n\n__ https://groups.google.com/d/forum/geodjango\n__ https://code.djangoproject.com/newticket\n\n.. _libsettings:\n\nLibrary environment settings\n----------------------------\n\nBy far, the most common problem when installing GeoDjango is that the\nexternal shared libraries (e.g., for GEOS and GDAL) cannot be located. [#]_\nTypically, the cause of this problem is that the operating system isn't aware\nof the directory where the libraries built from source were installed.\n\nIn general, the library path may be set on a per-user basis by setting\nan environment variable, or by configuring the library path for the entire\nsystem.\n\n``LD_LIBRARY_PATH`` environment variable\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nA user may set this environment variable to customize the library paths\nthey want to use.  The typical library directory for software\nbuilt from source is ``/usr/local/lib``.  Thus, ``/usr/local/lib`` needs\nto be included in the ``LD_LIBRARY_PATH`` variable.  For example, the user\ncould place the following in their bash profile::\n\n    export LD_LIBRARY_PATH=/usr/local/lib\n\nSetting system library path\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nOn GNU/Linux systems, there is typically a file in ``/etc/ld.so.conf``, which may include\nadditional paths from files in another directory, such as ``/etc/ld.so.conf.d``.\nAs the root user, add the custom library path (like ``/usr/local/lib``) on a\nnew line in ``ld.so.conf``.  This is *one* example of how to do so::\n\n    $ sudo echo /usr/local/lib >> /etc/ld.so.conf\n    $ sudo ldconfig\n\nFor OpenSolaris users, the system library path may be modified using the\n``crle`` utility.  Run ``crle`` with no options to see the current configuration\nand use ``crle -l`` to set with the new library path.  Be *very* careful when\nmodifying the system library path::\n\n    # crle -l $OLD_PATH:/usr/local/lib\n\n.. _binutils:\n\nInstall ``binutils``\n~~~~~~~~~~~~~~~~~~~~\n\nGeoDjango uses the ``find_library`` function (from the ``ctypes.util`` Python\nmodule) to discover libraries.  The ``find_library`` routine uses a program\ncalled ``objdump`` (part of the ``binutils`` package) to verify a shared\nlibrary on GNU/Linux systems.  Thus, if ``binutils`` is not installed on your\nLinux system then Python's ctypes may not be able to find your library even if\nyour library path is set correctly and geospatial libraries were built perfectly.\n\nThe ``binutils`` package may be installed on Debian and Ubuntu systems using the\nfollowing command::\n\n    $ sudo apt-get install binutils\n\nSimilarly, on Red Hat and CentOS systems::\n\n    $ sudo yum install binutils\n\nPlatform-specific instructions\n==============================\n\n.. _macos:\n\nmacOS\n-----\n\nBecause of the variety of packaging systems available for macOS, users have\nseveral different options for installing GeoDjango. These options are:\n\n* :ref:`postgresapp` (easiest and recommended)\n* :ref:`homebrew`\n* :ref:`kyngchaos`\n* :ref:`fink`\n* :ref:`macports`\n* :ref:`build_from_source`\n\nThis section also includes instructions for installing an upgraded version\nof :ref:`macos_python` from packages provided by the Python Software\nFoundation, however, this is not required.\n\n.. _macos_python:\n\nPython\n~~~~~~\n\nAlthough macOS comes with Python installed, users can use `framework\ninstallers`__ provided by the Python Software Foundation.  An advantage to\nusing the installer is that macOS's Python will remain \"pristine\" for internal\noperating system use.\n\n__ https://www.python.org/ftp/python/\n\n.. note::\n\n    You will need to modify the ``PATH`` environment variable in your\n    ``.profile`` file so that the new version of Python is used when\n    ``python`` is entered at the command-line::\n\n        export PATH=/Library/Frameworks/Python.framework/Versions/Current/bin:$PATH\n\n.. _postgresapp:\n\nPostgres.app\n~~~~~~~~~~~~\n\n`Postgres.app <https://postgresapp.com/>`_ is a standalone PostgreSQL server\nthat includes the PostGIS extension. You will also need to install ``gdal`` and\n``libgeoip`` with :ref:`homebrew`.\n\nAfter installing Postgres.app, add the following to your ``.bash_profile`` so\nyou can run the package's programs from the command-line. Replace ``X.Y`` with\nthe version of PostgreSQL in the Postgres.app you installed:\n\n.. code-block:: bash\n\n    export PATH=$PATH:/Applications/Postgres.app/Contents/Versions/X.Y/bin\n\nYou can check if the path is set up correctly by typing ``which psql`` at a\nterminal prompt.\n\n.. _homebrew:\n\nHomebrew\n~~~~~~~~\n\n`Homebrew`__ provides \"recipes\" for building binaries and packages from source.\nIt provides recipes for the GeoDjango prerequisites on Macintosh computers\nrunning macOS. Because Homebrew still builds the software from source, `Xcode`_\nis required.\n\nSummary::\n\n    $ brew install postgresql\n    $ brew install postgis\n    $ brew install gdal\n    $ brew install libgeoip\n\n__ https://brew.sh/\n.. _Xcode: https://developer.apple.com/xcode/\n\n.. _kyngchaos:\n\nKyngChaos packages\n~~~~~~~~~~~~~~~~~~\n\nWilliam Kyngesburye provides a number of `geospatial library binary packages`__\nthat help to get GeoDjango installed on macOS without compiling them from\nsource.  However, `Xcode`_ is still necessary for compiling the Python database\nadapters :ref:`psycopg2_kyngchaos` (for PostGIS).\n\n.. note::\n\n    SpatiaLite users should consult the :ref:`spatialite_macos` section\n    after installing the packages for additional instructions.\n\nDownload the framework packages for:\n\n* UnixImageIO\n* PROJ\n* GEOS\n* SQLite3 (includes the SpatiaLite library)\n* GDAL\n\nInstall the packages in the order they are listed above, as the GDAL and SQLite\npackages require the packages listed before them.\n\nAfterwards, you can also install the KyngChaos binary packages for `PostgreSQL\nand PostGIS`__.\n\nAfter installing the binary packages, you'll want to add the following to\nyour ``.profile`` to be able to run the package programs from the command-line::\n\n    export PATH=/Library/Frameworks/UnixImageIO.framework/Programs:$PATH\n    export PATH=/Library/Frameworks/PROJ.framework/Programs:$PATH\n    export PATH=/Library/Frameworks/GEOS.framework/Programs:$PATH\n    export PATH=/Library/Frameworks/SQLite3.framework/Programs:$PATH\n    export PATH=/Library/Frameworks/GDAL.framework/Programs:$PATH\n    export PATH=/usr/local/pgsql/bin:$PATH\n\n__ https://www.kyngchaos.com/software/frameworks\n__ https://www.kyngchaos.com/software/postgres\n\n.. _psycopg2_kyngchaos:\n\npsycopg2\n^^^^^^^^\n\nAfter you've installed the KyngChaos binaries and modified your ``PATH``, as\ndescribed above, ``psycopg2`` may be installed using the following command::\n\n    $ python -m pip install psycopg2\n\n.. note::\n\n    If you don't have ``pip``, follow the :ref:`installation instructions\n    <installing-official-release>` to install it.\n\n.. _fink:\n\nFink\n^^^^\n\n`Kurt Schwehr`__ has been gracious enough to create GeoDjango packages for users\nof the `Fink`__ package system. `Different packages are available`__ (starting\nwith ``django-gis``), depending on which version of Python you want to use.\n\n__ https://schwehr.blogspot.com/\n__ http://www.finkproject.org/\n__ http://pdb.finkproject.org/pdb/browse.php?summary=django-gis\n\n.. _macports:\n\nMacPorts\n~~~~~~~~\n\n`MacPorts`__ may be used to install GeoDjango prerequisites on computers\nrunning macOS.  Because MacPorts still builds the software from source,\n`Xcode`_ is required.\n\nSummary::\n\n    $ sudo port install postgresql93-server\n    $ sudo port install geos\n    $ sudo port install proj\n    $ sudo port install postgis\n    $ sudo port install gdal +geos\n    $ sudo port install libgeoip\n\n.. note::\n\n    You will also have to modify the ``PATH`` in your ``.profile`` so\n    that the MacPorts programs are accessible from the command-line::\n\n        export PATH=/opt/local/bin:/opt/local/lib/postgresql93/bin\n\n    In addition, add the ``DYLD_FALLBACK_LIBRARY_PATH`` setting so that\n    the libraries can be found by Python::\n\n        export DYLD_FALLBACK_LIBRARY_PATH=/opt/local/lib:/opt/local/lib/postgresql93\n\n__ https://www.macports.org/\n\n.. _windows:\n\nWindows\n-------\n\nProceed through the following sections sequentially in order to install\nGeoDjango on Windows.\n\nPython\n~~~~~~\n\n:doc:`Install Python </howto/windows>`.\n\nPostgreSQL\n~~~~~~~~~~\n\nFirst, download the latest `PostgreSQL 9.x installer`__ from the\n`EnterpriseDB`__ website.  After downloading, run the installer, follow the\non-screen directions, and keep the default options unless you know the\nconsequences of changing them.\n\n.. note::\n\n    The PostgreSQL installer creates both a new Windows user to be the\n    'postgres service account' and a ``postgres`` database superuser\n    You will be prompted once to set the password for both accounts --\n    make sure to remember it!\n\nWhen the installer completes, it will ask to launch the Application Stack\nBuilder (ASB) on exit -- keep this checked, as it is necessary to\ninstall :ref:`postgisasb`.\n\n.. note::\n\n    If installed successfully, the PostgreSQL server will run in the\n    background each time the system as started as a Windows service.\n    A :menuselection:`PostgreSQL 9.x` start menu group will created\n    and contains shortcuts for the ASB as well as the 'SQL Shell',\n    which will launch a ``psql`` command window.\n\n__ https://www.enterprisedb.com/downloads/postgres-postgresql-downloads\n__ https://www.enterprisedb.com\n\n.. _postgisasb:\n\nPostGIS\n~~~~~~~\n\nFrom within the Application Stack Builder (to run outside of the installer,\n:menuselection:`Start --> Programs --> PostgreSQL 9.x`), select\n:menuselection:`PostgreSQL Database Server 9.x on port 5432` from the drop down\nmenu.  Next, expand the :menuselection:`Categories --> Spatial Extensions` menu\ntree and select :menuselection:`PostGIS X.Y for PostgreSQL 9.x`.\n\nAfter clicking next, you will be prompted to select your mirror, PostGIS\nwill be downloaded, and the PostGIS installer will begin.  Select only the\ndefault options during install (e.g., do not uncheck the option to create a\ndefault PostGIS database).\n\n.. note::\n\n    You will be prompted to enter your ``postgres`` database superuser\n    password in the 'Database Connection Information' dialog.\n\npsycopg2\n~~~~~~~~\n\nThe ``psycopg2`` Python module provides the interface between Python and the\nPostgreSQL database.  Download the latest `Windows installer`__ for your version\nof Python and PostgreSQL and run using the default settings. [#]_\n\n__ http://www.stickpeople.com/projects/python/win-psycopg/\n\n.. _osgeo4w:\n\nOSGeo4W\n~~~~~~~\n\nThe `OSGeo4W installer`_ helps to install the PROJ, GDAL, and GEOS libraries\nrequired by GeoDjango. First, download the `OSGeo4W installer`_, and run it.\nSelect :menuselection:`Express Web-GIS Install` and click next.  In the 'Select\nPackages' list, ensure that GDAL is selected; MapServer and Apache are also\nenabled by default, but are not required by GeoDjango and may be unchecked\nsafely.  After clicking next, the packages will be automatically downloaded and\ninstalled, after which you may exit the installer.\n\n.. _OSGeo4W installer: https://trac.osgeo.org/osgeo4w/\n\nModify Windows environment\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIn order to use GeoDjango, you will need to add your Python and OSGeo4W\ndirectories to your Windows system ``Path``, as well as create ``GDAL_DATA``\nand ``PROJ_LIB`` environment variables.  The following set of commands,\nexecutable with ``cmd.exe``, will set this up:\n\n.. code-block:: bat\n\n    set OSGEO4W_ROOT=C:\\OSGeo4W\n    set PYTHON_ROOT=C:\\Python3X\n    set GDAL_DATA=%OSGEO4W_ROOT%\\share\\gdal\n    set PROJ_LIB=%OSGEO4W_ROOT%\\share\\proj\n    set PATH=%PATH%;%PYTHON_ROOT%;%OSGEO4W_ROOT%\\bin\n    reg ADD \"HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\" /v Path /t REG_EXPAND_SZ /f /d \"%PATH%\"\n    reg ADD \"HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\" /v GDAL_DATA /t REG_EXPAND_SZ /f /d \"%GDAL_DATA%\"\n    reg ADD \"HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\" /v PROJ_LIB /t REG_EXPAND_SZ /f /d \"%PROJ_LIB%\"\n\n.. note::\n\n    Administrator privileges are required to execute these commands.\n    To do this, create a ``bat`` script with the commands, right-click it, and\n    select :menuselection:`Run as administrator`. You need to log out and log\n    back in again for the settings to take effect.\n\n.. note::\n\n    If you customized the Python or OSGeo4W installation directories,\n    then you will need to modify the ``OSGEO4W_ROOT`` and/or ``PYTHON_ROOT``\n    variables accordingly.\n\nInstall Django and set up database\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nFinally, :ref:`install Django <installing-official-release>` on your system.\n\n.. rubric:: Footnotes\n.. [#] GeoDjango uses the :func:`~ctypes.util.find_library` routine from\n       ``ctypes.util`` to locate shared libraries.\n.. [#] The ``psycopg2`` Windows installers are packaged and maintained by\n       `Jason Erickson <http://www.stickpeople.com/projects/python/win-psycopg/>`_.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":144,"nodeType":"TextFile","repoName":null,"name":"fields.txt","path":"docs/ref/contrib/postgres","text":"================================\nPostgreSQL specific model fields\n================================\n\nAll of these fields are available from the ``django.contrib.postgres.fields``\nmodule.\n\n.. currentmodule:: django.contrib.postgres.fields\n\nIndexing these fields\n=====================\n\n:class:`~django.db.models.Index` and :attr:`.Field.db_index` both create a\nB-tree index, which isn't particularly helpful when querying complex data types.\nIndexes such as :class:`~django.contrib.postgres.indexes.GinIndex` and\n:class:`~django.contrib.postgres.indexes.GistIndex` are better suited, though\nthe index choice is dependent on the queries that you're using. Generally, GiST\nmay be a good choice for the :ref:`range fields <range-fields>` and\n:class:`HStoreField`, and GIN may be helpful for :class:`ArrayField`.\n\n``ArrayField``\n==============\n\n.. class:: ArrayField(base_field, size=None, **options)\n\n    A field for storing lists of data. Most field types can be used, and you\n    pass another field instance as the :attr:`base_field\n    <ArrayField.base_field>`. You may also specify a :attr:`size\n    <ArrayField.size>`. ``ArrayField`` can be nested to store multi-dimensional\n    arrays.\n\n    If you give the field a :attr:`~django.db.models.Field.default`, ensure\n    it's a callable such as ``list`` (for an empty default) or a callable that\n    returns a list (such as a function). Incorrectly using ``default=[]``\n    creates a mutable default that is shared between all instances of\n    ``ArrayField``.\n\n    .. attribute:: base_field\n\n        This is a required argument.\n\n        Specifies the underlying data type and behavior for the array. It\n        should be an instance of a subclass of\n        :class:`~django.db.models.Field`. For example, it could be an\n        :class:`~django.db.models.IntegerField` or a\n        :class:`~django.db.models.CharField`. Most field types are permitted,\n        with the exception of those handling relational data\n        (:class:`~django.db.models.ForeignKey`,\n        :class:`~django.db.models.OneToOneField` and\n        :class:`~django.db.models.ManyToManyField`).\n\n        It is possible to nest array fields - you can specify an instance of\n        ``ArrayField`` as the ``base_field``. For example::\n\n            from django.contrib.postgres.fields import ArrayField\n            from django.db import models\n\n            class ChessBoard(models.Model):\n                board = ArrayField(\n                    ArrayField(\n                        models.CharField(max_length=10, blank=True),\n                        size=8,\n                    ),\n                    size=8,\n                )\n\n        Transformation of values between the database and the model, validation\n        of data and configuration, and serialization are all delegated to the\n        underlying base field.\n\n    .. attribute:: size\n\n        This is an optional argument.\n\n        If passed, the array will have a maximum size as specified. This will\n        be passed to the database, although PostgreSQL at present does not\n        enforce the restriction.\n\n.. note::\n\n    When nesting ``ArrayField``, whether you use the ``size`` parameter or not,\n    PostgreSQL requires that the arrays are rectangular::\n\n        from django.contrib.postgres.fields import ArrayField\n        from django.db import models\n\n        class Board(models.Model):\n            pieces = ArrayField(ArrayField(models.IntegerField()))\n\n        # Valid\n        Board(pieces=[\n            [2, 3],\n            [2, 1],\n        ])\n\n        # Not valid\n        Board(pieces=[\n            [2, 3],\n            [2],\n        ])\n\n    If irregular shapes are required, then the underlying field should be made\n    nullable and the values padded with ``None``.\n\nQuerying ``ArrayField``\n-----------------------\n\nThere are a number of custom lookups and transforms for :class:`ArrayField`.\nWe will use the following example model::\n\n    from django.contrib.postgres.fields import ArrayField\n    from django.db import models\n\n    class Post(models.Model):\n        name = models.CharField(max_length=200)\n        tags = ArrayField(models.CharField(max_length=200), blank=True)\n\n        def __str__(self):\n            return self.name\n\n.. fieldlookup:: arrayfield.contains\n\n``contains``\n~~~~~~~~~~~~\n\nThe :lookup:`contains` lookup is overridden on :class:`ArrayField`. The\nreturned objects will be those where the values passed are a subset of the\ndata. It uses the SQL operator ``@>``. For example::\n\n    >>> Post.objects.create(name='First post', tags=['thoughts', 'django'])\n    >>> Post.objects.create(name='Second post', tags=['thoughts'])\n    >>> Post.objects.create(name='Third post', tags=['tutorial', 'django'])\n\n    >>> Post.objects.filter(tags__contains=['thoughts'])\n    <QuerySet [<Post: First post>, <Post: Second post>]>\n\n    >>> Post.objects.filter(tags__contains=['django'])\n    <QuerySet [<Post: First post>, <Post: Third post>]>\n\n    >>> Post.objects.filter(tags__contains=['django', 'thoughts'])\n    <QuerySet [<Post: First post>]>\n\n.. fieldlookup:: arrayfield.contained_by\n\n``contained_by``\n~~~~~~~~~~~~~~~~\n\nThis is the inverse of the :lookup:`contains <arrayfield.contains>` lookup -\nthe objects returned will be those where the data is a subset of the values\npassed. It uses the SQL operator ``<@``. For example::\n\n    >>> Post.objects.create(name='First post', tags=['thoughts', 'django'])\n    >>> Post.objects.create(name='Second post', tags=['thoughts'])\n    >>> Post.objects.create(name='Third post', tags=['tutorial', 'django'])\n\n    >>> Post.objects.filter(tags__contained_by=['thoughts', 'django'])\n    <QuerySet [<Post: First post>, <Post: Second post>]>\n\n    >>> Post.objects.filter(tags__contained_by=['thoughts', 'django', 'tutorial'])\n    <QuerySet [<Post: First post>, <Post: Second post>, <Post: Third post>]>\n\n.. fieldlookup:: arrayfield.overlap\n\n``overlap``\n~~~~~~~~~~~\n\nReturns objects where the data shares any results with the values passed. Uses\nthe SQL operator ``&&``. For example::\n\n    >>> Post.objects.create(name='First post', tags=['thoughts', 'django'])\n    >>> Post.objects.create(name='Second post', tags=['thoughts'])\n    >>> Post.objects.create(name='Third post', tags=['tutorial', 'django'])\n\n    >>> Post.objects.filter(tags__overlap=['thoughts'])\n    <QuerySet [<Post: First post>, <Post: Second post>]>\n\n    >>> Post.objects.filter(tags__overlap=['thoughts', 'tutorial'])\n    <QuerySet [<Post: First post>, <Post: Second post>, <Post: Third post>]>\n\n.. fieldlookup:: arrayfield.len\n\n``len``\n~~~~~~~\n\nReturns the length of the array. The lookups available afterwards are those\navailable for :class:`~django.db.models.IntegerField`. For example::\n\n    >>> Post.objects.create(name='First post', tags=['thoughts', 'django'])\n    >>> Post.objects.create(name='Second post', tags=['thoughts'])\n\n    >>> Post.objects.filter(tags__len=1)\n    <QuerySet [<Post: Second post>]>\n\n.. fieldlookup:: arrayfield.index\n\nIndex transforms\n~~~~~~~~~~~~~~~~\n\nIndex transforms index into the array. Any non-negative integer can be used.\nThere are no errors if it exceeds the :attr:`size <ArrayField.size>` of the\narray. The lookups available after the transform are those from the\n:attr:`base_field <ArrayField.base_field>`. For example::\n\n    >>> Post.objects.create(name='First post', tags=['thoughts', 'django'])\n    >>> Post.objects.create(name='Second post', tags=['thoughts'])\n\n    >>> Post.objects.filter(tags__0='thoughts')\n    <QuerySet [<Post: First post>, <Post: Second post>]>\n\n    >>> Post.objects.filter(tags__1__iexact='Django')\n    <QuerySet [<Post: First post>]>\n\n    >>> Post.objects.filter(tags__276='javascript')\n    <QuerySet []>\n\n.. note::\n\n    PostgreSQL uses 1-based indexing for array fields when writing raw SQL.\n    However these indexes and those used in :lookup:`slices <arrayfield.slice>`\n    use 0-based indexing to be consistent with Python.\n\n.. fieldlookup:: arrayfield.slice\n\nSlice transforms\n~~~~~~~~~~~~~~~~\n\nSlice transforms take a slice of the array. Any two non-negative integers can\nbe used, separated by a single underscore. The lookups available after the\ntransform do not change. For example::\n\n    >>> Post.objects.create(name='First post', tags=['thoughts', 'django'])\n    >>> Post.objects.create(name='Second post', tags=['thoughts'])\n    >>> Post.objects.create(name='Third post', tags=['django', 'python', 'thoughts'])\n\n    >>> Post.objects.filter(tags__0_1=['thoughts'])\n    <QuerySet [<Post: First post>, <Post: Second post>]>\n\n    >>> Post.objects.filter(tags__0_2__contains=['thoughts'])\n    <QuerySet [<Post: First post>, <Post: Second post>]>\n\n.. note::\n\n    PostgreSQL uses 1-based indexing for array fields when writing raw SQL.\n    However these slices and those used in :lookup:`indexes <arrayfield.index>`\n    use 0-based indexing to be consistent with Python.\n\n.. admonition:: Multidimensional arrays with indexes and slices\n\n    PostgreSQL has some rather esoteric behavior when using indexes and slices\n    on multidimensional arrays. It will always work to use indexes to reach\n    down to the final underlying data, but most other slices behave strangely\n    at the database level and cannot be supported in a logical, consistent\n    fashion by Django.\n\n``CIText`` fields\n=================\n\n.. class:: CIText(**options)\n\n    A mixin to create case-insensitive text fields backed by the citext_ type.\n    Read about `the performance considerations`_ prior to using it.\n\n    To use ``citext``, use the :class:`.CITextExtension` operation to\n    :ref:`setup the citext extension <create-postgresql-extensions>` in\n    PostgreSQL before the first ``CreateModel`` migration operation.\n\n    If you're using an :class:`~django.contrib.postgres.fields.ArrayField`\n    of ``CIText`` fields, you must add ``'django.contrib.postgres'`` in your\n    :setting:`INSTALLED_APPS`, otherwise field values will appear as strings\n    like ``'{thoughts,django}'``.\n\n    Several fields that use the mixin are provided:\n\n.. class:: CICharField(**options)\n.. class:: CIEmailField(**options)\n.. class:: CITextField(**options)\n\n    These fields subclass :class:`~django.db.models.CharField`,\n    :class:`~django.db.models.EmailField`, and\n    :class:`~django.db.models.TextField`, respectively.\n\n    ``max_length`` won't be enforced in the database since ``citext`` behaves\n    similar to PostgreSQL's ``text`` type.\n\n    .. _citext: https://www.postgresql.org/docs/current/citext.html\n    .. _the performance considerations: https://www.postgresql.org/docs/current/citext.html#id-1.11.7.17.7\n\n``HStoreField``\n===============\n\n.. class:: HStoreField(**options)\n\n    A field for storing key-value pairs. The Python data type used is a\n    ``dict``. Keys must be strings, and values may be either strings or nulls\n    (``None`` in Python).\n\n    To use this field, you'll need to:\n\n    #. Add ``'django.contrib.postgres'`` in your :setting:`INSTALLED_APPS`.\n    #. :ref:`Setup the hstore extension <create-postgresql-extensions>` in\n       PostgreSQL.\n\n    You'll see an error like ``can't adapt type 'dict'`` if you skip the first\n    step, or ``type \"hstore\" does not exist`` if you skip the second.\n\n.. note::\n\n    On occasions it may be useful to require or restrict the keys which are\n    valid for a given field. This can be done using the\n    :class:`~django.contrib.postgres.validators.KeysValidator`.\n\nQuerying ``HStoreField``\n------------------------\n\nIn addition to the ability to query by key, there are a number of custom\nlookups available for ``HStoreField``.\n\nWe will use the following example model::\n\n    from django.contrib.postgres.fields import HStoreField\n    from django.db import models\n\n    class Dog(models.Model):\n        name = models.CharField(max_length=200)\n        data = HStoreField()\n\n        def __str__(self):\n            return self.name\n\n.. fieldlookup:: hstorefield.key\n\nKey lookups\n~~~~~~~~~~~\n\nTo query based on a given key, you can use that key as the lookup name::\n\n    >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})\n    >>> Dog.objects.create(name='Meg', data={'breed': 'collie'})\n\n    >>> Dog.objects.filter(data__breed='collie')\n    <QuerySet [<Dog: Meg>]>\n\nYou can chain other lookups after key lookups::\n\n    >>> Dog.objects.filter(data__breed__contains='l')\n    <QuerySet [<Dog: Rufus>, <Dog: Meg>]>\n\nIf the key you wish to query by clashes with the name of another lookup, you\nneed to use the :lookup:`hstorefield.contains` lookup instead.\n\n.. warning::\n\n    Since any string could be a key in a hstore value, any lookup other than\n    those listed below will be interpreted as a key lookup. No errors are\n    raised. Be extra careful for typing mistakes, and always check your queries\n    work as you intend.\n\n.. fieldlookup:: hstorefield.contains\n\n``contains``\n~~~~~~~~~~~~\n\nThe :lookup:`contains` lookup is overridden on\n:class:`~django.contrib.postgres.fields.HStoreField`. The returned objects are\nthose where the given ``dict`` of key-value pairs are all contained in the\nfield. It uses the SQL operator ``@>``. For example::\n\n    >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador', 'owner': 'Bob'})\n    >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})\n    >>> Dog.objects.create(name='Fred', data={})\n\n    >>> Dog.objects.filter(data__contains={'owner': 'Bob'})\n    <QuerySet [<Dog: Rufus>, <Dog: Meg>]>\n\n    >>> Dog.objects.filter(data__contains={'breed': 'collie'})\n    <QuerySet [<Dog: Meg>]>\n\n.. fieldlookup:: hstorefield.contained_by\n\n``contained_by``\n~~~~~~~~~~~~~~~~\n\nThis is the inverse of the :lookup:`contains <hstorefield.contains>` lookup -\nthe objects returned will be those where the key-value pairs on the object are\na subset of those in the value passed. It uses the SQL operator ``<@``. For\nexample::\n\n    >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador', 'owner': 'Bob'})\n    >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})\n    >>> Dog.objects.create(name='Fred', data={})\n\n    >>> Dog.objects.filter(data__contained_by={'breed': 'collie', 'owner': 'Bob'})\n    <QuerySet [<Dog: Meg>, <Dog: Fred>]>\n\n    >>> Dog.objects.filter(data__contained_by={'breed': 'collie'})\n    <QuerySet [<Dog: Fred>]>\n\n.. fieldlookup:: hstorefield.has_key\n\n``has_key``\n~~~~~~~~~~~\n\nReturns objects where the given key is in the data. Uses the SQL operator\n``?``. For example::\n\n    >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})\n    >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})\n\n    >>> Dog.objects.filter(data__has_key='owner')\n    <QuerySet [<Dog: Meg>]>\n\n.. fieldlookup:: hstorefield.has_any_keys\n\n``has_any_keys``\n~~~~~~~~~~~~~~~~\n\nReturns objects where any of the given keys are in the data. Uses the SQL\noperator ``?|``. For example::\n\n    >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})\n    >>> Dog.objects.create(name='Meg', data={'owner': 'Bob'})\n    >>> Dog.objects.create(name='Fred', data={})\n\n    >>> Dog.objects.filter(data__has_any_keys=['owner', 'breed'])\n    <QuerySet [<Dog: Rufus>, <Dog: Meg>]>\n\n.. fieldlookup:: hstorefield.has_keys\n\n``has_keys``\n~~~~~~~~~~~~\n\nReturns objects where all of the given keys are in the data. Uses the SQL operator\n``?&``. For example::\n\n    >>> Dog.objects.create(name='Rufus', data={})\n    >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})\n\n    >>> Dog.objects.filter(data__has_keys=['breed', 'owner'])\n    <QuerySet [<Dog: Meg>]>\n\n.. fieldlookup:: hstorefield.keys\n\n``keys``\n~~~~~~~~\n\nReturns objects where the array of keys is the given value. Note that the order\nis not guaranteed to be reliable, so this transform is mainly useful for using\nin conjunction with lookups on\n:class:`~django.contrib.postgres.fields.ArrayField`. Uses the SQL function\n``akeys()``. For example::\n\n    >>> Dog.objects.create(name='Rufus', data={'toy': 'bone'})\n    >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})\n\n    >>> Dog.objects.filter(data__keys__overlap=['breed', 'toy'])\n    <QuerySet [<Dog: Rufus>, <Dog: Meg>]>\n\n.. fieldlookup:: hstorefield.values\n\n``values``\n~~~~~~~~~~\n\nReturns objects where the array of values is the given value. Note that the\norder is not guaranteed to be reliable, so this transform is mainly useful for\nusing in conjunction with lookups on\n:class:`~django.contrib.postgres.fields.ArrayField`. Uses the SQL function\n``avalues()``. For example::\n\n    >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})\n    >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})\n\n    >>> Dog.objects.filter(data__values__contains=['collie'])\n    <QuerySet [<Dog: Meg>]>\n\n``JSONField``\n=============\n\n.. class:: JSONField(encoder=None, **options)\n\n    A field for storing JSON encoded data. In Python the data is represented in\n    its Python native format: dictionaries, lists, strings, numbers, booleans\n    and ``None``.\n\n    .. attribute:: encoder\n\n        An optional JSON-encoding class to serialize data types not supported\n        by the standard JSON serializer (``datetime``, ``uuid``, etc.). For\n        example, you can use the\n        :class:`~django.core.serializers.json.DjangoJSONEncoder` class or any\n        other :py:class:`json.JSONEncoder` subclass.\n\n        When the value is retrieved from the database, it will be in the format\n        chosen by the custom encoder (most often a string), so you'll need to\n        take extra steps to convert the value back to the initial data type\n        (:meth:`Model.from_db() <django.db.models.Model.from_db>` and\n        :meth:`Field.from_db_value() <django.db.models.Field.from_db_value>`\n        are two possible hooks for that purpose). Your deserialization may need\n        to account for the fact that you can't be certain of the input type.\n        For example, you run the risk of returning a ``datetime`` that was\n        actually a string that just happened to be in the same format chosen\n        for ``datetime``\\s.\n\n    If you give the field a :attr:`~django.db.models.Field.default`, ensure\n    it's a callable such as ``dict`` (for an empty default) or a callable that\n    returns a dict (such as a function). Incorrectly using ``default={}``\n    creates a mutable default that is shared between all instances of\n    ``JSONField``.\n\n.. note::\n\n    PostgreSQL has two native JSON based data types: ``json`` and ``jsonb``.\n    The main difference between them is how they are stored and how they can be\n    queried. PostgreSQL's ``json`` field is stored as the original string\n    representation of the JSON and must be decoded on the fly when queried\n    based on keys. The ``jsonb`` field is stored based on the actual structure\n    of the JSON which allows indexing. The trade-off is a small additional cost\n    on writing to the ``jsonb`` field. ``JSONField`` uses ``jsonb``.\n\n.. deprecated:: 3.1\n\n    Use :class:`django.db.models.JSONField` instead.\n\nQuerying ``JSONField``\n----------------------\n\nSee :ref:`querying-jsonfield` for details.\n\n.. _range-fields:\n\nRange Fields\n============\n\nThere are five range field types, corresponding to the built-in range types in\nPostgreSQL. These fields are used to store a range of values; for example the\nstart and end timestamps of an event, or the range of ages an activity is\nsuitable for.\n\nAll of the range fields translate to :ref:`psycopg2 Range objects\n<psycopg2:adapt-range>` in Python, but also accept tuples as input if no bounds\ninformation is necessary. The default is lower bound included, upper bound\nexcluded, that is ``[)`` (see the PostgreSQL documentation for details about\n`different bounds`_).\n\n.. _different bounds: https://www.postgresql.org/docs/current/rangetypes.html#RANGETYPES-IO\n\n``IntegerRangeField``\n---------------------\n\n.. class:: IntegerRangeField(**options)\n\n    Stores a range of integers. Based on an\n    :class:`~django.db.models.IntegerField`. Represented by an ``int4range`` in\n    the database and a :class:`~psycopg2:psycopg2.extras.NumericRange` in\n    Python.\n\n    Regardless of the bounds specified when saving the data, PostgreSQL always\n    returns a range in a canonical form that includes the lower bound and\n    excludes the upper bound, that is ``[)``.\n\n``BigIntegerRangeField``\n------------------------\n\n.. class:: BigIntegerRangeField(**options)\n\n    Stores a range of large integers. Based on a\n    :class:`~django.db.models.BigIntegerField`. Represented by an ``int8range``\n    in the database and a :class:`~psycopg2:psycopg2.extras.NumericRange` in\n    Python.\n\n    Regardless of the bounds specified when saving the data, PostgreSQL always\n    returns a range in a canonical form that includes the lower bound and\n    excludes the upper bound, that is ``[)``.\n\n``DecimalRangeField``\n---------------------\n\n.. class:: DecimalRangeField(**options)\n\n    Stores a range of floating point values. Based on a\n    :class:`~django.db.models.DecimalField`. Represented by a ``numrange`` in\n    the database and a :class:`~psycopg2:psycopg2.extras.NumericRange` in\n    Python.\n\n``DateTimeRangeField``\n----------------------\n\n.. class:: DateTimeRangeField(**options)\n\n    Stores a range of timestamps. Based on a\n    :class:`~django.db.models.DateTimeField`. Represented by a ``tstzrange`` in\n    the database and a :class:`~psycopg2:psycopg2.extras.DateTimeTZRange` in\n    Python.\n\n``DateRangeField``\n------------------\n\n.. class:: DateRangeField(**options)\n\n    Stores a range of dates. Based on a\n    :class:`~django.db.models.DateField`. Represented by a ``daterange`` in the\n    database and a :class:`~psycopg2:psycopg2.extras.DateRange` in Python.\n\n    Regardless of the bounds specified when saving the data, PostgreSQL always\n    returns a range in a canonical form that includes the lower bound and\n    excludes the upper bound, that is ``[)``.\n\nQuerying Range Fields\n---------------------\n\nThere are a number of custom lookups and transforms for range fields. They are\navailable on all the above fields, but we will use the following example\nmodel::\n\n    from django.contrib.postgres.fields import IntegerRangeField\n    from django.db import models\n\n    class Event(models.Model):\n        name = models.CharField(max_length=200)\n        ages = IntegerRangeField()\n        start = models.DateTimeField()\n\n        def __str__(self):\n            return self.name\n\nWe will also use the following example objects::\n\n    >>> import datetime\n    >>> from django.utils import timezone\n    >>> now = timezone.now()\n    >>> Event.objects.create(name='Soft play', ages=(0, 10), start=now)\n    >>> Event.objects.create(name='Pub trip', ages=(21, None), start=now - datetime.timedelta(days=1))\n\nand ``NumericRange``:\n\n    >>> from psycopg2.extras import NumericRange\n\nContainment functions\n~~~~~~~~~~~~~~~~~~~~~\n\nAs with other PostgreSQL fields, there are three standard containment\noperators: ``contains``, ``contained_by`` and ``overlap``, using the SQL\noperators ``@>``, ``<@``, and ``&&`` respectively.\n\n.. fieldlookup:: rangefield.contains\n\n``contains``\n^^^^^^^^^^^^\n\n    >>> Event.objects.filter(ages__contains=NumericRange(4, 5))\n    <QuerySet [<Event: Soft play>]>\n\n.. fieldlookup:: rangefield.contained_by\n\n``contained_by``\n^^^^^^^^^^^^^^^^\n\n    >>> Event.objects.filter(ages__contained_by=NumericRange(0, 15))\n    <QuerySet [<Event: Soft play>]>\n\nThe ``contained_by`` lookup is also available on the non-range field types:\n:class:`~django.db.models.SmallAutoField`,\n:class:`~django.db.models.AutoField`, :class:`~django.db.models.BigAutoField`,\n:class:`~django.db.models.SmallIntegerField`,\n:class:`~django.db.models.IntegerField`,\n:class:`~django.db.models.BigIntegerField`,\n:class:`~django.db.models.DecimalField`, :class:`~django.db.models.FloatField`,\n:class:`~django.db.models.DateField`, and\n:class:`~django.db.models.DateTimeField`. For example::\n\n    >>> from psycopg2.extras import DateTimeTZRange\n    >>> Event.objects.filter(start__contained_by=DateTimeTZRange(\n    ...     timezone.now() - datetime.timedelta(hours=1),\n    ...     timezone.now() + datetime.timedelta(hours=1),\n    ... )\n    <QuerySet [<Event: Soft play>]>\n\n.. versionchanged:: 3.1\n\n    Support for :class:`~django.db.models.SmallAutoField`,\n    :class:`~django.db.models.AutoField`,\n    :class:`~django.db.models.BigAutoField`,\n    :class:`~django.db.models.SmallIntegerField`, and\n    :class:`~django.db.models.DecimalField` was added.\n\n.. fieldlookup:: rangefield.overlap\n\n``overlap``\n^^^^^^^^^^^\n\n    >>> Event.objects.filter(ages__overlap=NumericRange(8, 12))\n    <QuerySet [<Event: Soft play>]>\n\nComparison functions\n~~~~~~~~~~~~~~~~~~~~\n\nRange fields support the standard lookups: :lookup:`lt`, :lookup:`gt`,\n:lookup:`lte` and :lookup:`gte`. These are not particularly helpful - they\ncompare the lower bounds first and then the upper bounds only if necessary.\nThis is also the strategy used to order by a range field. It is better to use\nthe specific range comparison operators.\n\n.. fieldlookup:: rangefield.fully_lt\n\n``fully_lt``\n^^^^^^^^^^^^\n\nThe returned ranges are strictly less than the passed range. In other words,\nall the points in the returned range are less than all those in the passed\nrange.\n\n    >>> Event.objects.filter(ages__fully_lt=NumericRange(11, 15))\n    <QuerySet [<Event: Soft play>]>\n\n.. fieldlookup:: rangefield.fully_gt\n\n``fully_gt``\n^^^^^^^^^^^^\n\nThe returned ranges are strictly greater than the passed range. In other words,\nthe all the points in the returned range are greater than all those in the\npassed range.\n\n    >>> Event.objects.filter(ages__fully_gt=NumericRange(11, 15))\n    <QuerySet [<Event: Pub trip>]>\n\n.. fieldlookup:: rangefield.not_lt\n\n``not_lt``\n^^^^^^^^^^\n\nThe returned ranges do not contain any points less than the passed range, that\nis the lower bound of the returned range is at least the lower bound of the\npassed range.\n\n    >>> Event.objects.filter(ages__not_lt=NumericRange(0, 15))\n    <QuerySet [<Event: Soft play>, <Event: Pub trip>]>\n\n.. fieldlookup:: rangefield.not_gt\n\n``not_gt``\n^^^^^^^^^^\n\nThe returned ranges do not contain any points greater than the passed range, that\nis the upper bound of the returned range is at most the upper bound of the\npassed range.\n\n    >>> Event.objects.filter(ages__not_gt=NumericRange(3, 10))\n    <QuerySet [<Event: Soft play>]>\n\n.. fieldlookup:: rangefield.adjacent_to\n\n``adjacent_to``\n^^^^^^^^^^^^^^^\n\nThe returned ranges share a bound with the passed range.\n\n    >>> Event.objects.filter(ages__adjacent_to=NumericRange(10, 21))\n    <QuerySet [<Event: Soft play>, <Event: Pub trip>]>\n\nQuerying using the bounds\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThere are three transforms available for use in queries. You can extract the\nlower or upper bound, or query based on emptiness.\n\n.. fieldlookup:: rangefield.startswith\n\n``startswith``\n^^^^^^^^^^^^^^\n\nReturned objects have the given lower bound. Can be chained to valid lookups\nfor the base field.\n\n    >>> Event.objects.filter(ages__startswith=21)\n    <QuerySet [<Event: Pub trip>]>\n\n.. fieldlookup:: rangefield.endswith\n\n``endswith``\n^^^^^^^^^^^^\n\nReturned objects have the given upper bound. Can be chained to valid lookups\nfor the base field.\n\n    >>> Event.objects.filter(ages__endswith=10)\n    <QuerySet [<Event: Soft play>]>\n\n.. fieldlookup:: rangefield.isempty\n\n``isempty``\n^^^^^^^^^^^\n\nReturned objects are empty ranges. Can be chained to valid lookups for a\n:class:`~django.db.models.BooleanField`.\n\n    >>> Event.objects.filter(ages__isempty=True)\n    <QuerySet []>\n\n.. fieldlookup:: rangefield.lower_inc\n\n``lower_inc``\n^^^^^^^^^^^^^\n\n.. versionadded:: 3.1\n\nReturns objects that have inclusive or exclusive lower bounds, depending on the\nboolean value passed. Can be chained to valid lookups for a\n:class:`~django.db.models.BooleanField`.\n\n    >>> Event.objects.filter(ages__lower_inc=True)\n    <QuerySet [<Event: Soft play>, <Event: Pub trip>]>\n\n.. fieldlookup:: rangefield.lower_inf\n\n``lower_inf``\n^^^^^^^^^^^^^\n\n.. versionadded:: 3.1\n\nReturns objects that have unbounded (infinite) or bounded lower bound,\ndepending on the boolean value passed. Can be chained to valid lookups for a\n:class:`~django.db.models.BooleanField`.\n\n    >>> Event.objects.filter(ages__lower_inf=True)\n    <QuerySet []>\n\n.. fieldlookup:: rangefield.upper_inc\n\n``upper_inc``\n^^^^^^^^^^^^^\n\n.. versionadded:: 3.1\n\nReturns objects that have inclusive or exclusive upper bounds, depending on the\nboolean value passed. Can be chained to valid lookups for a\n:class:`~django.db.models.BooleanField`.\n\n    >>> Event.objects.filter(ages__upper_inc=True)\n    <QuerySet []>\n\n.. fieldlookup:: rangefield.upper_inf\n\n``upper_inf``\n^^^^^^^^^^^^^\n\n.. versionadded:: 3.1\n\nReturns objects that have unbounded (infinite) or bounded upper bound,\ndepending on the boolean value passed. Can be chained to valid lookups for a\n:class:`~django.db.models.BooleanField`.\n\n    >>> Event.objects.filter(ages__upper_inf=True)\n    <QuerySet [<Event: Pub trip>]>\n\nDefining your own range types\n-----------------------------\n\nPostgreSQL allows the definition of custom range types. Django's model and form\nfield implementations use base classes below, and psycopg2 provides a\n:func:`~psycopg2:psycopg2.extras.register_range` to allow use of custom range\ntypes.\n\n.. class:: RangeField(**options)\n\n    Base class for model range fields.\n\n    .. attribute:: base_field\n\n        The model field class to use.\n\n    .. attribute:: range_type\n\n        The psycopg2 range type to use.\n\n    .. attribute:: form_field\n\n        The form field class to use. Should be a subclass of\n        :class:`django.contrib.postgres.forms.BaseRangeField`.\n\n.. class:: django.contrib.postgres.forms.BaseRangeField\n\n    Base class for form range fields.\n\n    .. attribute:: base_field\n\n        The form field to use.\n\n    .. attribute:: range_type\n\n        The psycopg2 range type to use.\n\nRange operators\n---------------\n\n.. class:: RangeOperators\n\nPostgreSQL provides a set of SQL operators that can be used together with the\nrange data types (see `the PostgreSQL documentation for the full details of\nrange operators <https://www.postgresql.org/docs/current/\nfunctions-range.html#RANGE-OPERATORS-TABLE>`_). This class is meant as a\nconvenient method to avoid typos. The operator names overlap with the names of\ncorresponding lookups.\n\n.. code-block:: python\n\n    class RangeOperators:\n        EQUAL = '='\n        NOT_EQUAL = '<>'\n        CONTAINS = '@>'\n        CONTAINED_BY = '<@'\n        OVERLAPS = '&&'\n        FULLY_LT = '<<'\n        FULLY_GT = '>>'\n        NOT_LT = '&>'\n        NOT_GT = '&<'\n        ADJACENT_TO = '-|-'\n\nRangeBoundary() expressions\n---------------------------\n\n.. class:: RangeBoundary(inclusive_lower=True, inclusive_upper=False)\n\n    .. attribute:: inclusive_lower\n\n        If ``True`` (default), the lower bound is inclusive ``'['``, otherwise\n        it's exclusive ``'('``.\n\n    .. attribute:: inclusive_upper\n\n        If ``False`` (default), the upper bound is exclusive ``')'``, otherwise\n        it's inclusive ``']'``.\n\nA ``RangeBoundary()`` expression represents the range boundaries. It can be\nused with a custom range functions that expected boundaries, for example to\ndefine :class:`~django.contrib.postgres.constraints.ExclusionConstraint`. See\n`the PostgreSQL documentation for the full details <https://www.postgresql.org/\ndocs/current/rangetypes.html#RANGETYPES-INCLUSIVITY>`_.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":145,"nodeType":"TextFile","repoName":null,"name":"functions.txt","path":"docs/ref/contrib/gis","text":"=============================\nGeographic Database Functions\n=============================\n\n.. module:: django.contrib.gis.db.models.functions\n    :synopsis: Geographic Database Functions\n\nThe functions documented on this page allow users to access geographic database\nfunctions to be used in annotations, aggregations, or filters in Django.\n\nExample::\n\n    >>> from django.contrib.gis.db.models.functions import Length\n    >>> Track.objects.annotate(length=Length('line')).filter(length__gt=100)\n\nNot all backends support all functions, so refer to the documentation of each\nfunction to see if your database backend supports the function you want to use.\nIf you call a geographic function on a backend that doesn't support it, you'll\nget a ``NotImplementedError`` exception.\n\nFunction's summary:\n\n=========================  ========================  ======================  =======================  ==================  =====================\nMeasurement                Relationships             Operations              Editors                  Output format       Miscellaneous\n=========================  ========================  ======================  =======================  ==================  =====================\n:class:`Area`              :class:`Azimuth`          :class:`Difference`     :class:`ForcePolygonCW`  :class:`AsGeoJSON`  :class:`IsValid`\n:class:`Distance`          :class:`BoundingCircle`   :class:`Intersection`   :class:`MakeValid`       :class:`AsGML`      :class:`MemSize`\n:class:`GeometryDistance`  :class:`Centroid`         :class:`SymDifference`  :class:`Reverse`         :class:`AsKML`      :class:`NumGeometries`\n:class:`Length`            :class:`Envelope`         :class:`Union`          :class:`Scale`           :class:`AsSVG`      :class:`NumPoints`\n:class:`Perimeter`         :class:`LineLocatePoint`                          :class:`SnapToGrid`      :class:`AsWKB`\n..                         :class:`PointOnSurface`                           :class:`Transform`       :class:`AsWKT`\n..                                                                           :class:`Translate`       :class:`GeoHash`\n=========================  ========================  ======================  =======================  ==================  =====================\n\n``Area``\n========\n\n.. class:: Area(expression, **extra)\n\n*Availability*: MariaDB, `MySQL\n<https://dev.mysql.com/doc/refman/en/gis-polygon-property-functions.html#function_st-area>`_,\nOracle, `PostGIS <https://postgis.net/docs/ST_Area.html>`__, SpatiaLite\n\nAccepts a single geographic field or expression and returns the area of the\nfield as an :class:`~django.contrib.gis.measure.Area` measure.\n\nMySQL and SpatiaLite without LWGEOM don't support area calculations on\ngeographic SRSes.\n\n``AsGeoJSON``\n=============\n\n.. class:: AsGeoJSON(expression, bbox=False, crs=False, precision=8, **extra)\n\n*Availability*: MariaDB (≥ 10.2.4), `MySQL\n<https://dev.mysql.com/doc/refman/en/spatial-geojson-functions.html#function_st-asgeojson>`__ (≥ 5.7.5),\nOracle, `PostGIS <https://postgis.net/docs/ST_AsGeoJSON.html>`__, SpatiaLite\n\nAccepts a single geographic field or expression and returns a `GeoJSON\n<https://geojson.org/>`_ representation of the geometry. Note that the result\nis not a complete GeoJSON structure but only the ``geometry`` key content of a\nGeoJSON structure. See also :doc:`/ref/contrib/gis/serializers`.\n\nExample::\n\n    >>> City.objects.annotate(json=AsGeoJSON('point')).get(name='Chicago').json\n    {\"type\":\"Point\",\"coordinates\":[-87.65018,41.85039]}\n\n=====================  =====================================================\nKeyword Argument       Description\n=====================  =====================================================\n``bbox``               Set this to ``True`` if you want the bounding box\n                       to be included in the returned GeoJSON. Ignored on\n                       Oracle.\n\n``crs``                Set this to ``True`` if you want the coordinate\n                       reference system to be included in the returned\n                       GeoJSON. Ignored on MySQL and Oracle.\n\n``precision``          It may be used to specify the number of significant\n                       digits for the coordinates in the GeoJSON\n                       representation -- the default value is 8. Ignored on\n                       Oracle.\n=====================  =====================================================\n\n.. versionchanged:: 3.1\n\n    Oracle support was added.\n\n``AsGML``\n=========\n\n.. class:: AsGML(expression, version=2, precision=8, **extra)\n\n*Availability*: Oracle, `PostGIS <https://postgis.net/docs/ST_AsGML.html>`__,\nSpatiaLite\n\nAccepts a single geographic field or expression and returns a `Geographic Markup\nLanguage (GML)`__ representation of the geometry.\n\nExample::\n\n    >>> qs = Zipcode.objects.annotate(gml=AsGML('poly'))\n    >>> print(qs[0].gml)\n    <gml:Polygon srsName=\"EPSG:4326\"><gml:OuterBoundaryIs>-147.78711,70.245363 ...\n    -147.78711,70.245363</gml:OuterBoundaryIs></gml:Polygon>\n\n=====================  =====================================================\nKeyword Argument       Description\n=====================  =====================================================\n``precision``          Specifies the number of significant digits for the\n                       coordinates in the GML representation -- the default\n                       value is 8. Ignored on Oracle.\n\n``version``            Specifies the GML version to use: 2 (default) or 3.\n=====================  =====================================================\n\n__ https://en.wikipedia.org/wiki/Geography_Markup_Language\n\n``AsKML``\n=========\n\n.. class:: AsKML(expression, precision=8, **extra)\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_AsKML.html>`__, SpatiaLite\n\nAccepts a single geographic field or expression and returns a `Keyhole Markup\nLanguage (KML)`__ representation of the geometry.\n\nExample::\n\n    >>> qs = Zipcode.objects.annotate(kml=AsKML('poly'))\n    >>> print(qs[0].kml)\n    <Polygon><outerBoundaryIs><LinearRing><coordinates>-103.04135,36.217596,0 ...\n    -103.04135,36.217596,0</coordinates></LinearRing></outerBoundaryIs></Polygon>\n\n=====================  =====================================================\nKeyword Argument       Description\n=====================  =====================================================\n``precision``          This keyword may be used to specify the number of\n                       significant digits for the coordinates in the KML\n                       representation -- the default value is 8.\n=====================  =====================================================\n\n__ https://developers.google.com/kml/documentation/\n\n.. versionchanged:: 3.1\n\n    The undocumented ``version`` parameter was removed.\n\n``AsSVG``\n=========\n\n.. class:: AsSVG(expression, relative=False, precision=8, **extra)\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_AsSVG.html>`__, SpatiaLite\n\nAccepts a single geographic field or expression and returns a `Scalable Vector\nGraphics (SVG)`__ representation of the geometry.\n\n=====================  =====================================================\nKeyword Argument       Description\n=====================  =====================================================\n``relative``           If set to ``True``, the path data will be implemented\n                       in terms of relative moves. Defaults to ``False``,\n                       meaning that absolute moves are used instead.\n\n``precision``          This keyword may be used to specify the number of\n                       significant digits for the coordinates in the SVG\n                       representation -- the default value is 8.\n=====================  =====================================================\n\n__ https://www.w3.org/Graphics/SVG/\n\n``AsWKB``\n=========\n\n.. class:: AsWKB(expression, **extra)\n\n.. versionadded:: 3.1\n\n*Availability*: MariaDB, `MySQL\n<https://dev.mysql.com/doc/refman/en/gis-format-conversion-functions.html#function_st-asbinary>`__,\nOracle, `PostGIS <https://postgis.net/docs/ST_AsBinary.html>`__, SpatiaLite\n\nAccepts a single geographic field or expression and returns a `Well-known\nbinary (WKB)`__ representation of the geometry.\n\nExample::\n\n    >>> bytes(City.objects.annotate(wkb=AsWKB('point')).get(name='Chelyabinsk').wkb)\n    b'\\x01\\x01\\x00\\x00\\x00]3\\xf9f\\x9b\\x91K@\\x00X\\x1d9\\xd2\\xb9N@'\n\n__ https://en.wikipedia.org/wiki/Well-known_text_representation_of_geometry#Well-known_binary\n\n``AsWKT``\n=========\n\n.. class:: AsWKT(expression, **extra)\n\n.. versionadded:: 3.1\n\n*Availability*: MariaDB, `MySQL\n<https://dev.mysql.com/doc/refman/en/gis-format-conversion-functions.html#function_st-astext>`__,\nOracle, `PostGIS <https://postgis.net/docs/ST_AsText.html>`__, SpatiaLite\n\nAccepts a single geographic field or expression and returns a `Well-known text\n(WKT)`__ representation of the geometry.\n\nExample::\n\n    >>> City.objects.annotate(wkt=AsWKT('point')).get(name='Chelyabinsk').wkt\n    'POINT (55.137555 61.451728)'\n\n__ https://en.wikipedia.org/wiki/Well-known_text_representation_of_geometry\n\n``Azimuth``\n===========\n\n.. class:: Azimuth(point_a, point_b, **extra)\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Azimuth.html>`__,\nSpatiaLite (LWGEOM)\n\nReturns the azimuth in radians of the segment defined by the given point\ngeometries, or ``None`` if the two points are coincident. The azimuth is angle\nreferenced from north and is positive clockwise: north = ``0``; east = ``π/2``;\nsouth = ``π``; west = ``3π/2``.\n\n``BoundingCircle``\n==================\n\n.. class:: BoundingCircle(expression, num_seg=48, **extra)\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_MinimumBoundingCircle.html>`__,\n`Oracle <https://docs.oracle.com/en/database/oracle/oracle-database/18/spatl/\nSDO_GEOM-reference.html#GUID-82A61626-BB64-4793-B53D-A0DBEC91831A>`_\n\nAccepts a single geographic field or expression and returns the smallest circle\npolygon that can fully contain the geometry.\n\nThe ``num_seg`` parameter is used only on PostGIS.\n\n``Centroid``\n============\n\n.. class:: Centroid(expression, **extra)\n\n*Availability*: MariaDB, `MySQL\n<https://dev.mysql.com/doc/refman/en/gis-polygon-property-functions.html#function_st-centroid>`__,\n`PostGIS <https://postgis.net/docs/ST_Centroid.html>`__, Oracle, SpatiaLite\n\nAccepts a single geographic field or expression and returns the ``centroid``\nvalue of the geometry.\n\n``Difference``\n==============\n\n.. class:: Difference(expr1, expr2, **extra)\n\n*Availability*: MariaDB, `MySQL\n<https://dev.mysql.com/doc/refman/en/spatial-operator-functions.html#function_st-difference>`__,\n`PostGIS <https://postgis.net/docs/ST_Difference.html>`__, Oracle, SpatiaLite\n\nAccepts two geographic fields or expressions and returns the geometric\ndifference, that is the part of geometry A that does not intersect with\ngeometry B.\n\n``Distance``\n============\n\n.. class:: Distance(expr1, expr2, spheroid=None, **extra)\n\n*Availability*: MariaDB, `MySQL\n<https://dev.mysql.com/doc/refman/en/spatial-relation-functions-object-shapes.html#function_st-distance>`__,\n`PostGIS <https://postgis.net/docs/ST_Distance.html>`__, Oracle, SpatiaLite\n\nAccepts two geographic fields or expressions and returns the distance between\nthem, as a :class:`~django.contrib.gis.measure.Distance` object. On MySQL, a raw\nfloat value is returned when the coordinates are geodetic.\n\nOn backends that support distance calculation on geodetic coordinates, the\nproper backend function is automatically chosen depending on the SRID value of\nthe geometries (e.g. `ST_DistanceSphere\n<https://postgis.net/docs/ST_DistanceSphere.html>`__ on PostGIS).\n\nWhen distances are calculated with geodetic (angular) coordinates, as is the\ncase with the default WGS84 (4326) SRID, you can set the ``spheroid`` keyword\nargument to decide if the calculation should be based on a simple sphere (less\naccurate, less resource-intensive) or on a spheroid (more accurate, more\nresource-intensive).\n\nIn the following example, the distance from the city of Hobart to every other\n:class:`~django.contrib.gis.db.models.PointField` in the ``AustraliaCity``\nqueryset is calculated::\n\n    >>> from django.contrib.gis.db.models.functions import Distance\n    >>> pnt = AustraliaCity.objects.get(name='Hobart').point\n    >>> for city in AustraliaCity.objects.annotate(distance=Distance('point', pnt)):\n    ...     print(city.name, city.distance)\n    Wollongong 990071.220408 m\n    Shellharbour 972804.613941 m\n    Thirroul 1002334.36351 m\n    ...\n\n.. note::\n\n    Because the ``distance`` attribute is a\n    :class:`~django.contrib.gis.measure.Distance` object, you can easily express\n    the value in the units of your choice. For example, ``city.distance.mi`` is\n    the distance value in miles and ``city.distance.km`` is the distance value\n    in kilometers. See :doc:`measure` for usage details and the list of\n    :ref:`supported_units`.\n\n``Envelope``\n============\n\n.. class:: Envelope(expression, **extra)\n\n*Availability*: MariaDB, `MySQL\n<https://dev.mysql.com/doc/refman/en/gis-general-property-functions.html#function_st-envelope>`__,\n`Oracle <https://docs.oracle.com/en/database/oracle/oracle-database/18/spatl/\nSDO_GEOM-reference.html#GUID-646638D0-2C5F-490A-AF63-DE9B7A4C97C1__CHDJCEIH>`__,\n`PostGIS <https://postgis.net/docs/ST_Envelope.html>`__, SpatiaLite\n\nAccepts a single geographic field or expression and returns the geometry\nrepresenting the bounding box of the geometry.\n\n``ForcePolygonCW``\n==================\n\n.. class:: ForcePolygonCW(expression, **extra)\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_ForcePolygonCW.html>`__,\nSpatiaLite\n\nAccepts a single geographic field or expression and returns a modified version\nof the polygon/multipolygon in which all exterior rings are oriented clockwise\nand all interior rings are oriented counterclockwise. Non-polygonal geometries\nare returned unchanged.\n\n``GeoHash``\n===========\n\n.. class:: GeoHash(expression, precision=None, **extra)\n\n*Availability*: `MySQL\n<https://dev.mysql.com/doc/refman/en/spatial-geohash-functions.html#function_st-geohash>`__ (≥ 5.7.5),\n`PostGIS <https://postgis.net/docs/ST_GeoHash.html>`__, SpatiaLite (LWGEOM)\n\nAccepts a single geographic field or expression and returns a `GeoHash`__\nrepresentation of the geometry.\n\nThe ``precision`` keyword argument controls the number of characters in the\nresult.\n\n__ https://en.wikipedia.org/wiki/Geohash\n\n``GeometryDistance``\n====================\n\n.. class:: GeometryDistance(expr1, expr2, **extra)\n\n*Availability*: `PostGIS <https://postgis.net/docs/geometry_distance_knn.html>`__\n\nAccepts two geographic fields or expressions and returns the distance between\nthem. When used in an :meth:`~django.db.models.query.QuerySet.order_by` clause,\nit provides index-assisted nearest-neighbor result sets.\n\n``Intersection``\n================\n\n.. class:: Intersection(expr1, expr2, **extra)\n\n*Availability*: MariaDB, `MySQL\n<https://dev.mysql.com/doc/refman/en/spatial-operator-functions.html#function_st-intersection>`__,\n`PostGIS <https://postgis.net/docs/ST_Intersection.html>`__, Oracle, SpatiaLite\n\nAccepts two geographic fields or expressions and returns the geometric\nintersection between them.\n\n``IsValid``\n===========\n\n.. class:: IsValid(expr)\n\n*Availability*: `MySQL\n<https://dev.mysql.com/doc/refman/en/spatial-convenience-functions.html#function_st-isvalid>`__ (≥ 5.7.5),\n`PostGIS <https://postgis.net/docs/ST_IsValid.html>`__, Oracle, SpatiaLite (LWGEOM)\n\nAccepts a geographic field or expression and tests if the value is well formed.\nReturns ``True`` if its value is a valid geometry and ``False`` otherwise.\n\n``Length``\n==========\n\n.. class:: Length(expression, spheroid=True, **extra)\n\n*Availability*: MariaDB, `MySQL\n<https://dev.mysql.com/doc/refman/en/gis-linestring-property-functions.html#function_st-length>`__,\nOracle, `PostGIS <https://postgis.net/docs/ST_Length.html>`__, SpatiaLite\n\nAccepts a single geographic linestring or multilinestring field or expression\nand returns its length as a :class:`~django.contrib.gis.measure.Distance`\nmeasure.\n\nOn PostGIS and SpatiaLite, when the coordinates are geodetic (angular), you can\nspecify if the calculation should be based on a simple sphere (less\naccurate, less resource-intensive) or on a spheroid (more accurate, more\nresource-intensive) with the ``spheroid`` keyword argument.\n\nMySQL doesn't support length calculations on geographic SRSes.\n\n``LineLocatePoint``\n===================\n\n.. class:: LineLocatePoint(linestring, point, **extra)\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_LineLocatePoint.html>`__,\nSpatiaLite\n\nReturns a float between 0 and 1 representing the location of the closest point on\n``linestring`` to the given ``point``, as a fraction of the 2D line length.\n\n``MakeValid``\n=============\n\n.. class:: MakeValid(expr)\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_MakeValid.html>`__,\nSpatiaLite (LWGEOM)\n\nAccepts a geographic field or expression and attempts to convert the value into\na valid geometry without losing any of the input vertices. Geometries that are\nalready valid are returned without changes. Simple polygons might become a\nmultipolygon and the result might be of lower dimension than the input.\n\n``MemSize``\n===========\n\n.. class:: MemSize(expression, **extra)\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_MemSize.html>`__\n\nAccepts a single geographic field or expression and returns the memory size\n(number of bytes) that the geometry field takes.\n\n``NumGeometries``\n=================\n\n.. class:: NumGeometries(expression, **extra)\n\n*Availability*: MariaDB, `MySQL\n<https://dev.mysql.com/doc/refman/en/gis-geometrycollection-property-functions.html#function_st-numgeometries>`__,\n`PostGIS <https://postgis.net/docs/ST_NumGeometries.html>`__, Oracle,\nSpatiaLite\n\nAccepts a single geographic field or expression and returns the number of\ngeometries if the geometry field is a collection (e.g., a ``GEOMETRYCOLLECTION``\nor ``MULTI*`` field). Returns 1 for single geometries.\n\nOn MySQL, returns ``None`` for single geometries.\n\n``NumPoints``\n=============\n\n.. class:: NumPoints(expression, **extra)\n\n*Availability*: MariaDB, `MySQL\n<https://dev.mysql.com/doc/refman/en/gis-linestring-property-functions.html#function_st-numpoints>`__,\n`PostGIS <https://postgis.net/docs/ST_NPoints.html>`__, Oracle, SpatiaLite\n\nAccepts a single geographic field or expression and returns the number of points\nin a geometry.\n\nOn MySQL, returns ``None`` for any non-``LINESTRING`` geometry.\n\n``Perimeter``\n=============\n\n.. class:: Perimeter(expression, **extra)\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Perimeter.html>`__,\nOracle, SpatiaLite\n\nAccepts a single geographic field or expression and returns the perimeter of the\ngeometry field as a :class:`~django.contrib.gis.measure.Distance` object.\n\n``PointOnSurface``\n==================\n\n.. class:: PointOnSurface(expression, **extra)\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_PointOnSurface.html>`__,\nMariaDB, Oracle, SpatiaLite\n\nAccepts a single geographic field or expression and returns a ``Point`` geometry\nguaranteed to lie on the surface of the field; otherwise returns ``None``.\n\n``Reverse``\n===========\n\n.. class:: Reverse(expression, **extra)\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Reverse.html>`__, Oracle,\nSpatiaLite\n\nAccepts a single geographic field or expression and returns a geometry with\nreversed coordinates.\n\n``Scale``\n=========\n\n.. class:: Scale(expression, x, y, z=0.0, **extra)\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Scale.html>`__, SpatiaLite\n\nAccepts a single geographic field or expression and returns a geometry with\nscaled coordinates by multiplying them with the ``x``, ``y``, and optionally\n``z`` parameters.\n\n``SnapToGrid``\n==============\n\n.. class:: SnapToGrid(expression, *args, **extra)\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_SnapToGrid.html>`__,\nSpatiaLite\n\nAccepts a single geographic field or expression and returns a geometry with all\npoints snapped to the given grid.  How the geometry is snapped to the grid\ndepends on how many numeric (either float, integer, or long) arguments are\ngiven.\n\n===================  =====================================================\nNumber of Arguments  Description\n===================  =====================================================\n1                    A single size to snap both the X and Y grids to.\n2                    X and Y sizes to snap the grid to.\n4                    X, Y sizes and the corresponding X, Y origins.\n===================  =====================================================\n\n``SymDifference``\n=================\n\n.. class:: SymDifference(expr1, expr2, **extra)\n\n*Availability*: MariaDB, `MySQL\n<https://dev.mysql.com/doc/refman/en/spatial-operator-functions.html#function_st-symdifference>`__,\n`PostGIS <https://postgis.net/docs/ST_SymDifference.html>`__, Oracle,\nSpatiaLite\n\nAccepts two geographic fields or expressions and returns the geometric\nsymmetric difference (union without the intersection) between the given\nparameters.\n\n``Transform``\n=============\n\n.. class:: Transform(expression, srid, **extra)\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Transform.html>`__,\nOracle, SpatiaLite\n\nAccepts a geographic field or expression and a SRID integer code, and returns\nthe transformed geometry to the spatial reference system specified by the\n``srid`` parameter.\n\n.. note::\n\n    What spatial reference system an integer SRID corresponds to may depend on\n    the spatial database used.  In other words, the SRID numbers used for Oracle\n    are not necessarily the same as those used by PostGIS.\n\n``Translate``\n=============\n\n.. class:: Translate(expression, x, y, z=0.0, **extra)\n\n*Availability*: `PostGIS <https://postgis.net/docs/ST_Translate.html>`__,\nSpatiaLite\n\nAccepts a single geographic field or expression and returns a geometry with\nits coordinates offset by the ``x``, ``y``, and optionally ``z`` numeric\nparameters.\n\n``Union``\n=========\n\n.. class:: Union(expr1, expr2, **extra)\n\n*Availability*: MariaDB, `MySQL\n<https://dev.mysql.com/doc/refman/en/spatial-operator-functions.html#function_st-union>`__,\n`PostGIS <https://postgis.net/docs/ST_Union.html>`__, Oracle, SpatiaLite\n\nAccepts two geographic fields or expressions and returns the union of both\ngeometries.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":146,"nodeType":"TextFile","repoName":null,"name":"geolibs.txt","path":"docs/ref/contrib/gis/install","text":"===============================\nInstalling Geospatial libraries\n===============================\n\nGeoDjango uses and/or provides interfaces for the following open source\ngeospatial libraries:\n\n========================  ====================================  ================================  ===================================\nProgram                   Description                           Required                          Supported Versions\n========================  ====================================  ================================  ===================================\n:doc:`GEOS <../geos>`     Geometry Engine Open Source           Yes                               3.8, 3.7, 3.6, 3.5\n`PROJ`_                   Cartographic Projections library      Yes (PostgreSQL and SQLite only)  6.x, 5.x, 4.x\n:doc:`GDAL <../gdal>`     Geospatial Data Abstraction Library   Yes                               3.1, 3.0, 2.4, 2.3, 2.2, 2.1, 2.0\n:doc:`GeoIP <../geoip2>`  IP-based geolocation library          No                                2\n`PostGIS`__               Spatial extensions for PostgreSQL     Yes (PostgreSQL only)             3.0, 2.5, 2.4, 2.3\n`SpatiaLite`__            Spatial extensions for SQLite         Yes (SQLite only)                 4.3\n========================  ====================================  ================================  ===================================\n\nNote that older or more recent versions of these libraries *may* also work\ntotally fine with GeoDjango. Your mileage may vary.\n\n..\n    Libs release dates:\n    GEOS 3.5.0 2015-08-15\n    GEOS 3.6.0 2016-10-25\n    GEOS 3.7.0 2018-09-10\n    GEOS 3.8.0 2019-10-10\n    GDAL 2.0.0 2015-06\n    GDAL 2.1.0 2016-04\n    GDAL 2.2.0 2017-05\n    GDAL 2.3.0 2018-05\n    GDAL 2.4.0 2018-12\n    GDAL 3.0.0 2019-05\n    GDAL 3.1.0 2020-05-07\n    PostGIS 2.3.0 2016-09-26\n    PostGIS 2.4.0 2017-09-30\n    PostGIS 2.5.0 2018-09-23\n    PostGIS 3.0.0 2019-10-20\n    SpatiaLite 4.3.0 2015-09-07\n\n.. note::\n\n    The GeoDjango interfaces to GEOS, GDAL, and GeoIP may be used\n    independently of Django.  In other words, no database or settings file\n    required -- import them as normal from :mod:`django.contrib.gis`.\n\n.. _PROJ: https://proj.org/\n__ https://postgis.net/\n__ https://www.gaia-gis.it/gaia-sins/\n\n\nOn Debian/Ubuntu, you are advised to install the following packages which will\ninstall, directly or by dependency, the required geospatial libraries:\n\n.. code-block:: console\n\n    $ sudo apt-get install binutils libproj-dev gdal-bin\n\nPlease also consult platform-specific instructions if you are on :ref:`macos`\nor :ref:`windows`.\n\n.. _build_from_source:\n\nBuilding from source\n====================\n\nWhen installing from source on UNIX and GNU/Linux systems, please follow\nthe installation instructions carefully, and install the libraries in the\ngiven order.  If using MySQL or Oracle as the spatial database, only GEOS\nis required.\n\n.. note::\n\n    On Linux platforms, it may be necessary to run the ``ldconfig`` command\n    after installing each library. For example::\n\n        $ sudo make install\n        $ sudo ldconfig\n\n.. note::\n\n    macOS users must install `Xcode`_ in order to compile software from source.\n\n.. _Xcode: https://developer.apple.com/xcode/\n\n.. _geosbuild:\n\nGEOS\n----\n\nGEOS is a C++ library for performing geometric operations, and is the default\ninternal geometry representation used by GeoDjango (it's behind the \"lazy\"\ngeometries).  Specifically, the C API library is called (e.g., ``libgeos_c.so``)\ndirectly from Python using ctypes.\n\nFirst, download GEOS from the GEOS website and untar the source archive::\n\n    $ wget https://download.osgeo.org/geos/geos-X.Y.Z.tar.bz2\n    $ tar xjf geos-X.Y.Z.tar.bz2\n\nNext, change into the directory where GEOS was unpacked, run the configure\nscript, compile, and install::\n\n    $ cd geos-X.Y.Z\n    $ ./configure\n    $ make\n    $ sudo make install\n    $ cd ..\n\nTroubleshooting\n~~~~~~~~~~~~~~~\n\nCan't find GEOS library\n^^^^^^^^^^^^^^^^^^^^^^^\n\nWhen GeoDjango can't find GEOS, this error is raised:\n\n.. code-block:: text\n\n    ImportError: Could not find the GEOS library (tried \"geos_c\"). Try setting GEOS_LIBRARY_PATH in your settings.\n\nThe most common solution is to properly configure your :ref:`libsettings` *or* set\n:ref:`geoslibrarypath` in your settings.\n\nIf using a binary package of GEOS (e.g., on Ubuntu), you may need to :ref:`binutils`.\n\n.. _geoslibrarypath:\n\n``GEOS_LIBRARY_PATH``\n^^^^^^^^^^^^^^^^^^^^^\n\nIf your GEOS library is in a non-standard location, or you don't want to\nmodify the system's library path then the :setting:`GEOS_LIBRARY_PATH`\nsetting may be added to your Django settings file with the full path to the\nGEOS C library.  For example::\n\n    GEOS_LIBRARY_PATH = '/home/bob/local/lib/libgeos_c.so'\n\n.. note::\n\n    The setting must be the *full* path to the **C** shared library; in\n    other words you want to use ``libgeos_c.so``, not ``libgeos.so``.\n\nSee also :ref:`My logs are filled with GEOS-related errors <geos-exceptions-in-logfile>`.\n\n.. _proj4:\n\nPROJ\n----\n\n`PROJ`_ is a library for converting geospatial data to different coordinate\nreference systems.\n\nFirst, download the PROJ source code and datum shifting files [#]_::\n\n    $ wget https://download.osgeo.org/proj/proj-X.Y.Z.tar.gz\n    $ wget https://download.osgeo.org/proj/proj-datumgrid-X.Y.tar.gz\n\nNext, untar the source code archive, and extract the datum shifting files in the\n``nad`` subdirectory.  This must be done *prior* to configuration::\n\n    $ tar xzf proj-X.Y.Z.tar.gz\n    $ cd proj-X.Y.Z/nad\n    $ tar xzf ../../proj-datumgrid-X.Y.tar.gz\n    $ cd ..\n\nFinally, configure, make and install PROJ::\n\n    $ ./configure\n    $ make\n    $ sudo make install\n    $ cd ..\n\n.. _gdalbuild:\n\nGDAL\n----\n\n`GDAL`__ is an excellent open source geospatial library that has support for\nreading most vector and raster spatial data formats.  Currently, GeoDjango only\nsupports :doc:`GDAL's vector data <../gdal>` capabilities [#]_.\n:ref:`geosbuild` and :ref:`proj4` should be installed prior to building GDAL.\n\nFirst download the latest GDAL release version and untar the archive::\n\n    $ wget https://download.osgeo.org/gdal/X.Y.Z/gdal-X.Y.Z.tar.gz\n    $ tar xzf gdal-X.Y.Z.tar.gz\n    $ cd gdal-X.Y.Z\n\nConfigure, make and install::\n\n    $ ./configure\n    $ make # Go get some coffee, this takes a while.\n    $ sudo make install\n    $ cd ..\n\n.. note::\n\n    Because GeoDjango has its own Python interface, the preceding instructions\n    do not build GDAL's own Python bindings. The bindings may be built by\n    adding the ``--with-python`` flag when running ``configure``. See\n    `GDAL/OGR In Python`__ for more information on GDAL's bindings.\n\nIf you have any problems, please see the troubleshooting section below for\nsuggestions and solutions.\n\n__ https://trac.osgeo.org/gdal/\n__ https://trac.osgeo.org/gdal/wiki/GdalOgrInPython\n\n.. _gdaltrouble:\n\nTroubleshooting\n~~~~~~~~~~~~~~~\n\nCan't find GDAL library\n^^^^^^^^^^^^^^^^^^^^^^^\n\nWhen GeoDjango can't find the GDAL library, configure your :ref:`libsettings`\n*or* set :ref:`gdallibrarypath` in your settings.\n\n.. _gdallibrarypath:\n\n``GDAL_LIBRARY_PATH``\n^^^^^^^^^^^^^^^^^^^^^\n\nIf your GDAL library is in a non-standard location, or you don't want to\nmodify the system's library path then the :setting:`GDAL_LIBRARY_PATH`\nsetting may be added to your Django settings file with the full path to\nthe GDAL library.  For example::\n\n    GDAL_LIBRARY_PATH = '/home/sue/local/lib/libgdal.so'\n\n.. rubric:: Footnotes\n.. [#] The datum shifting files are needed for converting data to and from\n       certain projections.\n       For example, the PROJ string for the `Google projection (900913 or 3857)\n       <https://spatialreference.org/ref/sr-org/6864/prj/>`_ requires the\n       ``null`` grid file only included in the extra datum shifting files.\n       It is easier to install the shifting files now, then to have debug a\n       problem caused by their absence later.\n.. [#] Specifically, GeoDjango provides support for the `OGR\n       <https://gdal.org/user/vector_data_model.html>`_ library, a component of\n       GDAL.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":147,"nodeType":"TextFile","repoName":null,"name":"gdal.txt","path":"docs/ref/contrib/gis","text":"========\nGDAL API\n========\n\n.. module:: django.contrib.gis.gdal\n    :synopsis: GeoDjango's high-level interface to the GDAL library.\n\n`GDAL`__ stands for **Geospatial Data Abstraction Library**,\nand is a veritable \"Swiss army knife\" of GIS data functionality.  A subset\nof GDAL is the `OGR`__ Simple Features Library, which specializes\nin reading and writing vector geographic data in a variety of standard\nformats.\n\nGeoDjango provides a high-level Python interface for some of the\ncapabilities of OGR, including the reading and coordinate transformation\nof vector spatial data and minimal support for GDAL's features with respect\nto raster (image) data.\n\n.. note::\n\n    Although the module is named ``gdal``, GeoDjango only supports some of the\n    capabilities of OGR and GDAL's raster features at this time.\n\n__ https://www.gdal.org/\n__ https://gdal.org/user/vector_data_model.html\n\nOverview\n========\n\n.. _gdal_sample_data:\n\nSample Data\n-----------\n\nThe GDAL/OGR tools described here are designed to help you read in\nyour geospatial data, in order for most of them to be useful you have\nto have some data to work with.  If you're starting out and don't yet\nhave any data of your own to use, GeoDjango tests contain a number of\ndata sets that you can use for testing. You can download them here::\n\n    $ wget https://raw.githubusercontent.com/django/django/master/tests/gis_tests/data/cities/cities.{shp,prj,shx,dbf}\n    $ wget https://raw.githubusercontent.com/django/django/master/tests/gis_tests/data/rasters/raster.tif\n\nVector Data Source Objects\n==========================\n\n``DataSource``\n--------------\n\n:class:`DataSource` is a wrapper for the OGR data source object that\nsupports reading data from a variety of OGR-supported geospatial file\nformats and data sources using a consistent interface.  Each\ndata source is represented by a :class:`DataSource` object which contains\none or more layers of data.  Each layer, represented by a :class:`Layer`\nobject, contains some number of geographic features (:class:`Feature`),\ninformation about the type of features contained in that layer (e.g.\npoints, polygons, etc.), as well as the names and types of any\nadditional fields (:class:`Field`) of data that may be associated with\neach feature in that layer.\n\n.. class:: DataSource(ds_input, encoding='utf-8')\n\n    The constructor for ``DataSource`` only requires one parameter: the path of\n    the file you want to read. However, OGR also supports a variety of more\n    complex data sources, including databases, that may be accessed by passing\n    a special name string instead of a path. For more information, see the\n    `OGR Vector Formats`__ documentation. The :attr:`name` property of a\n    ``DataSource`` instance gives the OGR name of the underlying data source\n    that it is using.\n\n    The optional ``encoding`` parameter allows you to specify a non-standard\n    encoding of the strings in the source. This is typically useful when you\n    obtain ``DjangoUnicodeDecodeError`` exceptions while reading field values.\n\n    Once you've created your ``DataSource``, you can find out how many layers\n    of data it contains by accessing the :attr:`layer_count` property, or\n    (equivalently) by using the ``len()`` function. For information on\n    accessing the layers of data themselves, see the next section::\n\n        >>> from django.contrib.gis.gdal import DataSource\n        >>> ds = DataSource('/path/to/your/cities.shp')\n        >>> ds.name\n        '/path/to/your/cities.shp'\n        >>> ds.layer_count                  # This file only contains one layer\n        1\n\n    .. attribute:: layer_count\n\n    Returns the number of layers in the data source.\n\n    .. attribute:: name\n\n    Returns the name of the data source.\n\n__ https://gdal.org/drivers/vector/\n\n``Layer``\n---------\n\n.. class:: Layer\n\n    ``Layer`` is a wrapper for a layer of data in a ``DataSource`` object. You\n    never create a ``Layer`` object directly. Instead, you retrieve them from\n    a :class:`DataSource` object, which is essentially a standard Python\n    container of ``Layer`` objects. For example, you can access a specific\n    layer by its index (e.g. ``ds[0]`` to access the first layer), or you can\n    iterate over all the layers in the container in a ``for`` loop. The\n    ``Layer`` itself acts as a container for geometric features.\n\n    Typically, all the features in a given layer have the same geometry type.\n    The :attr:`geom_type` property of a layer is an :class:`OGRGeomType` that\n    identifies the feature type. We can use it to print out some basic\n    information about each layer in a :class:`DataSource`::\n\n        >>> for layer in ds:\n        ...     print('Layer \"%s\": %i %ss' % (layer.name, len(layer), layer.geom_type.name))\n        ...\n        Layer \"cities\": 3 Points\n\n    The example output is from the cities data source, loaded above, which\n    evidently contains one layer, called ``\"cities\"``, which contains three\n    point features. For simplicity, the examples below assume that you've\n    stored that layer in the variable ``layer``::\n\n        >>> layer = ds[0]\n\n    .. attribute:: name\n\n    Returns the name of this layer in the data source.\n\n        >>> layer.name\n        'cities'\n\n    .. attribute:: num_feat\n\n    Returns the number of features in the layer. Same as ``len(layer)``::\n\n        >>> layer.num_feat\n        3\n\n    .. attribute:: geom_type\n\n    Returns the geometry type of the layer, as an :class:`OGRGeomType` object::\n\n        >>> layer.geom_type.name\n        'Point'\n\n    .. attribute:: num_fields\n\n    Returns the number of fields in the layer, i.e the number of fields of\n    data associated with each feature in the layer::\n\n        >>> layer.num_fields\n        4\n\n    .. attribute:: fields\n\n    Returns a list of the names of each of the fields in this layer::\n\n        >>> layer.fields\n        ['Name', 'Population', 'Density', 'Created']\n\n    .. attribute field_types\n\n    Returns a list of the data types of each of the fields in this layer. These\n    are subclasses of ``Field``, discussed below::\n\n        >>> [ft.__name__ for ft in layer.field_types]\n        ['OFTString', 'OFTReal', 'OFTReal', 'OFTDate']\n\n    .. attribute:: field_widths\n\n    Returns a list of the maximum field widths for each of the fields in this\n    layer::\n\n        >>> layer.field_widths\n        [80, 11, 24, 10]\n\n    .. attribute:: field_precisions\n\n    Returns a list of the numeric precisions for each of the fields in this\n    layer. This is meaningless (and set to zero) for non-numeric fields::\n\n        >>> layer.field_precisions\n        [0, 0, 15, 0]\n\n    .. attribute:: extent\n\n    Returns the spatial extent of this layer, as an :class:`Envelope` object::\n\n        >>> layer.extent.tuple\n        (-104.609252, 29.763374, -95.23506, 38.971823)\n\n    .. attribute:: srs\n\n    Property that returns the :class:`SpatialReference` associated with this\n    layer::\n\n        >>> print(layer.srs)\n        GEOGCS[\"GCS_WGS_1984\",\n            DATUM[\"WGS_1984\",\n                SPHEROID[\"WGS_1984\",6378137,298.257223563]],\n            PRIMEM[\"Greenwich\",0],\n            UNIT[\"Degree\",0.017453292519943295]]\n\n    If the :class:`Layer` has no spatial reference information associated\n    with it, ``None`` is returned.\n\n    .. attribute:: spatial_filter\n\n    Property that may be used to retrieve or set a spatial filter for this\n    layer. A spatial filter can only be set with an :class:`OGRGeometry`\n    instance, a 4-tuple extent, or ``None``. When set with something other than\n    ``None``, only features that intersect the filter will be returned when\n    iterating over the layer::\n\n        >>> print(layer.spatial_filter)\n        None\n        >>> print(len(layer))\n        3\n        >>> [feat.get('Name') for feat in layer]\n        ['Pueblo', 'Lawrence', 'Houston']\n        >>> ks_extent = (-102.051, 36.99, -94.59, 40.00) # Extent for state of Kansas\n        >>> layer.spatial_filter = ks_extent\n        >>> len(layer)\n        1\n        >>> [feat.get('Name') for feat in layer]\n        ['Lawrence']\n        >>> layer.spatial_filter = None\n        >>> len(layer)\n        3\n\n    .. method:: get_fields()\n\n    A method that returns a list of the values of a given field for each\n    feature in the layer::\n\n        >>> layer.get_fields('Name')\n        ['Pueblo', 'Lawrence', 'Houston']\n\n    .. method:: get_geoms(geos=False)\n\n    A method that returns a list containing the geometry of each feature in the\n    layer. If the optional argument ``geos`` is set to ``True`` then the\n    geometries are converted to :class:`~django.contrib.gis.geos.GEOSGeometry`\n    objects. Otherwise, they are returned as :class:`OGRGeometry` objects::\n\n        >>> [pt.tuple for pt in layer.get_geoms()]\n        [(-104.609252, 38.255001), (-95.23506, 38.971823), (-95.363151, 29.763374)]\n\n    .. method:: test_capability(capability)\n\n    Returns a boolean indicating whether this layer supports the given\n    capability (a string).  Examples of valid capability strings include:\n    ``'RandomRead'``, ``'SequentialWrite'``, ``'RandomWrite'``,\n    ``'FastSpatialFilter'``, ``'FastFeatureCount'``, ``'FastGetExtent'``,\n    ``'CreateField'``, ``'Transactions'``, ``'DeleteFeature'``, and\n    ``'FastSetNextByIndex'``.\n\n``Feature``\n-----------\n\n.. class:: Feature\n\n    ``Feature`` wraps an OGR feature. You never create a ``Feature`` object\n    directly. Instead, you retrieve them from a :class:`Layer` object. Each\n    feature consists of a geometry and a set of fields containing additional\n    properties. The geometry of a field is accessible via its ``geom`` property,\n    which returns an :class:`OGRGeometry` object. A ``Feature`` behaves like a\n    standard Python container for its fields, which it returns as :class:`Field`\n    objects: you can access a field directly by its index or name, or you can\n    iterate over a feature's fields, e.g. in a ``for`` loop.\n\n    .. attribute:: geom\n\n    Returns the geometry for this feature, as an ``OGRGeometry`` object::\n\n        >>> city.geom.tuple\n        (-104.609252, 38.255001)\n\n    .. attribute:: get\n\n    A method that returns the value of the given field (specified by name)\n    for this feature, **not** a ``Field`` wrapper object::\n\n        >>> city.get('Population')\n        102121\n\n    .. attribute:: geom_type\n\n    Returns the type of geometry for this feature, as an :class:`OGRGeomType`\n    object. This will be the same for all features in a given layer and is\n    equivalent to the :attr:`Layer.geom_type` property of the :class:`Layer`\n    object the feature came from.\n\n    .. attribute:: num_fields\n\n    Returns the number of fields of data associated with the feature. This will\n    be the same for all features in a given layer and is equivalent to the\n    :attr:`Layer.num_fields` property of the :class:`Layer` object the feature\n    came from.\n\n    .. attribute:: fields\n\n    Returns a list of the names of the fields of data associated with the\n    feature. This will be the same for all features in a given layer and is\n    equivalent to the :attr:`Layer.fields` property of the :class:`Layer`\n    object the feature came from.\n\n    .. attribute:: fid\n\n    Returns the feature identifier within the layer::\n\n        >>> city.fid\n        0\n\n    .. attribute:: layer_name\n\n    Returns the name of the :class:`Layer` that the feature came from. This\n    will be the same for all features in a given layer::\n\n        >>> city.layer_name\n        'cities'\n\n    .. attribute:: index\n\n    A method that returns the index of the given field name. This will be the\n    same for all features in a given layer::\n\n        >>> city.index('Population')\n        1\n\n``Field``\n---------\n\n.. class:: Field\n\n    .. attribute:: name\n\n    Returns the name of this field::\n\n        >>> city['Name'].name\n        'Name'\n\n    .. attribute:: type\n\n    Returns the OGR type of this field, as an integer. The ``FIELD_CLASSES``\n    dictionary maps these values onto subclasses of ``Field``::\n\n        >>> city['Density'].type\n        2\n\n    .. attribute:: type_name\n\n    Returns a string with the name of the data type of this field::\n\n        >>> city['Name'].type_name\n        'String'\n\n    .. attribute:: value\n\n    Returns the value of this field. The ``Field`` class itself returns the\n    value as a string, but each subclass returns the value in the most\n    appropriate form::\n\n        >>> city['Population'].value\n        102121\n\n    .. attribute:: width\n\n    Returns the width of this field::\n\n        >>> city['Name'].width\n        80\n\n    .. attribute:: precision\n\n    Returns the numeric precision of this field. This is meaningless (and set\n    to zero) for non-numeric fields::\n\n        >>> city['Density'].precision\n        15\n\n    .. method:: as_double()\n\n    Returns the value of the field as a double (float)::\n\n        >>> city['Density'].as_double()\n        874.7\n\n    .. method:: as_int()\n\n    Returns the value of the field as an integer::\n\n        >>> city['Population'].as_int()\n        102121\n\n    .. method:: as_string()\n\n    Returns the value of the field as a string::\n\n        >>> city['Name'].as_string()\n        'Pueblo'\n\n    .. method:: as_datetime()\n\n    Returns the value of the field as a tuple of date and time components::\n\n        >>> city['Created'].as_datetime()\n        (c_long(1999), c_long(5), c_long(23), c_long(0), c_long(0), c_long(0), c_long(0))\n\n``Driver``\n----------\n\n.. class:: Driver(dr_input)\n\n    The ``Driver`` class is used internally to wrap an OGR :class:`DataSource`\n    driver.\n\n    .. attribute:: driver_count\n\n    Returns the number of OGR vector drivers currently registered.\n\nOGR Geometries\n==============\n\n``OGRGeometry``\n---------------\n\n:class:`OGRGeometry` objects share similar functionality with\n:class:`~django.contrib.gis.geos.GEOSGeometry` objects and are thin wrappers\naround OGR's internal geometry representation. Thus, they allow for more\nefficient access to data when using :class:`DataSource`. Unlike its GEOS\ncounterpart, :class:`OGRGeometry` supports spatial reference systems and\ncoordinate transformation::\n\n    >>> from django.contrib.gis.gdal import OGRGeometry\n    >>> polygon = OGRGeometry('POLYGON((0 0, 5 0, 5 5, 0 5))')\n\n.. class:: OGRGeometry(geom_input, srs=None)\n\n    This object is a wrapper for the `OGR Geometry`__ class. These objects are\n    instantiated directly from the given ``geom_input`` parameter, which may be\n    a string containing WKT, HEX, GeoJSON, a ``buffer`` containing WKB data, or\n    an :class:`OGRGeomType` object. These objects are also returned from the\n    :class:`Feature.geom` attribute, when reading vector data from\n    :class:`Layer` (which is in turn a part of a :class:`DataSource`).\n\n    __ https://gdal.org/api/ogrgeometry_cpp.html#ogrgeometry-class\n\n    .. classmethod:: from_gml(gml_string)\n\n    Constructs an :class:`OGRGeometry` from the given GML string.\n\n    .. classmethod:: from_bbox(bbox)\n\n    Constructs a :class:`Polygon` from the given bounding-box (a 4-tuple).\n\n    .. method:: __len__()\n\n    Returns the number of points in a :class:`LineString`, the number of rings\n    in a :class:`Polygon`, or the number of geometries in a\n    :class:`GeometryCollection`. Not applicable to other geometry types.\n\n    .. method:: __iter__()\n\n    Iterates over the points in a :class:`LineString`, the rings in a\n    :class:`Polygon`, or the geometries in a :class:`GeometryCollection`.\n    Not applicable to other geometry types.\n\n    .. method:: __getitem__()\n\n    Returns the point at the specified index for a :class:`LineString`, the\n    interior ring at the specified index for a :class:`Polygon`, or the geometry\n    at the specified index in a :class:`GeometryCollection`. Not applicable to\n    other geometry types.\n\n    .. attribute:: dimension\n\n    Returns the number of coordinated dimensions of the geometry, i.e. 0\n    for points, 1 for lines, and so forth::\n\n        >> polygon.dimension\n        2\n\n    .. attribute:: coord_dim\n\n    Returns or sets the coordinate dimension of this geometry. For example, the\n    value would be 2 for two-dimensional geometries.\n\n    .. attribute:: geom_count\n\n    Returns the number of elements in this geometry::\n\n        >>> polygon.geom_count\n        1\n\n    .. attribute:: point_count\n\n    Returns the number of points used to describe this geometry::\n\n        >>> polygon.point_count\n        4\n\n    .. attribute:: num_points\n\n    Alias for :attr:`point_count`.\n\n    .. attribute:: num_coords\n\n    Alias for :attr:`point_count`.\n\n    .. attribute:: geom_type\n\n    Returns the type of this geometry, as an :class:`OGRGeomType` object.\n\n    .. attribute:: geom_name\n\n    Returns the name of the type of this geometry::\n\n        >>> polygon.geom_name\n        'POLYGON'\n\n    .. attribute:: area\n\n    Returns the area of this geometry, or 0 for geometries that do not contain\n    an area::\n\n        >>> polygon.area\n        25.0\n\n    .. attribute:: envelope\n\n    Returns the envelope of this geometry, as an :class:`Envelope` object.\n\n    .. attribute:: extent\n\n    Returns the envelope of this geometry as a 4-tuple, instead of as an\n    :class:`Envelope` object::\n\n        >>> point.extent\n        (0.0, 0.0, 5.0, 5.0)\n\n    .. attribute:: srs\n\n    This property controls the spatial reference for this geometry, or\n    ``None`` if no spatial reference system has been assigned to it.\n    If assigned, accessing this property returns a :class:`SpatialReference`\n    object.  It may be set with another :class:`SpatialReference` object,\n    or any input that :class:`SpatialReference` accepts. Example::\n\n        >>> city.geom.srs.name\n        'GCS_WGS_1984'\n\n    .. attribute:: srid\n\n    Returns or sets the spatial reference identifier corresponding to\n    :class:`SpatialReference` of this geometry.  Returns ``None`` if\n    there is no spatial reference information associated with this\n    geometry, or if an SRID cannot be determined.\n\n    .. attribute:: geos\n\n    Returns a :class:`~django.contrib.gis.geos.GEOSGeometry` object\n    corresponding to this geometry.\n\n    .. attribute:: gml\n\n    Returns a string representation of this geometry in GML format::\n\n        >>> OGRGeometry('POINT(1 2)').gml\n        '<gml:Point><gml:coordinates>1,2</gml:coordinates></gml:Point>'\n\n    .. attribute:: hex\n\n    Returns a string representation of this geometry in HEX WKB format::\n\n        >>> OGRGeometry('POINT(1 2)').hex\n        '0101000000000000000000F03F0000000000000040'\n\n    .. attribute:: json\n\n    Returns a string representation of this geometry in JSON format::\n\n        >>> OGRGeometry('POINT(1 2)').json\n        '{ \"type\": \"Point\", \"coordinates\": [ 1.000000, 2.000000 ] }'\n\n    .. attribute:: kml\n\n    Returns a string representation of this geometry in KML format.\n\n    .. attribute:: wkb_size\n\n    Returns the size of the WKB buffer needed to hold a WKB representation\n    of this geometry::\n\n        >>> OGRGeometry('POINT(1 2)').wkb_size\n        21\n\n    .. attribute:: wkb\n\n    Returns a ``buffer`` containing a WKB representation of this geometry.\n\n    .. attribute:: wkt\n\n    Returns a string representation of this geometry in WKT format.\n\n    .. attribute:: ewkt\n\n    Returns the EWKT representation of this geometry.\n\n    .. method:: clone()\n\n    Returns a new :class:`OGRGeometry` clone of this geometry object.\n\n    .. method:: close_rings()\n\n    If there are any rings within this geometry that have not been closed,\n    this routine will do so by adding the starting point to the end::\n\n        >>> triangle = OGRGeometry('LINEARRING (0 0,0 1,1 0)')\n        >>> triangle.close_rings()\n        >>> triangle.wkt\n        'LINEARRING (0 0,0 1,1 0,0 0)'\n\n    .. method:: transform(coord_trans, clone=False)\n\n    Transforms this geometry to a different spatial reference system. May take\n    a :class:`CoordTransform` object, a :class:`SpatialReference` object, or\n    any other input accepted by :class:`SpatialReference` (including spatial\n    reference WKT and PROJ strings, or an integer SRID).\n\n    By default nothing is returned and the geometry is transformed in-place.\n    However, if the ``clone`` keyword is set to ``True`` then a transformed\n    clone of this geometry is returned instead.\n\n    .. method:: intersects(other)\n\n    Returns ``True`` if this geometry intersects the other, otherwise returns\n    ``False``.\n\n    .. method:: equals(other)\n\n    Returns ``True`` if this geometry is equivalent to the other, otherwise\n    returns ``False``.\n\n    .. method:: disjoint(other)\n\n    Returns ``True`` if this geometry is spatially disjoint to (i.e. does\n    not intersect) the other, otherwise returns ``False``.\n\n    .. method:: touches(other)\n\n    Returns ``True`` if this geometry touches the other, otherwise returns\n    ``False``.\n\n    .. method:: crosses(other)\n\n    Returns ``True`` if this geometry crosses the other, otherwise returns\n    ``False``.\n\n    .. method:: within(other)\n\n    Returns ``True`` if this geometry is contained within the other, otherwise\n    returns ``False``.\n\n    .. method:: contains(other)\n\n    Returns ``True`` if this geometry contains the other, otherwise returns\n    ``False``.\n\n    .. method:: overlaps(other)\n\n    Returns ``True`` if this geometry overlaps the other, otherwise returns\n    ``False``.\n\n    .. method:: boundary()\n\n    The boundary of this geometry, as a new :class:`OGRGeometry` object.\n\n    .. attribute:: convex_hull\n\n    The smallest convex polygon that contains this geometry, as a new\n    :class:`OGRGeometry` object.\n\n    .. method:: difference()\n\n    Returns the region consisting of the difference of this geometry and\n    the other, as a new :class:`OGRGeometry` object.\n\n    .. method:: intersection()\n\n    Returns the region consisting of the intersection of this geometry and\n    the other, as a new :class:`OGRGeometry` object.\n\n    .. method:: sym_difference()\n\n    Returns the region consisting of the symmetric difference of this\n    geometry and the other, as a new :class:`OGRGeometry` object.\n\n    .. method:: union()\n\n    Returns the region consisting of the union of this geometry and\n    the other, as a new :class:`OGRGeometry` object.\n\n    .. attribute:: tuple\n\n    Returns the coordinates of a point geometry as a tuple, the\n    coordinates of a line geometry as a tuple of tuples, and so forth::\n\n        >>> OGRGeometry('POINT (1 2)').tuple\n        (1.0, 2.0)\n        >>> OGRGeometry('LINESTRING (1 2,3 4)').tuple\n        ((1.0, 2.0), (3.0, 4.0))\n\n    .. attribute:: coords\n\n    An alias for :attr:`tuple`.\n\n.. class:: Point\n\n    .. attribute:: x\n\n    Returns the X coordinate of this point::\n\n        >>> OGRGeometry('POINT (1 2)').x\n        1.0\n\n    .. attribute:: y\n\n    Returns the Y coordinate of this point::\n\n        >>> OGRGeometry('POINT (1 2)').y\n        2.0\n\n    .. attribute:: z\n\n    Returns the Z coordinate of this point, or ``None`` if the point does not\n    have a Z coordinate::\n\n        >>> OGRGeometry('POINT (1 2 3)').z\n        3.0\n\n.. class:: LineString\n\n    .. attribute:: x\n\n    Returns a list of X coordinates in this line::\n\n        >>> OGRGeometry('LINESTRING (1 2,3 4)').x\n        [1.0, 3.0]\n\n    .. attribute:: y\n\n    Returns a list of Y coordinates in this line::\n\n        >>> OGRGeometry('LINESTRING (1 2,3 4)').y\n        [2.0, 4.0]\n\n    .. attribute:: z\n\n    Returns a list of Z coordinates in this line, or ``None`` if the line does\n    not have Z coordinates::\n\n        >>> OGRGeometry('LINESTRING (1 2 3,4 5 6)').z\n        [3.0, 6.0]\n\n\n.. class:: Polygon\n\n    .. attribute:: shell\n\n    Returns the shell or exterior ring of this polygon, as a ``LinearRing``\n    geometry.\n\n    .. attribute:: exterior_ring\n\n    An alias for :attr:`shell`.\n\n    .. attribute:: centroid\n\n    Returns a :class:`Point` representing the centroid of this polygon.\n\n.. class:: GeometryCollection\n\n    .. method:: add(geom)\n\n    Adds a geometry to this geometry collection. Not applicable to other\n    geometry types.\n\n``OGRGeomType``\n---------------\n\n.. class:: OGRGeomType(type_input)\n\n    This class allows for the representation of an OGR geometry type\n    in any of several ways::\n\n        >>> from django.contrib.gis.gdal import OGRGeomType\n        >>> gt1 = OGRGeomType(3)             # Using an integer for the type\n        >>> gt2 = OGRGeomType('Polygon')     # Using a string\n        >>> gt3 = OGRGeomType('POLYGON')     # It's case-insensitive\n        >>> print(gt1 == 3, gt1 == 'Polygon') # Equivalence works w/non-OGRGeomType objects\n        True True\n\n    .. attribute:: name\n\n    Returns a short-hand string form of the OGR Geometry type::\n\n        >>> gt1.name\n        'Polygon'\n\n    .. attribute:: num\n\n    Returns the number corresponding to the OGR geometry type::\n\n        >>> gt1.num\n        3\n\n    .. attribute:: django\n\n    Returns the Django field type (a subclass of GeometryField) to use for\n    storing this OGR type, or ``None`` if there is no appropriate Django type::\n\n        >>> gt1.django\n        'PolygonField'\n\n``Envelope``\n------------\n\n.. class:: Envelope(*args)\n\n    Represents an OGR Envelope structure that contains the minimum and maximum\n    X, Y coordinates for a rectangle bounding box. The naming of the variables\n    is compatible with the OGR Envelope C structure.\n\n    .. attribute:: min_x\n\n    The value of the minimum X coordinate.\n\n    .. attribute:: min_y\n\n    The value of the maximum X coordinate.\n\n    .. attribute:: max_x\n\n    The value of the minimum Y coordinate.\n\n    .. attribute:: max_y\n\n    The value of the maximum Y coordinate.\n\n    .. attribute:: ur\n\n    The upper-right coordinate, as a tuple.\n\n    .. attribute:: ll\n\n    The lower-left coordinate, as a tuple.\n\n    .. attribute:: tuple\n\n    A tuple representing the envelope.\n\n    .. attribute:: wkt\n\n    A string representing this envelope as a polygon in WKT format.\n\n    .. method:: expand_to_include(*args)\n\nCoordinate System Objects\n=========================\n\n``SpatialReference``\n--------------------\n\n.. class:: SpatialReference(srs_input)\n\n    Spatial reference objects are initialized on the given ``srs_input``,\n    which may be one of the following:\n\n    * OGC Well Known Text (WKT) (a string)\n    * EPSG code (integer or string)\n    * PROJ string\n    * A shorthand string for well-known standards (``'WGS84'``, ``'WGS72'``,\n      ``'NAD27'``, ``'NAD83'``)\n\n    Example::\n\n        >>> wgs84 = SpatialReference('WGS84') # shorthand string\n        >>> wgs84 = SpatialReference(4326) # EPSG code\n        >>> wgs84 = SpatialReference('EPSG:4326') # EPSG string\n        >>> proj = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs '\n        >>> wgs84 = SpatialReference(proj) # PROJ string\n        >>> wgs84 = SpatialReference(\"\"\"GEOGCS[\"WGS 84\",\n        DATUM[\"WGS_1984\",\n             SPHEROID[\"WGS 84\",6378137,298.257223563,\n                 AUTHORITY[\"EPSG\",\"7030\"]],\n             AUTHORITY[\"EPSG\",\"6326\"]],\n         PRIMEM[\"Greenwich\",0,\n             AUTHORITY[\"EPSG\",\"8901\"]],\n         UNIT[\"degree\",0.01745329251994328,\n             AUTHORITY[\"EPSG\",\"9122\"]],\n         AUTHORITY[\"EPSG\",\"4326\"]]\"\"\") # OGC WKT\n\n    .. method:: __getitem__(target)\n\n    Returns the value of the given string attribute node, ``None`` if the node\n    doesn't exist. Can also take a tuple as a parameter, (target, child), where\n    child is the index of the attribute in the WKT. For example::\n\n        >>> wkt = 'GEOGCS[\"WGS 84\", DATUM[\"WGS_1984, ... AUTHORITY[\"EPSG\",\"4326\"]]')\n        >>> srs = SpatialReference(wkt) # could also use 'WGS84', or 4326\n        >>> print(srs['GEOGCS'])\n        WGS 84\n        >>> print(srs['DATUM'])\n        WGS_1984\n        >>> print(srs['AUTHORITY'])\n        EPSG\n        >>> print(srs['AUTHORITY', 1]) # The authority value\n        4326\n        >>> print(srs['TOWGS84', 4]) # the fourth value in this wkt\n        0\n        >>> print(srs['UNIT|AUTHORITY']) # For the units authority, have to use the pipe symbol.\n        EPSG\n        >>> print(srs['UNIT|AUTHORITY', 1]) # The authority value for the units\n        9122\n\n    .. method:: attr_value(target, index=0)\n\n    The attribute value for the given target node (e.g. ``'PROJCS'``).\n    The index keyword specifies an index of the child node to return.\n\n    .. method:: auth_name(target)\n\n    Returns the authority name for the given string target node.\n\n    .. method:: auth_code(target)\n\n    Returns the authority code for the given string target node.\n\n    .. method:: clone()\n\n    Returns a clone of this spatial reference object.\n\n    .. method:: identify_epsg()\n\n    This method inspects the WKT of this ``SpatialReference`` and will add EPSG\n    authority nodes where an EPSG identifier is applicable.\n\n    .. method:: from_esri()\n\n    Morphs this SpatialReference from ESRI's format to EPSG\n\n    .. method:: to_esri()\n\n    Morphs this SpatialReference to ESRI's format.\n\n    .. method:: validate()\n\n    Checks to see if the given spatial reference is valid, if not\n    an exception will be raised.\n\n    .. method:: import_epsg(epsg)\n\n    Import spatial reference from EPSG code.\n\n    .. method:: import_proj(proj)\n\n    Import spatial reference from PROJ string.\n\n    .. method:: import_user_input(user_input)\n\n    .. method:: import_wkt(wkt)\n\n    Import spatial reference from WKT.\n\n    .. method:: import_xml(xml)\n\n    Import spatial reference from XML.\n\n    .. attribute:: name\n\n    Returns the name of this Spatial Reference.\n\n    .. attribute:: srid\n\n    Returns the SRID of top-level authority, or ``None`` if undefined.\n\n    .. attribute:: linear_name\n\n    Returns the name of the linear units.\n\n    .. attribute:: linear_units\n\n    Returns the value of the linear units.\n\n    .. attribute:: angular_name\n\n    Returns the name of the angular units.\"\n\n    .. attribute:: angular_units\n\n    Returns the value of the angular units.\n\n    .. attribute:: units\n\n    Returns a 2-tuple of the units value and the units name and will\n    automatically determines whether to return the linear or angular units.\n\n    .. attribute:: ellipsoid\n\n    Returns a tuple of the ellipsoid parameters for this spatial reference:\n    (semimajor axis, semiminor axis, and inverse flattening).\n\n    .. attribute:: semi_major\n\n    Returns the semi major axis of the ellipsoid for this spatial reference.\n\n    .. attribute:: semi_minor\n\n    Returns the semi minor axis of the ellipsoid for this spatial reference.\n\n    .. attribute:: inverse_flattening\n\n    Returns the inverse flattening of the ellipsoid for this spatial reference.\n\n    .. attribute:: geographic\n\n    Returns ``True`` if this spatial reference is geographic (root node is\n    ``GEOGCS``).\n\n    .. attribute:: local\n\n    Returns ``True`` if this spatial reference is local (root node is\n    ``LOCAL_CS``).\n\n    .. attribute:: projected\n\n    Returns ``True`` if this spatial reference is a projected coordinate system\n    (root node is ``PROJCS``).\n\n    .. attribute:: wkt\n\n    Returns the WKT representation of this spatial reference.\n\n    .. attribute:: pretty_wkt\n\n    Returns the 'pretty' representation of the WKT.\n\n    .. attribute:: proj\n\n    Returns the PROJ representation for this spatial reference.\n\n    .. attribute:: proj4\n\n    Alias for :attr:`SpatialReference.proj`.\n\n    .. attribute:: xml\n\n    Returns the XML representation of this spatial reference.\n\n``CoordTransform``\n------------------\n\n.. class:: CoordTransform(source, target)\n\nRepresents a coordinate system transform. It is initialized with two\n:class:`SpatialReference`, representing the source and target coordinate\nsystems, respectively. These objects should be used when performing the same\ncoordinate transformation repeatedly on different geometries::\n\n    >>> ct = CoordTransform(SpatialReference('WGS84'), SpatialReference('NAD83'))\n    >>> for feat in layer:\n    ...     geom = feat.geom # getting clone of feature geometry\n    ...     geom.transform(ct) # transforming\n\n.. _raster-data-source-objects:\n\nRaster Data Objects\n===================\n\n``GDALRaster``\n----------------\n\n:class:`GDALRaster` is a wrapper for the GDAL raster source object that\nsupports reading data from a variety of GDAL-supported geospatial file\nformats and data sources using a consistent interface.  Each\ndata source is represented by a :class:`GDALRaster` object which contains\none or more layers of data named bands.  Each band, represented by a\n:class:`GDALBand` object, contains georeferenced image data. For example, an RGB\nimage is represented as three bands: one for red, one for green, and one for\nblue.\n\n.. note::\n\n    For raster data there is no difference between a raster instance and its\n    data source. Unlike for the Geometry objects, :class:`GDALRaster` objects are\n    always a data source. Temporary rasters can be instantiated in memory\n    using the corresponding driver, but they will be of the same class as file-based\n    raster sources.\n\n.. class:: GDALRaster(ds_input, write=False)\n\n    The constructor for ``GDALRaster`` accepts two parameters. The first\n    parameter defines the raster source, and the second parameter defines if a\n    raster should be opened in write mode. For newly-created rasters, the second\n    parameter is ignored and the new raster is always created in write mode.\n\n    The first parameter can take three forms: a string representing a file\n    path, a dictionary with values defining a new raster, or a bytes object\n    representing a raster file.\n\n    If the input is a file path, the raster is opened from there. If the input\n    is raw data in a dictionary, the parameters ``width``, ``height``, and\n    ``srid`` are required. If the input is a bytes object, it will be opened\n    using a GDAL virtual filesystem.\n\n    For a detailed description of how to create rasters using dictionary input,\n    see :ref:`gdal-raster-ds-input`. For a detailed description of how to\n    create rasters in the virtual filesystem, see :ref:`gdal-raster-vsimem`.\n\n    The following example shows how rasters can be created from different input\n    sources (using the sample data from the GeoDjango tests; see also the\n    :ref:`gdal_sample_data` section).\n\n        >>> from django.contrib.gis.gdal import GDALRaster\n        >>> rst = GDALRaster('/path/to/your/raster.tif', write=False)\n        >>> rst.name\n        '/path/to/your/raster.tif'\n        >>> rst.width, rst.height  # This file has 163 x 174 pixels\n        (163, 174)\n        >>> rst = GDALRaster({  # Creates an in-memory raster\n        ...     'srid': 4326,\n        ...     'width': 4,\n        ...     'height': 4,\n        ...     'datatype': 1,\n        ...     'bands': [{\n        ...         'data': (2, 3),\n        ...         'offset': (1, 1),\n        ...         'size': (2, 2),\n        ...         'shape': (2, 1),\n        ...         'nodata_value': 5,\n        ...     }]\n        ... })\n        >>> rst.srs.srid\n        4326\n        >>> rst.width, rst.height\n        (4, 4)\n        >>> rst.bands[0].data()\n        array([[5, 5, 5, 5],\n               [5, 2, 3, 5],\n               [5, 2, 3, 5],\n               [5, 5, 5, 5]], dtype=uint8)\n        >>> rst_file = open('/path/to/your/raster.tif', 'rb')\n        >>> rst_bytes = rst_file.read()\n        >>> rst = GDALRaster(rst_bytes)\n        >>> rst.is_vsi_based\n        True\n        >>> rst.name  # Stored in a random path in the vsimem filesystem.\n        '/vsimem/da300bdb-129d-49a8-b336-e410a9428dad'\n\n    .. attribute:: name\n\n        The name of the source which is equivalent to the input file path or the name\n        provided upon instantiation.\n\n            >>> GDALRaster({'width': 10, 'height': 10, 'name': 'myraster', 'srid': 4326}).name\n            'myraster'\n\n    .. attribute:: driver\n\n        The name of the GDAL driver used to handle the input file. For ``GDALRaster``\\s created\n        from a file, the driver type is detected automatically. The creation of rasters from\n        scratch is an in-memory raster by default (``'MEM'``), but can be\n        altered as needed. For instance, use ``GTiff`` for a ``GeoTiff`` file.\n        For a list of file types, see also the `GDAL Raster Formats`__ list.\n\n        __ https://gdal.org/drivers/raster/\n\n        An in-memory raster is created through the following example:\n\n            >>> GDALRaster({'width': 10, 'height': 10, 'srid': 4326}).driver.name\n            'MEM'\n\n        A file based GeoTiff raster is created through the following example:\n\n            >>> import tempfile\n            >>> rstfile = tempfile.NamedTemporaryFile(suffix='.tif')\n            >>> rst = GDALRaster({'driver': 'GTiff', 'name': rstfile.name, 'srid': 4326,\n            ...                   'width': 255, 'height': 255, 'nr_of_bands': 1})\n            >>> rst.name\n            '/tmp/tmp7x9H4J.tif'           # The exact filename will be different on your computer\n            >>> rst.driver.name\n            'GTiff'\n\n    .. attribute:: width\n\n        The width of the source in pixels (X-axis).\n\n            >>> GDALRaster({'width': 10, 'height': 20, 'srid': 4326}).width\n            10\n\n    .. attribute:: height\n\n        The height of the source in pixels (Y-axis).\n\n            >>> GDALRaster({'width': 10, 'height': 20, 'srid': 4326}).height\n            20\n\n    .. attribute:: srs\n\n        The spatial reference system of the raster, as a\n        :class:`SpatialReference` instance. The SRS can be changed by\n        setting it to an other :class:`SpatialReference` or providing any input\n        that is accepted by the :class:`SpatialReference` constructor.\n\n            >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})\n            >>> rst.srs.srid\n            4326\n            >>> rst.srs = 3086\n            >>> rst.srs.srid\n            3086\n\n    .. attribute:: srid\n\n        The Spatial Reference System Identifier (SRID) of the raster. This\n        property is a shortcut to getting or setting the SRID through the\n        :attr:`srs` attribute.\n\n            >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})\n            >>> rst.srid\n            4326\n            >>> rst.srid = 3086\n            >>> rst.srid\n            3086\n            >>> rst.srs.srid  # This is equivalent\n            3086\n\n    .. attribute:: geotransform\n\n        The affine transformation matrix used to georeference the source, as a\n        tuple of six coefficients which map pixel/line coordinates into\n        georeferenced space using the following relationship::\n\n            Xgeo = GT(0) + Xpixel*GT(1) + Yline*GT(2)\n            Ygeo = GT(3) + Xpixel*GT(4) + Yline*GT(5)\n\n        The same values can be retrieved by accessing the :attr:`origin`\n        (indices 0 and 3), :attr:`scale` (indices 1 and 5) and :attr:`skew`\n        (indices 2 and 4) properties.\n\n        The default is ``[0.0, 1.0, 0.0, 0.0, 0.0, -1.0]``.\n\n            >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})\n            >>> rst.geotransform\n            [0.0, 1.0, 0.0, 0.0, 0.0, -1.0]\n\n    .. attribute:: origin\n\n        Coordinates of the top left origin of the raster in the spatial\n        reference system of the source, as a point object with ``x`` and ``y``\n        members.\n\n            >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})\n            >>> rst.origin\n            [0.0, 0.0]\n            >>> rst.origin.x = 1\n            >>> rst.origin\n            [1.0, 0.0]\n\n    .. attribute:: scale\n\n        Pixel width and height used for georeferencing the raster, as a point\n        object with ``x`` and ``y``  members. See :attr:`geotransform` for more\n        information.\n\n            >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})\n            >>> rst.scale\n            [1.0, -1.0]\n            >>> rst.scale.x = 2\n            >>> rst.scale\n            [2.0, -1.0]\n\n    .. attribute:: skew\n\n        Skew coefficients used to georeference the raster, as a point object\n        with ``x`` and ``y``  members. In case of north up images, these\n        coefficients are both ``0``.\n\n            >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})\n            >>> rst.skew\n            [0.0, 0.0]\n            >>> rst.skew.x = 3\n            >>> rst.skew\n            [3.0, 0.0]\n\n    .. attribute:: extent\n\n        Extent (boundary values) of the raster source, as a 4-tuple\n        ``(xmin, ymin, xmax, ymax)`` in the spatial reference system of the\n        source.\n\n            >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})\n            >>> rst.extent\n            (0.0, -20.0, 10.0, 0.0)\n            >>> rst.origin.x = 100\n            >>> rst.extent\n            (100.0, -20.0, 110.0, 0.0)\n\n    .. attribute:: bands\n\n        List of all bands of the source, as :class:`GDALBand` instances.\n\n            >>> rst = GDALRaster({\"width\": 1, \"height\": 2, 'srid': 4326,\n            ...                   \"bands\": [{\"data\": [0, 1]}, {\"data\": [2, 3]}]})\n            >>> len(rst.bands)\n            2\n            >>> rst.bands[1].data()\n            array([[ 2.,  3.]], dtype=float32)\n\n    .. method:: warp(ds_input, resampling='NearestNeighbour', max_error=0.0)\n\n        Returns a warped version of this raster.\n\n        The warping parameters can be specified through the ``ds_input``\n        argument. The use of ``ds_input`` is analogous to the corresponding\n        argument of the class constructor. It is a dictionary with the\n        characteristics of the target raster. Allowed dictionary key values are\n        width, height, SRID, origin, scale, skew, datatype, driver, and name\n        (filename).\n\n        By default, the warp functions keeps most parameters equal to the\n        values of the original source raster, so only parameters that should be\n        changed need to be specified. Note that this includes the driver, so\n        for file-based rasters the warp function will create a new raster on\n        disk.\n\n        The only parameter that is set differently from the source raster is the\n        name. The default value of the raster name is the name of the source\n        raster appended with ``'_copy' + source_driver_name``. For file-based\n        rasters it is recommended to provide the file path of the target raster.\n\n        The resampling algorithm used for warping can be specified with the\n        ``resampling`` argument. The default is ``NearestNeighbor``, and the\n        other allowed values are ``Bilinear``, ``Cubic``, ``CubicSpline``,\n        ``Lanczos``, ``Average``, and ``Mode``.\n\n        The ``max_error`` argument can be used to specify the maximum error\n        measured in input pixels that is allowed in approximating the\n        transformation. The default is 0.0 for exact calculations.\n\n        For users familiar with ``GDAL``, this function has a similar\n        functionality to the ``gdalwarp`` command-line utility.\n\n        For example, the warp function can be used for aggregating a raster to\n        the double of its original pixel scale:\n\n            >>> rst = GDALRaster({\n            ...     \"width\": 6, \"height\": 6, \"srid\": 3086,\n            ...     \"origin\": [500000, 400000],\n            ...     \"scale\": [100, -100],\n            ...     \"bands\": [{\"data\": range(36), \"nodata_value\": 99}]\n            ... })\n            >>> target = rst.warp({\"scale\": [200, -200], \"width\": 3, \"height\": 3})\n            >>> target.bands[0].data()\n            array([[  7.,   9.,  11.],\n                   [ 19.,  21.,  23.],\n                   [ 31.,  33.,  35.]], dtype=float32)\n\n    .. method:: transform(srid, driver=None, name=None, resampling='NearestNeighbour', max_error=0.0)\n\n        Returns a transformed version of this raster with the specified SRID.\n\n        This function transforms the current raster into a new spatial reference\n        system that can be specified with an ``srid``. It calculates the bounds\n        and scale of the current raster in the new spatial reference system and\n        warps the raster using the :attr:`~GDALRaster.warp` function.\n\n        By default, the driver of the source raster is used and the name of the\n        raster is the original name appended with\n        ``'_copy' + source_driver_name``. A different driver or name can be\n        specified with the ``driver`` and ``name`` arguments.\n\n        The default resampling algorithm is ``NearestNeighbour`` but can be\n        changed using the ``resampling`` argument. The default maximum allowed\n        error for resampling is 0.0 and can be changed using the ``max_error``\n        argument. Consult the :attr:`~GDALRaster.warp` documentation for detail\n        on those arguments.\n\n            >>> rst = GDALRaster({\n            ...     \"width\": 6, \"height\": 6, \"srid\": 3086,\n            ...     \"origin\": [500000, 400000],\n            ...     \"scale\": [100, -100],\n            ...     \"bands\": [{\"data\": range(36), \"nodata_value\": 99}]\n            ... })\n            >>> target = rst.transform(4326)\n            >>> target.origin\n            [-82.98492744885776, 27.601924753080144]\n\n    .. attribute:: info\n\n        Returns a string with a summary of the raster. This is equivalent to\n        the `gdalinfo`__ command line utility.\n\n        __ https://gdal.org/programs/gdalinfo.html\n\n    .. attribute:: metadata\n\n        The metadata of this raster, represented as a nested dictionary. The\n        first-level key is the metadata domain. The second-level contains the\n        metadata item names and values from each domain.\n\n        To set or update a metadata item, pass the corresponding metadata item\n        to the method using the nested structure described above. Only keys\n        that are in the specified dictionary are updated; the rest of the\n        metadata remains unchanged.\n\n        To remove a metadata item, use ``None`` as the metadata value.\n\n            >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})\n            >>> rst.metadata\n            {}\n            >>> rst.metadata = {'DEFAULT': {'OWNER': 'Django', 'VERSION': '1.0'}}\n            >>> rst.metadata\n            {'DEFAULT': {'OWNER': 'Django', 'VERSION': '1.0'}}\n            >>> rst.metadata = {'DEFAULT': {'OWNER': None, 'VERSION': '2.0'}}\n            >>> rst.metadata\n            {'DEFAULT': {'VERSION': '2.0'}}\n\n    .. attribute:: vsi_buffer\n\n        A ``bytes`` representation of this raster. Returns ``None`` for rasters\n        that are not stored in GDAL's virtual filesystem.\n\n    .. attribute:: is_vsi_based\n\n        A boolean indicating if this raster is stored in GDAL's virtual\n        filesystem.\n\n``GDALBand``\n------------\n\n.. class:: GDALBand\n\n    ``GDALBand`` instances are not created explicitly, but rather obtained\n    from a :class:`GDALRaster` object, through its :attr:`~GDALRaster.bands`\n    attribute. The GDALBands contain the actual pixel values of the raster.\n\n    .. attribute:: description\n\n        The name or description of the band, if any.\n\n    .. attribute:: width\n\n        The width of the band in pixels (X-axis).\n\n    .. attribute:: height\n\n        The height of the band in pixels (Y-axis).\n\n    .. attribute:: pixel_count\n\n        The total number of pixels in this band. Is equal to ``width * height``.\n\n    .. method:: statistics(refresh=False, approximate=False)\n\n        Compute statistics on the pixel values of this band. The return value\n        is a tuple with the following structure:\n        ``(minimum, maximum, mean, standard deviation)``.\n\n        If the ``approximate`` argument is set to ``True``, the statistics may\n        be computed based on overviews or a subset of image tiles.\n\n        If the ``refresh`` argument is set to ``True``, the statistics will be\n        computed from the data directly, and the cache will be updated with the\n        result.\n\n        If a persistent cache value is found, that value is returned. For\n        raster formats using Persistent Auxiliary Metadata (PAM) services, the\n        statistics might be cached in an auxiliary file. In some cases this\n        metadata might be out of sync with the pixel values or cause values\n        from a previous call to be returned which don't reflect the value of\n        the ``approximate`` argument. In such cases, use the ``refresh``\n        argument to get updated values and store them in the cache.\n\n        For empty bands (where all pixel values are \"no data\"), all statistics\n        are returned as ``None``.\n\n        The statistics can also be retrieved directly by accessing the\n        :attr:`min`, :attr:`max`, :attr:`mean`, and :attr:`std` properties.\n\n    .. attribute:: min\n\n        The minimum pixel value of the band (excluding the \"no data\" value).\n\n    .. attribute:: max\n\n        The maximum pixel value of the band (excluding the \"no data\" value).\n\n    .. attribute:: mean\n\n        The mean of all pixel values of the band (excluding the \"no data\"\n        value).\n\n    .. attribute:: std\n\n        The standard deviation of all pixel values of the band (excluding the\n        \"no data\" value).\n\n    .. attribute:: nodata_value\n\n        The \"no data\" value for a band is generally a special marker value used\n        to mark pixels that are not valid data. Such pixels should generally not\n        be displayed, nor contribute to analysis operations.\n\n        To delete an existing \"no data\" value, set this property to ``None``\n        (requires GDAL ≥ 2.1).\n\n    .. method:: datatype(as_string=False)\n\n        The data type contained in the band, as an integer constant between 0\n        (Unknown) and 11. If ``as_string`` is ``True``, the data type is\n        returned as a string with the following possible values:\n        ``GDT_Unknown``, ``GDT_Byte``, ``GDT_UInt16``, ``GDT_Int16``,\n        ``GDT_UInt32``, ``GDT_Int32``, ``GDT_Float32``, ``GDT_Float64``,\n        ``GDT_CInt16``, ``GDT_CInt32``, ``GDT_CFloat32``, and ``GDT_CFloat64``.\n\n    .. method:: color_interp(as_string=False)\n\n        The color interpretation for the band, as an integer between 0and 16.\n        If ``as_string`` is ``True``, the data type is returned as a string\n        with the following possible values:\n        ``GCI_Undefined``, ``GCI_GrayIndex``, ``GCI_PaletteIndex``,\n        ``GCI_RedBand``, ``GCI_GreenBand``, ``GCI_BlueBand``, ``GCI_AlphaBand``,\n        ``GCI_HueBand``, ``GCI_SaturationBand``, ``GCI_LightnessBand``,\n        ``GCI_CyanBand``, ``GCI_MagentaBand``, ``GCI_YellowBand``,\n        ``GCI_BlackBand``, ``GCI_YCbCr_YBand``, ``GCI_YCbCr_CbBand``, and\n        ``GCI_YCbCr_CrBand``. ``GCI_YCbCr_CrBand`` also represents ``GCI_Max``\n        because both correspond to the integer 16, but only ``GCI_YCbCr_CrBand``\n        is returned as a string.\n\n    .. method:: data(data=None, offset=None, size=None, shape=None)\n\n        The accessor to the pixel values of the ``GDALBand``. Returns the complete\n        data array if no parameters are provided. A subset of the pixel array can\n        be requested by specifying an offset and block size as tuples.\n\n        If NumPy is available, the data is returned as NumPy array. For performance\n        reasons, it is highly recommended to use NumPy.\n\n        Data is written to the ``GDALBand`` if the ``data`` parameter is provided.\n        The input can be of one of the following types - packed string, buffer, list,\n        array, and NumPy array. The number of items in the input should normally\n        correspond to the total number of pixels in the band, or to the number\n        of pixels for a specific block of pixel values if the ``offset`` and\n        ``size`` parameters are provided.\n\n        If the number of items in the input is different from the target pixel\n        block, the ``shape`` parameter must be specified. The shape is a tuple\n        that specifies the width and height of the input data in pixels. The\n        data is then replicated to update the pixel values of the selected\n        block. This is useful to fill an entire band with a single value, for\n        instance.\n\n        For example:\n\n            >>> rst = GDALRaster({'width': 4, 'height': 4, 'srid': 4326, 'datatype': 1, 'nr_of_bands': 1})\n            >>> bnd = rst.bands[0]\n            >>> bnd.data(range(16))\n            >>> bnd.data()\n            array([[ 0,  1,  2,  3],\n                   [ 4,  5,  6,  7],\n                   [ 8,  9, 10, 11],\n                   [12, 13, 14, 15]], dtype=int8)\n            >>> bnd.data(offset=(1, 1), size=(2, 2))\n            array([[ 5,  6],\n                   [ 9, 10]], dtype=int8)\n            >>> bnd.data(data=[-1, -2, -3, -4], offset=(1, 1), size=(2, 2))\n            >>> bnd.data()\n            array([[ 0,  1,  2,  3],\n                   [ 4, -1, -2,  7],\n                   [ 8, -3, -4, 11],\n                   [12, 13, 14, 15]], dtype=int8)\n            >>> bnd.data(data='\\x9d\\xa8\\xb3\\xbe', offset=(1, 1), size=(2, 2))\n            >>> bnd.data()\n            array([[  0,   1,   2,   3],\n                   [  4, -99, -88,   7],\n                   [  8, -77, -66,  11],\n                   [ 12,  13,  14,  15]], dtype=int8)\n            >>> bnd.data([1], shape=(1, 1))\n            >>> bnd.data()\n            array([[1, 1, 1, 1],\n                   [1, 1, 1, 1],\n                   [1, 1, 1, 1],\n                   [1, 1, 1, 1]], dtype=uint8)\n            >>> bnd.data(range(4), shape=(1, 4))\n            array([[0, 0, 0, 0],\n                   [1, 1, 1, 1],\n                   [2, 2, 2, 2],\n                   [3, 3, 3, 3]], dtype=uint8)\n\n    .. attribute:: metadata\n\n        The metadata of this band. The functionality is identical to\n        :attr:`GDALRaster.metadata`.\n\n.. _gdal-raster-ds-input:\n\nCreating rasters from data\n--------------------------\n\nThis section describes how to create rasters from scratch using the\n``ds_input`` parameter.\n\nA new raster is created when a ``dict`` is passed to the :class:`GDALRaster`\nconstructor. The dictionary contains defining parameters of the new raster,\nsuch as the origin, size, or spatial reference system. The dictionary can also\ncontain pixel data and information about the format of the new raster. The\nresulting raster can therefore be file-based or memory-based, depending on the\ndriver specified.\n\nThere's no standard for describing raster data in a dictionary or JSON flavor.\nThe definition of the dictionary input to the :class:`GDALRaster` class is\ntherefore specific to Django. It's inspired by the `geojson`__ format, but the\n``geojson`` standard is currently limited to vector formats.\n\nExamples of using the different keys when creating rasters can be found in the\ndocumentation of the corresponding attributes and methods of the\n:class:`GDALRaster` and :class:`GDALBand` classes.\n\n__ https://geojson.org\n\nThe ``ds_input`` dictionary\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nOnly a few keys are required in the ``ds_input`` dictionary to create a raster:\n``width``, ``height``, and ``srid``. All other parameters have default values\n(see the table below). The list of keys that can be passed in the ``ds_input``\ndictionary is closely related but not identical to the :class:`GDALRaster`\nproperties. Many of the parameters are mapped directly to those properties;\nthe others are described below.\n\nThe following table describes all keys that can be set in the ``ds_input``\ndictionary.\n\n================= ======== ==================================================\nKey               Default  Usage\n================= ======== ==================================================\n``srid``          required Mapped to the :attr:`~GDALRaster.srid` attribute\n``width``         required Mapped to the :attr:`~GDALRaster.width` attribute\n``height``        required Mapped to the :attr:`~GDALRaster.height` attribute\n``driver``        ``MEM``  Mapped to the :attr:`~GDALRaster.driver` attribute\n``name``          ``''``   See below\n``origin``        ``0``    Mapped to the :attr:`~GDALRaster.origin` attribute\n``scale``         ``0``    Mapped to the :attr:`~GDALRaster.scale` attribute\n``skew``          ``0``    Mapped to the :attr:`~GDALRaster.width` attribute\n``bands``         ``[]``   See below\n``nr_of_bands``   ``0``    See below\n``datatype``      ``6``    See below\n``papsz_options`` ``{}``   See below\n================= ======== ==================================================\n\n.. object:: name\n\n    String representing the name of the raster. When creating a file-based\n    raster, this parameter must be the file path for the new raster. If the\n    name starts with ``/vsimem/``, the raster is created in GDAL's virtual\n    filesystem.\n\n.. object:: datatype\n\n    Integer representing the data type for all the bands. Defaults to ``6``\n    (Float32). All bands of a new raster are required to have the same datatype.\n    The value mapping is:\n\n    ===== =============== ===============================\n    Value GDAL Pixel Type Description\n    ===== =============== ===============================\n    1     GDT_Byte        Eight bit unsigned integer\n    2     GDT_UInt16      Sixteen bit unsigned integer\n    3     GDT_Int16       Sixteen bit signed integer\n    4     GDT_UInt32      Thirty-two bit unsigned integer\n    5     GDT_Int32       Thirty-two bit signed integer\n    6     GDT_Float32     Thirty-two bit floating point\n    7     GDT_Float64     Sixty-four bit floating point\n    ===== =============== ===============================\n\n.. object:: nr_of_bands\n\n    Integer representing the number of bands of the raster. A raster can be\n    created without passing band data upon creation. If the number of bands\n    isn't specified, it's automatically calculated from the length of the\n    ``bands`` input. The number of bands can't be changed after creation.\n\n.. object:: bands\n\n    A list of ``band_input`` dictionaries with band input data. The resulting\n    band indices are the same as in the list provided. The definition of the\n    band input dictionary is given below. If band data isn't provided, the\n    raster bands values are instantiated as an array of zeros and the \"no\n    data\" value is set to ``None``.\n\n.. object:: papsz_options\n\n    A dictionary with raster creation options. The key-value pairs of the\n    input dictionary are passed to the driver on creation of the raster.\n\n    The available options are driver-specific and are described in the\n    documentation of each driver.\n\n    The values in the dictionary are not case-sensitive and are automatically\n    converted to the correct string format upon creation.\n\n    The following example uses some of the options available for the\n    `GTiff driver`__. The result is a compressed signed byte raster with an\n    internal tiling scheme. The internal tiles have a block size of 23 by 23::\n\n        >>> GDALRaster({\n        ...    'driver': 'GTiff',\n        ...    'name': '/path/to/new/file.tif',\n        ...    'srid': 4326,\n        ...    'width': 255,\n        ...    'height': 255,\n        ...    'nr_of_bands': 1,\n        ...    'papsz_options': {\n        ...        'compress': 'packbits',\n        ...        'pixeltype': 'signedbyte',\n        ...        'tiled': 'yes',\n        ...        'blockxsize': 23,\n        ...        'blockysize': 23,\n        ...    }\n        ... })\n\n__ https://gdal.org/drivers/raster/gtiff.html\n\nThe ``band_input`` dictionary\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe ``bands`` key in the ``ds_input`` dictionary is a list of ``band_input``\ndictionaries. Each ``band_input`` dictionary can contain pixel values and the\n\"no data\" value to be set on the bands of the new raster. The data array can\nhave the full size of the new raster or be smaller. For arrays that are smaller\nthan the full raster, the ``size``, ``shape``, and ``offset`` keys  control the\npixel values. The corresponding keys are passed to the :meth:`~GDALBand.data`\nmethod. Their functionality is the same as setting the band data with that\nmethod. The following table describes the keys that can be used.\n\n================ ================================= ======================================================\nKey              Default                           Usage\n================ ================================= ======================================================\n``nodata_value`` ``None``                          Mapped to the :attr:`~GDALBand.nodata_value` attribute\n``data``         Same as ``nodata_value`` or ``0`` Passed to the :meth:`~GDALBand.data` method\n``size``         ``(with, height)`` of raster      Passed to the :meth:`~GDALBand.data` method\n``shape``        Same as size                      Passed to the :meth:`~GDALBand.data` method\n``offset``       ``(0, 0)``                        Passed to the :meth:`~GDALBand.data` method\n================ ================================= ======================================================\n\n.. _gdal-raster-vsimem:\n\nUsing GDAL's Virtual Filesystem\n-------------------------------\n\nGDAL has an internal memory-based filesystem, which allows treating blocks of\nmemory as files. It can be used to read and write :class:`GDALRaster` objects\nto and from binary file buffers.\n\nThis is useful in web contexts where rasters might be obtained as a buffer\nfrom a remote storage or returned from a view without being written to disk.\n\n:class:`GDALRaster` objects are created in the virtual filesystem when a\n``bytes`` object is provided as input, or when the file path starts with\n``/vsimem/``.\n\nInput provided as ``bytes`` has to be a full binary representation of a file.\nFor instance::\n\n    # Read a raster as a file object from a remote source.\n    >>> from urllib.request import urlopen\n    >>> dat = urlopen('http://example.com/raster.tif').read()\n    # Instantiate a raster from the bytes object.\n    >>> rst = GDALRaster(dat)\n    # The name starts with /vsimem/, indicating that the raster lives in the\n    # virtual filesystem.\n    >>> rst.name\n    '/vsimem/da300bdb-129d-49a8-b336-e410a9428dad'\n\nTo create a new virtual file-based raster from scratch, use the ``ds_input``\ndictionary representation and provide a ``name`` argument that starts with\n``/vsimem/`` (for detail of the dictionary representation, see\n:ref:`gdal-raster-ds-input`). For virtual file-based rasters, the\n:attr:`~GDALRaster.vsi_buffer` attribute returns the ``bytes`` representation\nof the raster.\n\nHere's how to create a raster and return it as a file in an\n:class:`~django.http.HttpResponse`::\n\n    >>> from django.http import HttpResponse\n    >>> rst = GDALRaster({\n    ...     'name': '/vsimem/temporarymemfile',\n    ...     'driver': 'tif',\n    ...     'width': 6, 'height': 6, 'srid': 3086,\n    ...     'origin': [500000, 400000],\n    ...     'scale': [100, -100],\n    ...     'bands': [{'data': range(36), 'nodata_value': 99}]\n    ... })\n    >>> HttpResponse(rast.vsi_buffer, 'image/tiff')\n\nSettings\n========\n\n.. setting:: GDAL_LIBRARY_PATH\n\n``GDAL_LIBRARY_PATH``\n---------------------\n\nA string specifying the location of the GDAL library.  Typically,\nthis setting is only used if the GDAL library is in a non-standard\nlocation (e.g., ``/home/john/lib/libgdal.so``).\n\nExceptions\n==========\n\n.. exception:: GDALException\n\n    The base GDAL exception, indicating a GDAL-related error.\n\n.. exception:: SRSException\n\n    An exception raised when an error occurs when constructing or using a\n    spatial reference system object.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":148,"nodeType":"TextFile","repoName":null,"name":"forms.txt","path":"docs/ref/contrib/postgres","text":"===========================================\nPostgreSQL specific form fields and widgets\n===========================================\n\nAll of these fields and widgets are available from the\n``django.contrib.postgres.forms`` module.\n\n.. currentmodule:: django.contrib.postgres.forms\n\nFields\n======\n\n``SimpleArrayField``\n--------------------\n\n.. class:: SimpleArrayField(base_field, delimiter=',', max_length=None, min_length=None)\n\n    A field which maps to an array. It is represented by an HTML ``<input>``.\n\n    .. attribute:: base_field\n\n        This is a required argument.\n\n        It specifies the underlying form field for the array. This is not used\n        to render any HTML, but it is used to process the submitted data and\n        validate it. For example::\n\n            >>> from django import forms\n            >>> from django.contrib.postgres.forms import SimpleArrayField\n\n            >>> class NumberListForm(forms.Form):\n            ...     numbers = SimpleArrayField(forms.IntegerField())\n\n            >>> form = NumberListForm({'numbers': '1,2,3'})\n            >>> form.is_valid()\n            True\n            >>> form.cleaned_data\n            {'numbers': [1, 2, 3]}\n\n            >>> form = NumberListForm({'numbers': '1,2,a'})\n            >>> form.is_valid()\n            False\n\n    .. attribute:: delimiter\n\n        This is an optional argument which defaults to a comma: ``,``. This\n        value is used to split the submitted data. It allows you to chain\n        ``SimpleArrayField`` for multidimensional data::\n\n            >>> from django import forms\n            >>> from django.contrib.postgres.forms import SimpleArrayField\n\n            >>> class GridForm(forms.Form):\n            ...     places = SimpleArrayField(SimpleArrayField(IntegerField()), delimiter='|')\n\n            >>> form = GridForm({'places': '1,2|2,1|4,3'})\n            >>> form.is_valid()\n            True\n            >>> form.cleaned_data\n            {'places': [[1, 2], [2, 1], [4, 3]]}\n\n        .. note::\n\n            The field does not support escaping of the delimiter, so be careful\n            in cases where the delimiter is a valid character in the underlying\n            field. The delimiter does not need to be only one character.\n\n    .. attribute:: max_length\n\n        This is an optional argument which validates that the array does not\n        exceed the stated length.\n\n    .. attribute:: min_length\n\n        This is an optional argument which validates that the array reaches at\n        least the stated length.\n\n    .. admonition:: User friendly forms\n\n        ``SimpleArrayField`` is not particularly user friendly in most cases,\n        however it is a useful way to format data from a client-side widget for\n        submission to the server.\n\n``SplitArrayField``\n-------------------\n\n.. class:: SplitArrayField(base_field, size, remove_trailing_nulls=False)\n\n    This field handles arrays by reproducing the underlying field a fixed\n    number of times.\n\n    .. attribute:: base_field\n\n        This is a required argument. It specifies the form field to be\n        repeated.\n\n    .. attribute:: size\n\n        This is the fixed number of times the underlying field will be used.\n\n    .. attribute:: remove_trailing_nulls\n\n        By default, this is set to ``False``. When ``False``, each value from\n        the repeated fields is stored. When set to ``True``, any trailing\n        values which are blank will be stripped from the result. If the\n        underlying field has ``required=True``, but ``remove_trailing_nulls``\n        is ``True``, then null values are only allowed at the end, and will be\n        stripped.\n\n        Some examples::\n\n            SplitArrayField(IntegerField(required=True), size=3, remove_trailing_nulls=False)\n\n            ['1', '2', '3']  # -> [1, 2, 3]\n            ['1', '2', '']  # -> ValidationError - third entry required.\n            ['1', '', '3']  # -> ValidationError - second entry required.\n            ['', '2', '']  # -> ValidationError - first and third entries required.\n\n            SplitArrayField(IntegerField(required=False), size=3, remove_trailing_nulls=False)\n\n            ['1', '2', '3']  # -> [1, 2, 3]\n            ['1', '2', '']  # -> [1, 2, None]\n            ['1', '', '3']  # -> [1, None, 3]\n            ['', '2', '']  # -> [None, 2, None]\n\n            SplitArrayField(IntegerField(required=True), size=3, remove_trailing_nulls=True)\n\n            ['1', '2', '3']  # -> [1, 2, 3]\n            ['1', '2', '']  # -> [1, 2]\n            ['1', '', '3']  # -> ValidationError - second entry required.\n            ['', '2', '']  # -> ValidationError - first entry required.\n\n            SplitArrayField(IntegerField(required=False), size=3, remove_trailing_nulls=True)\n\n            ['1', '2', '3']  # -> [1, 2, 3]\n            ['1', '2', '']  # -> [1, 2]\n            ['1', '', '3']  # -> [1, None, 3]\n            ['', '2', '']  # -> [None, 2]\n\n``HStoreField``\n---------------\n\n.. class:: HStoreField\n\n    A field which accepts JSON encoded data for an\n    :class:`~django.contrib.postgres.fields.HStoreField`. It casts all values\n    (except nulls) to strings. It is represented by an HTML ``<textarea>``.\n\n    .. admonition:: User friendly forms\n\n        ``HStoreField`` is not particularly user friendly in most cases,\n        however it is a useful way to format data from a client-side widget for\n        submission to the server.\n\n    .. note::\n\n        On occasions it may be useful to require or restrict the keys which are\n        valid for a given field. This can be done using the\n        :class:`~django.contrib.postgres.validators.KeysValidator`.\n\n``JSONField``\n-------------\n\n.. class:: JSONField\n\n    A field which accepts JSON encoded data for a\n    :class:`~django.db.models.JSONField`. It is represented by an HTML\n    ``<textarea>``.\n\n    .. admonition:: User friendly forms\n\n        ``JSONField`` is not particularly user friendly in most cases, however\n        it is a useful way to format data from a client-side widget for\n        submission to the server.\n\n    .. deprecated:: 3.1\n\n        Use :class:`django.forms.JSONField` instead.\n\nRange Fields\n------------\n\nThis group of fields all share similar functionality for accepting range data.\nThey are based on :class:`~django.forms.MultiValueField`. They treat one\nomitted value as an unbounded range. They also validate that the lower bound is\nnot greater than the upper bound. All of these fields use\n:class:`~django.contrib.postgres.forms.RangeWidget`.\n\n``IntegerRangeField``\n~~~~~~~~~~~~~~~~~~~~~\n\n.. class:: IntegerRangeField\n\n    Based on :class:`~django.forms.IntegerField` and translates its input into\n    :class:`~psycopg2:psycopg2.extras.NumericRange`. Default for\n    :class:`~django.contrib.postgres.fields.IntegerRangeField` and\n    :class:`~django.contrib.postgres.fields.BigIntegerRangeField`.\n\n``DecimalRangeField``\n~~~~~~~~~~~~~~~~~~~~~\n\n.. class:: DecimalRangeField\n\n    Based on :class:`~django.forms.DecimalField` and translates its input into\n    :class:`~psycopg2:psycopg2.extras.NumericRange`. Default for\n    :class:`~django.contrib.postgres.fields.DecimalRangeField`.\n\n``DateTimeRangeField``\n~~~~~~~~~~~~~~~~~~~~~~\n\n.. class:: DateTimeRangeField\n\n    Based on :class:`~django.forms.DateTimeField` and translates its input into\n    :class:`~psycopg2:psycopg2.extras.DateTimeTZRange`. Default for\n    :class:`~django.contrib.postgres.fields.DateTimeRangeField`.\n\n``DateRangeField``\n~~~~~~~~~~~~~~~~~~\n\n.. class:: DateRangeField\n\n    Based on :class:`~django.forms.DateField` and translates its input into\n    :class:`~psycopg2:psycopg2.extras.DateRange`. Default for\n    :class:`~django.contrib.postgres.fields.DateRangeField`.\n\nWidgets\n=======\n\n``RangeWidget``\n---------------\n\n.. class:: RangeWidget(base_widget, attrs=None)\n\n    Widget used by all of the range fields.\n    Based on :class:`~django.forms.MultiWidget`.\n\n    :class:`~RangeWidget` has one required argument:\n\n    .. attribute:: base_widget\n\n        A :class:`~RangeWidget` comprises a 2-tuple of ``base_widget``.\n\n    .. method:: decompress(value)\n\n        Takes a single \"compressed\" value of a field, for example a\n        :class:`~django.contrib.postgres.fields.DateRangeField`,\n        and returns a tuple representing and lower and upper bound.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":149,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/ref/contrib/postgres","text":"===========================\n``django.contrib.postgres``\n===========================\n\n.. module:: django.contrib.postgres\n    :synopsis: PostgreSQL-specific fields and features\n\nPostgreSQL has a number of features which are not shared by the other databases\nDjango supports. This optional module contains model fields and form fields for\na number of PostgreSQL specific data types.\n\n.. note::\n    Django is, and will continue to be, a database-agnostic web framework. We\n    would encourage those writing reusable applications for the Django\n    community to write database-agnostic code where practical. However, we\n    recognize that real world projects written using Django need not be\n    database-agnostic. In fact, once a project reaches a given size changing\n    the underlying data store is already a significant challenge and is likely\n    to require changing the code base in some ways to handle differences\n    between the data stores.\n\n    Django provides support for a number of data types which will\n    only work with PostgreSQL. There is no fundamental reason why (for example)\n    a ``contrib.mysql`` module does not exist, except that PostgreSQL has the\n    richest feature set of the supported databases so its users have the most\n    to gain.\n\n.. toctree::\n    :maxdepth: 2\n\n    aggregates\n    constraints\n    fields\n    forms\n    functions\n    indexes\n    lookups\n    operations\n    search\n    validators\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":150,"nodeType":"TextFile","repoName":null,"name":"operations.txt","path":"docs/ref/contrib/postgres","text":"=============================\nDatabase migration operations\n=============================\n\nAll of these :doc:`operations </ref/migration-operations>` are available from\nthe ``django.contrib.postgres.operations`` module.\n\n.. _create-postgresql-extensions:\n\nCreating extension using migrations\n===================================\n\nYou can create a PostgreSQL extension in your database using a migration file.\nThis example creates an hstore extension, but the same principles apply for\nother extensions.\n\nSet up the hstore extension in PostgreSQL before the first ``CreateModel``\nor ``AddField`` operation that involves\n:class:`~django.contrib.postgres.fields.HStoreField` by adding a migration with\nthe :class:`~django.contrib.postgres.operations.HStoreExtension` operation.\nFor example::\n\n    from django.contrib.postgres.operations import HStoreExtension\n\n    class Migration(migrations.Migration):\n        ...\n\n        operations = [\n            HStoreExtension(),\n            ...\n        ]\n\nCreating the extension requires a database user with superuser privileges.\nIf the Django database user doesn't have superuser privileges, you'll have\nto create the extension outside of Django migrations with a user that has\nthe appropriate privileges. In that case, connect to your Django database and\nrun the query ``CREATE EXTENSION IF NOT EXISTS hstore;``.\n\n.. currentmodule:: django.contrib.postgres.operations\n\n``CreateExtension``\n===================\n\n.. class:: CreateExtension(name)\n\n    An ``Operation`` subclass which installs PostgreSQL extensions.\n\n    .. attribute:: name\n\n        This is a required argument. The name of the extension to be installed.\n\n``BloomExtension``\n==================\n\n.. class:: BloomExtension()\n\n    .. versionadded:: 3.1\n\n    Install the ``bloom`` extension.\n\n``BtreeGinExtension``\n=====================\n\n.. class:: BtreeGinExtension()\n\n    Install the ``btree_gin`` extension.\n\n``BtreeGistExtension``\n======================\n\n.. class:: BtreeGistExtension()\n\n    Install the ``btree_gist`` extension.\n\n``CITextExtension``\n===================\n\n.. class:: CITextExtension()\n\n    Installs the ``citext`` extension.\n\n``CryptoExtension``\n===================\n\n.. class:: CryptoExtension()\n\n    Installs the ``pgcrypto`` extension.\n\n``HStoreExtension``\n===================\n\n.. class:: HStoreExtension()\n\n    Installs the ``hstore`` extension and also sets up the connection to\n    interpret hstore data for possible use in subsequent migrations.\n\n``TrigramExtension``\n====================\n\n.. class:: TrigramExtension()\n\n    Installs the ``pg_trgm`` extension.\n\n``UnaccentExtension``\n=====================\n\n.. class:: UnaccentExtension()\n\n    Installs the ``unaccent`` extension.\n\nIndex concurrent operations\n===========================\n\nPostgreSQL supports the ``CONCURRENTLY`` option to ``CREATE INDEX`` and\n``DROP INDEX`` statements to add and remove indexes without locking out writes.\nThis option is useful for adding or removing an index in a live production\ndatabase.\n\n.. class:: AddIndexConcurrently(model_name, index)\n\n    Like :class:`~django.db.migrations.operations.AddIndex`, but creates an\n    index with the ``CONCURRENTLY`` option. This has a few caveats to be aware\n    of when using this option, see `the PostgreSQL documentation of building\n    indexes concurrently <https://www.postgresql.org/docs/current/\n    sql-createindex.html#SQL-CREATEINDEX-CONCURRENTLY>`_.\n\n.. class:: RemoveIndexConcurrently(model_name, name)\n\n    Like :class:`~django.db.migrations.operations.RemoveIndex`, but removes the\n    index with the ``CONCURRENTLY`` option. This has a few caveats to be aware\n    of when using this option, see `the PostgreSQL documentation\n    <https://www.postgresql.org/docs/current/sql-dropindex.html>`_.\n\n.. note::\n\n    The ``CONCURRENTLY`` option is not supported inside a transaction (see\n    :ref:`non-atomic migration <non-atomic-migrations>`).\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":151,"nodeType":"TextFile","repoName":null,"name":"search.txt","path":"docs/ref/contrib/postgres","text":"================\nFull text search\n================\n\nThe database functions in the ``django.contrib.postgres.search`` module ease\nthe use of PostgreSQL's `full text search engine\n<https://www.postgresql.org/docs/current/textsearch.html>`_.\n\nFor the examples in this document, we'll use the models defined in\n:doc:`/topics/db/queries`.\n\n.. seealso::\n\n    For a high-level overview of searching, see the :doc:`topic documentation\n    </topics/db/search>`.\n\n.. currentmodule:: django.contrib.postgres.search\n\nThe ``search`` lookup\n=====================\n\n.. fieldlookup:: search\n\nA common way to use full text search is to search a single term against a\nsingle column in the database. For example::\n\n    >>> Entry.objects.filter(body_text__search='Cheese')\n    [<Entry: Cheese on Toast recipes>, <Entry: Pizza Recipes>]\n\nThis creates a ``to_tsvector`` in the database from the ``body_text`` field\nand a ``plainto_tsquery`` from the search term ``'Cheese'``, both using the\ndefault database search configuration. The results are obtained by matching the\nquery and the vector.\n\nTo use the ``search`` lookup, ``'django.contrib.postgres'`` must be in your\n:setting:`INSTALLED_APPS`.\n\n.. versionchanged:: 3.1\n\n    Support for query expressions was added.\n\n``SearchVector``\n================\n\n.. class:: SearchVector(*expressions, config=None, weight=None)\n\nSearching against a single field is great but rather limiting. The ``Entry``\ninstances we're searching belong to a ``Blog``, which has a ``tagline`` field.\nTo query against both fields, use a ``SearchVector``::\n\n    >>> from django.contrib.postgres.search import SearchVector\n    >>> Entry.objects.annotate(\n    ...     search=SearchVector('body_text', 'blog__tagline'),\n    ... ).filter(search='Cheese')\n    [<Entry: Cheese on Toast recipes>, <Entry: Pizza Recipes>]\n\nThe arguments to ``SearchVector`` can be any\n:class:`~django.db.models.Expression` or the name of a field. Multiple\narguments will be concatenated together using a space so that the search\ndocument includes them all.\n\n``SearchVector`` objects can be combined together, allowing you to reuse them.\nFor example::\n\n    >>> Entry.objects.annotate(\n    ...     search=SearchVector('body_text') + SearchVector('blog__tagline'),\n    ... ).filter(search='Cheese')\n    [<Entry: Cheese on Toast recipes>, <Entry: Pizza Recipes>]\n\nSee :ref:`postgresql-fts-search-configuration` and\n:ref:`postgresql-fts-weighting-queries` for an explanation of the ``config``\nand ``weight`` parameters.\n\n``SearchQuery``\n===============\n\n.. class:: SearchQuery(value, config=None, search_type='plain')\n\n``SearchQuery`` translates the terms the user provides into a search query\nobject that the database compares to a search vector. By default, all the words\nthe user provides are passed through the stemming algorithms, and then it\nlooks for matches for all of the resulting terms.\n\nIf ``search_type`` is ``'plain'``, which is the default, the terms are treated\nas separate keywords. If ``search_type`` is ``'phrase'``, the terms are treated\nas a single phrase. If ``search_type`` is ``'raw'``, then you can provide a\nformatted search query with terms and operators. If ``search_type`` is\n``'websearch'``, then you can provide a formatted search query, similar to the\none used by web search engines. ``'websearch'`` requires PostgreSQL ≥ 11. Read\nPostgreSQL's `Full Text Search docs`_ to learn about differences and syntax.\nExamples:\n\n.. _Full Text Search docs: https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-PARSING-QUERIES\n\n    >>> from django.contrib.postgres.search import SearchQuery\n    >>> SearchQuery('red tomato')  # two keywords\n    >>> SearchQuery('tomato red')  # same results as above\n    >>> SearchQuery('red tomato', search_type='phrase')  # a phrase\n    >>> SearchQuery('tomato red', search_type='phrase')  # a different phrase\n    >>> SearchQuery(\"'tomato' & ('red' | 'green')\", search_type='raw')  # boolean operators\n    >>> SearchQuery(\"'tomato' ('red' OR 'green')\", search_type='websearch')  # websearch operators\n\n``SearchQuery`` terms can be combined logically to provide more flexibility::\n\n    >>> from django.contrib.postgres.search import SearchQuery\n    >>> SearchQuery('meat') & SearchQuery('cheese')  # AND\n    >>> SearchQuery('meat') | SearchQuery('cheese')  # OR\n    >>> ~SearchQuery('meat')  # NOT\n\nSee :ref:`postgresql-fts-search-configuration` for an explanation of the\n``config`` parameter.\n\n.. versionchanged:: 3.1\n\n    Support for ``'websearch'`` search type and query expressions in\n    ``SearchQuery.value`` were added.\n\n``SearchRank``\n==============\n\n.. class:: SearchRank(vector, query, weights=None, normalization=None, cover_density=False)\n\nSo far, we've returned the results for which any match between the vector and\nthe query are possible. It's likely you may wish to order the results by some\nsort of relevancy. PostgreSQL provides a ranking function which takes into\naccount how often the query terms appear in the document, how close together\nthe terms are in the document, and how important the part of the document is\nwhere they occur. The better the match, the higher the value of the rank. To\norder by relevancy::\n\n    >>> from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector\n    >>> vector = SearchVector('body_text')\n    >>> query = SearchQuery('cheese')\n    >>> Entry.objects.annotate(rank=SearchRank(vector, query)).order_by('-rank')\n    [<Entry: Cheese on Toast recipes>, <Entry: Pizza recipes>]\n\nSee :ref:`postgresql-fts-weighting-queries` for an explanation of the\n``weights`` parameter.\n\nSet the ``cover_density`` parameter to ``True`` to enable the cover density\nranking, which means that the proximity of matching query terms is taken into\naccount.\n\nProvide an integer to the ``normalization`` parameter to control rank\nnormalization. This integer is a bit mask, so you can combine multiple\nbehaviors::\n\n    >>> from django.db.models import Value\n    >>> Entry.objects.annotate(\n    ...     rank=SearchRank(\n    ...         vector,\n    ...         query,\n    ...         normalization=Value(2).bitor(Value(4)),\n    ...     )\n    ... )\n\nThe PostgreSQL documentation has more details about `different rank\nnormalization options`_.\n\n.. _different rank normalization options: https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-RANKING\n\n.. versionadded:: 3.1\n\n    The ``normalization`` and ``cover_density`` parameters were added.\n\n``SearchHeadline``\n==================\n\n.. versionadded:: 3.1\n\n.. class:: SearchHeadline(expression, query, config=None, start_sel=None, stop_sel=None, max_words=None, min_words=None, short_word=None, highlight_all=None, max_fragments=None, fragment_delimiter=None)\n\nAccepts a single text field or an expression, a query, a config, and a set of\noptions. Returns highlighted search results.\n\nSet the ``start_sel`` and ``stop_sel`` parameters to the string values to be\nused to wrap highlighted query terms in the document. PostgreSQL's defaults are\n``<b>`` and ``</b>``.\n\nProvide integer values to the ``max_words`` and ``min_words`` parameters to\ndetermine the longest and shortest headlines. PostgreSQL's defaults are 35 and\n15.\n\nProvide an integer value to the ``short_word`` parameter to discard words of\nthis length or less in each headline. PostgreSQL's default is 3.\n\nSet the ``highlight_all`` parameter to ``True`` to use the whole document in\nplace of a fragment and ignore ``max_words``, ``min_words``, and ``short_word``\nparameters. That's disabled by default in PostgreSQL.\n\nProvide a non-zero integer value to the ``max_fragments`` to set the maximum\nnumber of fragments to display. That's disabled by default in PostgreSQL.\n\nSet the ``fragment_delimiter`` string parameter to configure the delimiter\nbetween fragments. PostgreSQL's default is ``\" ... \"``.\n\nThe PostgreSQL documentation has more details on `highlighting search\nresults`_.\n\nUsage example::\n\n    >>> from django.contrib.postgres.search import SearchHeadline, SearchQuery\n    >>> query = SearchQuery('red tomato')\n    >>> entry = Entry.objects.annotate(\n    ...     headline=SearchHeadline(\n    ...         'body_text',\n    ...         query,\n    ...         start_sel='<span>',\n    ...         stop_sel='</span>',\n    ...     ),\n    ... ).get()\n    >>> print(entry.headline)\n    Sandwich with <span>tomato</span> and <span>red</span> cheese.\n\nSee :ref:`postgresql-fts-search-configuration` for an explanation of the\n``config`` parameter.\n\n.. _highlighting search results: https://www.postgresql.org/docs/current/textsearch-controls.html#TEXTSEARCH-HEADLINE\n\n.. _postgresql-fts-search-configuration:\n\nChanging the search configuration\n=================================\n\nYou can specify the ``config`` attribute to a :class:`SearchVector` and\n:class:`SearchQuery` to use a different search configuration. This allows using\ndifferent language parsers and dictionaries as defined by the database::\n\n    >>> from django.contrib.postgres.search import SearchQuery, SearchVector\n    >>> Entry.objects.annotate(\n    ...     search=SearchVector('body_text', config='french'),\n    ... ).filter(search=SearchQuery('œuf', config='french'))\n    [<Entry: Pain perdu>]\n\nThe value of ``config`` could also be stored in another column::\n\n    >>> from django.db.models import F\n    >>> Entry.objects.annotate(\n    ...     search=SearchVector('body_text', config=F('blog__language')),\n    ... ).filter(search=SearchQuery('œuf', config=F('blog__language')))\n    [<Entry: Pain perdu>]\n\n.. _postgresql-fts-weighting-queries:\n\nWeighting queries\n=================\n\nEvery field may not have the same relevance in a query, so you can set weights\nof various vectors before you combine them::\n\n    >>> from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector\n    >>> vector = SearchVector('body_text', weight='A') + SearchVector('blog__tagline', weight='B')\n    >>> query = SearchQuery('cheese')\n    >>> Entry.objects.annotate(rank=SearchRank(vector, query)).filter(rank__gte=0.3).order_by('rank')\n\nThe weight should be one of the following letters: D, C, B, A. By default,\nthese weights refer to the numbers ``0.1``, ``0.2``, ``0.4``, and ``1.0``,\nrespectively. If you wish to weight them differently, pass a list of four\nfloats to :class:`SearchRank` as ``weights`` in the same order above::\n\n    >>> rank = SearchRank(vector, query, weights=[0.2, 0.4, 0.6, 0.8])\n    >>> Entry.objects.annotate(rank=rank).filter(rank__gte=0.3).order_by('-rank')\n\nPerformance\n===========\n\nSpecial database configuration isn't necessary to use any of these functions,\nhowever, if you're searching more than a few hundred records, you're likely to\nrun into performance problems. Full text search is a more intensive process\nthan comparing the size of an integer, for example.\n\nIn the event that all the fields you're querying on are contained within one\nparticular model, you can create a functional index which matches the search\nvector you wish to use. The PostgreSQL documentation has details on\n`creating indexes for full text search\n<https://www.postgresql.org/docs/current/textsearch-tables.html#TEXTSEARCH-TABLES-INDEX>`_.\n\n``SearchVectorField``\n---------------------\n\n.. class:: SearchVectorField\n\nIf this approach becomes too slow, you can add a ``SearchVectorField`` to your\nmodel. You'll need to keep it populated with triggers, for example, as\ndescribed in the `PostgreSQL documentation`_. You can then query the field as\nif it were an annotated ``SearchVector``::\n\n    >>> Entry.objects.update(search_vector=SearchVector('body_text'))\n    >>> Entry.objects.filter(search_vector='cheese')\n    [<Entry: Cheese on Toast recipes>, <Entry: Pizza recipes>]\n\n.. _PostgreSQL documentation: https://www.postgresql.org/docs/current/textsearch-features.html#TEXTSEARCH-UPDATE-TRIGGERS\n\nTrigram similarity\n==================\n\nAnother approach to searching is trigram similarity. A trigram is a group of\nthree consecutive characters. In addition to the :lookup:`trigram_similar`\nlookup, you can use a couple of other expressions.\n\nTo use them, you need to activate the `pg_trgm extension\n<https://www.postgresql.org/docs/current/pgtrgm.html>`_ on PostgreSQL. You can\ninstall it using the\n:class:`~django.contrib.postgres.operations.TrigramExtension` migration\noperation.\n\n``TrigramSimilarity``\n---------------------\n\n.. class:: TrigramSimilarity(expression, string, **extra)\n\nAccepts a field name or expression, and a string or expression. Returns the\ntrigram similarity between the two arguments.\n\nUsage example::\n\n    >>> from django.contrib.postgres.search import TrigramSimilarity\n    >>> Author.objects.create(name='Katy Stevens')\n    >>> Author.objects.create(name='Stephen Keats')\n    >>> test = 'Katie Stephens'\n    >>> Author.objects.annotate(\n    ...     similarity=TrigramSimilarity('name', test),\n    ... ).filter(similarity__gt=0.3).order_by('-similarity')\n    [<Author: Katy Stevens>, <Author: Stephen Keats>]\n\n``TrigramDistance``\n-------------------\n\n.. class:: TrigramDistance(expression, string, **extra)\n\nAccepts a field name or expression, and a string or expression. Returns the\ntrigram distance between the two arguments.\n\nUsage example::\n\n    >>> from django.contrib.postgres.search import TrigramDistance\n    >>> Author.objects.create(name='Katy Stevens')\n    >>> Author.objects.create(name='Stephen Keats')\n    >>> test = 'Katie Stephens'\n    >>> Author.objects.annotate(\n    ...     distance=TrigramDistance('name', test),\n    ... ).filter(distance__lte=0.7).order_by('distance')\n    [<Author: Katy Stevens>, <Author: Stephen Keats>]\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":152,"nodeType":"Package","repoName":null,"name":"docs/ref/templates","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":153,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/ref/templates","text":"=========\nTemplates\n=========\n\nDjango's template engine provides a powerful mini-language for defining the\nuser-facing layer of your application, encouraging a clean separation of\napplication and presentation logic. Templates can be maintained by anyone with\nan understanding of HTML; no knowledge of Python is required. For introductory\nmaterial, see :doc:`/topics/templates` topic guide.\n\n.. toctree::\n   :maxdepth: 2\n\n   language\n   builtins\n   api\n\n.. seealso::\n\n    For information on writing your own custom tags and filters, see\n    :doc:`/howto/custom-template-tags`.\n\n    To learn how to override templates in other Django applications, see\n    :doc:`/howto/overriding-templates`.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":154,"nodeType":"TextFile","repoName":null,"name":"functions.txt","path":"docs/ref/contrib/postgres","text":"======================================\nPostgreSQL specific database functions\n======================================\n\nAll of these functions are available from the\n``django.contrib.postgres.functions`` module.\n\n.. currentmodule:: django.contrib.postgres.functions\n\n``RandomUUID``\n==============\n\n.. class:: RandomUUID()\n\nReturns a version 4 UUID.\n\nThe `pgcrypto extension`_ must be installed. You can use the\n:class:`~django.contrib.postgres.operations.CryptoExtension` migration\noperation to install it.\n\n.. _pgcrypto extension: https://www.postgresql.org/docs/current/pgcrypto.html\n\nUsage example::\n\n    >>> from django.contrib.postgres.functions import RandomUUID\n    >>> Article.objects.update(uuid=RandomUUID())\n\n``TransactionNow``\n==================\n\n.. class:: TransactionNow()\n\nReturns the date and time on the database server that the current transaction\nstarted. If you are not in a transaction it will return the date and time of\nthe current statement. This is a complement to\n:class:`django.db.models.functions.Now`, which returns the date and time of the\ncurrent statement.\n\nNote that only the outermost call to :func:`~django.db.transaction.atomic()`\nsets up a transaction and thus sets the time that ``TransactionNow()`` will\nreturn; nested calls create savepoints which do not affect the transaction\ntime.\n\nUsage example::\n\n    >>> from django.contrib.postgres.functions import TransactionNow\n    >>> Article.objects.filter(published__lte=TransactionNow())\n    <QuerySet [<Article: How to Django>]>\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":155,"nodeType":"Package","repoName":null,"name":"docs/ref/class-based-views","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":156,"nodeType":"TextFile","repoName":null,"name":"mixins.txt","path":"docs/ref/class-based-views","text":"========================\nClass-based views mixins\n========================\n\nClass-based views API reference. For introductory material, see :doc:`/topics/class-based-views/mixins`.\n\n.. toctree::\n   :maxdepth: 1\n\n   mixins-simple\n   mixins-single-object\n   mixins-multiple-object\n   mixins-editing\n   mixins-date-based\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":157,"nodeType":"TextFile","repoName":null,"name":"actions.txt","path":"docs/ref/contrib/admin","text":"=============\nAdmin actions\n=============\n\n.. currentmodule:: django.contrib.admin\n\nThe basic workflow of Django's admin is, in a nutshell, \"select an object,\nthen change it.\" This works well for a majority of use cases. However, if you\nneed to make the same change to many objects at once, this workflow can be\nquite tedious.\n\nIn these cases, Django's admin lets you write and register \"actions\" --\nfunctions that get called with a list of objects selected on the change list\npage.\n\nIf you look at any change list in the admin, you'll see this feature in\naction; Django ships with a \"delete selected objects\" action available to all\nmodels. For example, here's the user module from Django's built-in\n:mod:`django.contrib.auth` app:\n\n.. image:: _images/admin-actions.png\n\n.. warning::\n\n    The \"delete selected objects\" action uses :meth:`QuerySet.delete()\n    <django.db.models.query.QuerySet.delete>` for efficiency reasons, which\n    has an important caveat: your model's ``delete()`` method will not be\n    called.\n\n    If you wish to override this behavior, you can override\n    :meth:`.ModelAdmin.delete_queryset` or write a custom action which does\n    deletion in your preferred manner -- for example, by calling\n    ``Model.delete()`` for each of the selected items.\n\n    For more background on bulk deletion, see the documentation on :ref:`object\n    deletion <topics-db-queries-delete>`.\n\nRead on to find out how to add your own actions to this list.\n\nWriting actions\n===============\n\nThe easiest way to explain actions is by example, so let's dive in.\n\nA common use case for admin actions is the bulk updating of a model. Imagine a\nnews application with an ``Article`` model::\n\n    from django.db import models\n\n    STATUS_CHOICES = [\n        ('d', 'Draft'),\n        ('p', 'Published'),\n        ('w', 'Withdrawn'),\n    ]\n\n    class Article(models.Model):\n        title = models.CharField(max_length=100)\n        body = models.TextField()\n        status = models.CharField(max_length=1, choices=STATUS_CHOICES)\n\n        def __str__(self):\n            return self.title\n\nA common task we might perform with a model like this is to update an\narticle's status from \"draft\" to \"published\". We could easily do this in the\nadmin one article at a time, but if we wanted to bulk-publish a group of\narticles, it'd be tedious. So, let's write an action that lets us change an\narticle's status to \"published.\"\n\nWriting action functions\n------------------------\n\nFirst, we'll need to write a function that gets called when the action is\ntriggered from the admin. Action functions are regular functions that take\nthree arguments:\n\n* The current :class:`ModelAdmin`\n* An :class:`~django.http.HttpRequest` representing the current request,\n* A :class:`~django.db.models.query.QuerySet` containing the set of\n  objects selected by the user.\n\nOur publish-these-articles function won't need the :class:`ModelAdmin` or the\nrequest object, but we will use the queryset::\n\n    def make_published(modeladmin, request, queryset):\n        queryset.update(status='p')\n\n.. note::\n\n    For the best performance, we're using the queryset's :ref:`update method\n    <topics-db-queries-update>`. Other types of actions might need to deal\n    with each object individually; in these cases we'd iterate over the\n    queryset::\n\n        for obj in queryset:\n            do_something_with(obj)\n\nThat's actually all there is to writing an action! However, we'll take one\nmore optional-but-useful step and give the action a \"nice\" title in the admin.\nBy default, this action would appear in the action list as \"Make published\" --\nthe function name, with underscores replaced by spaces. That's fine, but we\ncan provide a better, more human-friendly name by giving the\n``make_published`` function a ``short_description`` attribute::\n\n    def make_published(modeladmin, request, queryset):\n        queryset.update(status='p')\n    make_published.short_description = \"Mark selected stories as published\"\n\n.. note::\n\n    This might look familiar; the admin's ``list_display`` option uses the\n    same technique to provide human-readable descriptions for callback\n    functions registered there, too.\n\nAdding actions to the :class:`ModelAdmin`\n-----------------------------------------\n\nNext, we'll need to inform our :class:`ModelAdmin` of the action. This works\njust like any other configuration option. So, the complete ``admin.py`` with\nthe action and its registration would look like::\n\n    from django.contrib import admin\n    from myapp.models import Article\n\n    def make_published(modeladmin, request, queryset):\n        queryset.update(status='p')\n    make_published.short_description = \"Mark selected stories as published\"\n\n    class ArticleAdmin(admin.ModelAdmin):\n        list_display = ['title', 'status']\n        ordering = ['title']\n        actions = [make_published]\n\n    admin.site.register(Article, ArticleAdmin)\n\nThat code will give us an admin change list that looks something like this:\n\n.. image:: _images/adding-actions-to-the-modeladmin.png\n\nThat's really all there is to it! If you're itching to write your own actions,\nyou now know enough to get started. The rest of this document covers more\nadvanced techniques.\n\nHandling errors in actions\n--------------------------\n\nIf there are foreseeable error conditions that may occur while running your\naction, you should gracefully inform the user of the problem. This means\nhandling exceptions and using\n:meth:`django.contrib.admin.ModelAdmin.message_user` to display a user friendly\ndescription of the problem in the response.\n\nAdvanced action techniques\n==========================\n\nThere's a couple of extra options and possibilities you can exploit for more\nadvanced options.\n\nActions as :class:`ModelAdmin` methods\n--------------------------------------\n\nThe example above shows the ``make_published`` action defined as a function.\nThat's perfectly fine, but it's not perfect from a code design point of view:\nsince the action is tightly coupled to the ``Article`` object, it makes sense\nto hook the action to the ``ArticleAdmin`` object itself.\n\nYou can do it like this::\n\n    class ArticleAdmin(admin.ModelAdmin):\n        ...\n\n        actions = ['make_published']\n\n        def make_published(self, request, queryset):\n            queryset.update(status='p')\n        make_published.short_description = \"Mark selected stories as published\"\n\nNotice first that we've moved ``make_published`` into a method and renamed the\n``modeladmin`` parameter to ``self``, and second that we've now put the string\n``'make_published'`` in ``actions`` instead of a direct function reference. This\ntells the :class:`ModelAdmin` to look up the action as a method.\n\nDefining actions as methods gives the action more idiomatic access to the\n:class:`ModelAdmin` itself, allowing the action to call any of the methods\nprovided by the admin.\n\n.. _custom-admin-action:\n\nFor example, we can use ``self`` to flash a message to the user informing her\nthat the action was successful::\n\n    from django.contrib import messages\n    from django.utils.translation import ngettext\n\n    class ArticleAdmin(admin.ModelAdmin):\n        ...\n\n        def make_published(self, request, queryset):\n            updated = queryset.update(status='p')\n            self.message_user(request, ngettext(\n                '%d story was successfully marked as published.',\n                '%d stories were successfully marked as published.',\n                updated,\n            ) % updated, messages.SUCCESS)\n\nThis make the action match what the admin itself does after successfully\nperforming an action:\n\n.. image:: _images/actions-as-modeladmin-methods.png\n\nActions that provide intermediate pages\n---------------------------------------\n\nBy default, after an action is performed the user is redirected back to the\noriginal change list page. However, some actions, especially more complex ones,\nwill need to return intermediate pages. For example, the built-in delete action\nasks for confirmation before deleting the selected objects.\n\nTo provide an intermediary page, return an :class:`~django.http.HttpResponse`\n(or subclass) from your action. For example, you might write a export function\nthat uses Django's :doc:`serialization functions </topics/serialization>` to\ndump some selected objects as JSON::\n\n    from django.core import serializers\n    from django.http import HttpResponse\n\n    def export_as_json(modeladmin, request, queryset):\n        response = HttpResponse(content_type=\"application/json\")\n        serializers.serialize(\"json\", queryset, stream=response)\n        return response\n\nGenerally, something like the above isn't considered a great idea. Most of the\ntime, the best practice will be to return an\n:class:`~django.http.HttpResponseRedirect` and redirect the user to a view\nyou've written, passing the list of selected objects in the GET query string.\nThis allows you to provide complex interaction logic on the intermediary\npages. For example, if you wanted to provide a more complete export function,\nyou'd want to let the user choose a format, and possibly a list of fields to\ninclude in the export. The best thing to do would be to write a small action\nthat redirects to your custom export view::\n\n    from django.contrib.contenttypes.models import ContentType\n    from django.http import HttpResponseRedirect\n\n    def export_selected_objects(modeladmin, request, queryset):\n        selected = queryset.values_list('pk', flat=True)\n        ct = ContentType.objects.get_for_model(queryset.model)\n        return HttpResponseRedirect('/export/?ct=%s&ids=%s' % (\n            ct.pk,\n            ','.join(str(pk) for pk in selected),\n        ))\n\nAs you can see, the action is rather short; all the complex logic would belong\nin your export view. This would need to deal with objects of any type, hence\nthe business with the ``ContentType``.\n\nWriting this view is left as an exercise to the reader.\n\n.. _adminsite-actions:\n\nMaking actions available site-wide\n----------------------------------\n\n.. method:: AdminSite.add_action(action, name=None)\n\n    Some actions are best if they're made available to *any* object in the admin\n    site -- the export action defined above would be a good candidate. You can\n    make an action globally available using :meth:`AdminSite.add_action()`. For\n    example::\n\n        from django.contrib import admin\n\n        admin.site.add_action(export_selected_objects)\n\n    This makes the ``export_selected_objects`` action globally available as an\n    action named \"export_selected_objects\". You can explicitly give the action\n    a name -- good if you later want to programmatically :ref:`remove the action\n    <disabling-admin-actions>` -- by passing a second argument to\n    :meth:`AdminSite.add_action()`::\n\n        admin.site.add_action(export_selected_objects, 'export_selected')\n\n.. _disabling-admin-actions:\n\nDisabling actions\n-----------------\n\nSometimes you need to disable certain actions -- especially those\n:ref:`registered site-wide <adminsite-actions>` -- for particular objects.\nThere's a few ways you can disable actions:\n\nDisabling a site-wide action\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. method:: AdminSite.disable_action(name)\n\n    If you need to disable a :ref:`site-wide action <adminsite-actions>` you can\n    call :meth:`AdminSite.disable_action()`.\n\n    For example, you can use this method to remove the built-in \"delete selected\n    objects\" action::\n\n        admin.site.disable_action('delete_selected')\n\n    Once you've done the above, that action will no longer be available\n    site-wide.\n\n    If, however, you need to re-enable a globally-disabled action for one\n    particular model, list it explicitly in your ``ModelAdmin.actions`` list::\n\n        # Globally disable delete selected\n        admin.site.disable_action('delete_selected')\n\n        # This ModelAdmin will not have delete_selected available\n        class SomeModelAdmin(admin.ModelAdmin):\n            actions = ['some_other_action']\n            ...\n\n        # This one will\n        class AnotherModelAdmin(admin.ModelAdmin):\n            actions = ['delete_selected', 'a_third_action']\n            ...\n\n\nDisabling all actions for a particular :class:`ModelAdmin`\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf you want *no* bulk actions available for a given :class:`ModelAdmin`, set\n:attr:`ModelAdmin.actions` to ``None``::\n\n    class MyModelAdmin(admin.ModelAdmin):\n        actions = None\n\nThis tells the :class:`ModelAdmin` to not display or allow any actions,\nincluding any :ref:`site-wide actions <adminsite-actions>`.\n\nConditionally enabling or disabling actions\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. method:: ModelAdmin.get_actions(request)\n\n    Finally, you can conditionally enable or disable actions on a per-request\n    (and hence per-user basis) by overriding :meth:`ModelAdmin.get_actions`.\n\n    This returns a dictionary of actions allowed. The keys are action names, and\n    the values are ``(function, name, short_description)`` tuples.\n\n    For example, if you only want users whose names begin with 'J' to be able\n    to delete objects in bulk::\n\n        class MyModelAdmin(admin.ModelAdmin):\n            ...\n\n            def get_actions(self, request):\n                actions = super().get_actions(request)\n                if request.user.username[0].upper() != 'J':\n                    if 'delete_selected' in actions:\n                        del actions['delete_selected']\n                return actions\n\n.. _admin-action-permissions:\n\nSetting permissions for actions\n-------------------------------\n\nActions may limit their availability to users with specific permissions by\nsetting an ``allowed_permissions`` attribute on the action function::\n\n    def make_published(modeladmin, request, queryset):\n        queryset.update(status='p')\n    make_published.allowed_permissions = ('change',)\n\nThe ``make_published()`` action will only be available to users that pass the\n:meth:`.ModelAdmin.has_change_permission` check.\n\nIf ``allowed_permissions`` has more than one permission, the action will be\navailable as long as the user passes at least one of the checks.\n\nAvailable values for ``allowed_permissions`` and the corresponding method\nchecks are:\n\n- ``'add'``: :meth:`.ModelAdmin.has_add_permission`\n- ``'change'``: :meth:`.ModelAdmin.has_change_permission`\n- ``'delete'``: :meth:`.ModelAdmin.has_delete_permission`\n- ``'view'``: :meth:`.ModelAdmin.has_view_permission`\n\nYou can specify any other value as long as you implement a corresponding\n``has_<value>_permission(self, request)`` method on the ``ModelAdmin``.\n\nFor example::\n\n    from django.contrib import admin\n    from django.contrib.auth import get_permission_codename\n\n    class ArticleAdmin(admin.ModelAdmin):\n        actions = ['make_published']\n\n        def make_published(self, request, queryset):\n            queryset.update(status='p')\n        make_published.allowed_permissions = ('publish',)\n\n        def has_publish_permission(self, request):\n            \"\"\"Does the user have the publish permission?\"\"\"\n            opts = self.opts\n            codename = get_permission_codename('publish', opts)\n            return request.user.has_perm('%s.%s' % (opts.app_label, codename))\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":158,"nodeType":"TextFile","repoName":null,"name":"generic-editing.txt","path":"docs/ref/class-based-views","text":"=====================\nGeneric editing views\n=====================\n\nThe following views are described on this page and provide a foundation for\nediting content:\n\n* :class:`django.views.generic.edit.FormView`\n* :class:`django.views.generic.edit.CreateView`\n* :class:`django.views.generic.edit.UpdateView`\n* :class:`django.views.generic.edit.DeleteView`\n\n.. seealso::\n\n    The :doc:`messages framework </ref/contrib/messages>` contains\n    :class:`~django.contrib.messages.views.SuccessMessageMixin`, which\n    facilitates presenting messages about successful form submissions.\n\n.. note::\n\n    Some of the examples on this page assume that an ``Author`` model has been\n    defined as follows in ``myapp/models.py``::\n\n        from django.db import models\n        from django.urls import reverse\n\n        class Author(models.Model):\n            name = models.CharField(max_length=200)\n\n            def get_absolute_url(self):\n                return reverse('author-detail', kwargs={'pk': self.pk})\n\n``FormView``\n============\n\n.. class:: django.views.generic.edit.FormView\n\n    A view that displays a form. On error, redisplays the form with validation\n    errors; on success, redirects to a new URL.\n\n    **Ancestors (MRO)**\n\n    This view inherits methods and attributes from the following views:\n\n    * :class:`django.views.generic.base.TemplateResponseMixin`\n    * ``django.views.generic.edit.BaseFormView``\n    * :class:`django.views.generic.edit.FormMixin`\n    * :class:`django.views.generic.edit.ProcessFormView`\n    * :class:`django.views.generic.base.View`\n\n    **Example myapp/forms.py**::\n\n        from django import forms\n\n        class ContactForm(forms.Form):\n            name = forms.CharField()\n            message = forms.CharField(widget=forms.Textarea)\n\n            def send_email(self):\n                # send email using the self.cleaned_data dictionary\n                pass\n\n    **Example myapp/views.py**::\n\n        from myapp.forms import ContactForm\n        from django.views.generic.edit import FormView\n\n        class ContactView(FormView):\n            template_name = 'contact.html'\n            form_class = ContactForm\n            success_url = '/thanks/'\n\n            def form_valid(self, form):\n                # This method is called when valid form data has been POSTed.\n                # It should return an HttpResponse.\n                form.send_email()\n                return super().form_valid(form)\n\n    **Example myapp/contact.html**:\n\n    .. code-block:: html+django\n\n        <form method=\"post\">{% csrf_token %}\n            {{ form.as_p }}\n            <input type=\"submit\" value=\"Send message\">\n        </form>\n\n\n``CreateView``\n==============\n\n.. class:: django.views.generic.edit.CreateView\n\n    A view that displays a form for creating an object, redisplaying the form\n    with validation errors (if there are any) and saving the object.\n\n    **Ancestors (MRO)**\n\n    This view inherits methods and attributes from the following views:\n\n    * :class:`django.views.generic.detail.SingleObjectTemplateResponseMixin`\n    * :class:`django.views.generic.base.TemplateResponseMixin`\n    * ``django.views.generic.edit.BaseCreateView``\n    * :class:`django.views.generic.edit.ModelFormMixin`\n    * :class:`django.views.generic.edit.FormMixin`\n    * :class:`django.views.generic.detail.SingleObjectMixin`\n    * :class:`django.views.generic.edit.ProcessFormView`\n    * :class:`django.views.generic.base.View`\n\n    **Attributes**\n\n    .. attribute:: template_name_suffix\n\n        The ``CreateView`` page displayed to a ``GET`` request uses a\n        ``template_name_suffix`` of ``'_form'``. For\n        example, changing this attribute to ``'_create_form'`` for a view\n        creating objects for the example ``Author`` model would cause the\n        default ``template_name`` to be ``'myapp/author_create_form.html'``.\n\n    .. attribute:: object\n\n        When using ``CreateView`` you have access to ``self.object``, which is\n        the object being created. If the object hasn't been created yet, the\n        value will be ``None``.\n\n    **Example myapp/views.py**::\n\n        from django.views.generic.edit import CreateView\n        from myapp.models import Author\n\n        class AuthorCreate(CreateView):\n            model = Author\n            fields = ['name']\n\n    **Example myapp/author_form.html**:\n\n    .. code-block:: html+django\n\n        <form method=\"post\">{% csrf_token %}\n            {{ form.as_p }}\n            <input type=\"submit\" value=\"Save\">\n        </form>\n\n``UpdateView``\n==============\n\n.. class:: django.views.generic.edit.UpdateView\n\n    A view that displays a form for editing an existing object, redisplaying\n    the form with validation errors (if there are any) and saving changes to\n    the object. This uses a form automatically generated from the object's\n    model class (unless a form class is manually specified).\n\n    **Ancestors (MRO)**\n\n    This view inherits methods and attributes from the following views:\n\n    * :class:`django.views.generic.detail.SingleObjectTemplateResponseMixin`\n    * :class:`django.views.generic.base.TemplateResponseMixin`\n    * ``django.views.generic.edit.BaseUpdateView``\n    * :class:`django.views.generic.edit.ModelFormMixin`\n    * :class:`django.views.generic.edit.FormMixin`\n    * :class:`django.views.generic.detail.SingleObjectMixin`\n    * :class:`django.views.generic.edit.ProcessFormView`\n    * :class:`django.views.generic.base.View`\n\n    **Attributes**\n\n    .. attribute:: template_name_suffix\n\n        The ``UpdateView`` page displayed to a ``GET`` request uses a\n        ``template_name_suffix`` of ``'_form'``. For\n        example, changing this attribute to ``'_update_form'`` for a view\n        updating objects for the example ``Author`` model would cause the\n        default ``template_name`` to be ``'myapp/author_update_form.html'``.\n\n    .. attribute:: object\n\n        When using ``UpdateView`` you have access to ``self.object``, which is\n        the object being updated.\n\n    **Example myapp/views.py**::\n\n        from django.views.generic.edit import UpdateView\n        from myapp.models import Author\n\n        class AuthorUpdate(UpdateView):\n            model = Author\n            fields = ['name']\n            template_name_suffix = '_update_form'\n\n    **Example myapp/author_update_form.html**:\n\n    .. code-block:: html+django\n\n        <form method=\"post\">{% csrf_token %}\n            {{ form.as_p }}\n            <input type=\"submit\" value=\"Update\">\n        </form>\n\n``DeleteView``\n==============\n\n.. class:: django.views.generic.edit.DeleteView\n\n    A view that displays a confirmation page and deletes an existing object.\n    The given object will only be deleted if the request method is ``POST``. If\n    this view is fetched via ``GET``, it will display a confirmation page that\n    should contain a form that POSTs to the same URL.\n\n    **Ancestors (MRO)**\n\n    This view inherits methods and attributes from the following views:\n\n    * :class:`django.views.generic.detail.SingleObjectTemplateResponseMixin`\n    * :class:`django.views.generic.base.TemplateResponseMixin`\n    * ``django.views.generic.edit.BaseDeleteView``\n    * :class:`django.views.generic.edit.DeletionMixin`\n    * ``django.views.generic.detail.BaseDetailView``\n    * :class:`django.views.generic.detail.SingleObjectMixin`\n    * :class:`django.views.generic.base.View`\n\n    **Attributes**\n\n    .. attribute:: template_name_suffix\n\n        The ``DeleteView`` page displayed to a ``GET`` request uses a\n        ``template_name_suffix`` of ``'_confirm_delete'``. For\n        example, changing this attribute to ``'_check_delete'`` for a view\n        deleting objects for the example ``Author`` model would cause the\n        default ``template_name`` to be ``'myapp/author_check_delete.html'``.\n\n    **Example myapp/views.py**::\n\n        from django.urls import reverse_lazy\n        from django.views.generic.edit import DeleteView\n        from myapp.models import Author\n\n        class AuthorDelete(DeleteView):\n            model = Author\n            success_url = reverse_lazy('author-list')\n\n    **Example myapp/author_confirm_delete.html**:\n\n    .. code-block:: html+django\n\n        <form method=\"post\">{% csrf_token %}\n            <p>Are you sure you want to delete \"{{ object }}\"?</p>\n            <input type=\"submit\" value=\"Confirm\">\n        </form>\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":159,"nodeType":"TextFile","repoName":null,"name":"base.txt","path":"docs/ref/class-based-views","text":"==========\nBase views\n==========\n\nThe following three classes provide much of the functionality needed to create\nDjango views. You may think of them as *parent* views, which can be used by\nthemselves or inherited from. They may not provide all the capabilities\nrequired for projects, in which case there are Mixins and Generic class-based\nviews.\n\nMany of Django's built-in class-based views inherit from other class-based\nviews or various mixins. Because this inheritance chain is very important, the\nancestor classes are  documented under the section title of **Ancestors (MRO)**.\nMRO is an acronym for Method Resolution Order.\n\n``View``\n========\n\n.. class:: django.views.generic.base.View\n\n    The master class-based base view. All other class-based views inherit from\n    this base class. It isn't strictly a generic view and thus can also be\n    imported from ``django.views``.\n\n    **Method Flowchart**\n\n    #. :meth:`setup()`\n    #. :meth:`dispatch()`\n    #. :meth:`http_method_not_allowed()`\n    #. :meth:`options()`\n\n    **Example views.py**::\n\n        from django.http import HttpResponse\n        from django.views import View\n\n        class MyView(View):\n\n            def get(self, request, *args, **kwargs):\n                return HttpResponse('Hello, World!')\n\n    **Example urls.py**::\n\n        from django.urls import path\n\n        from myapp.views import MyView\n\n        urlpatterns = [\n            path('mine/', MyView.as_view(), name='my-view'),\n        ]\n\n    **Attributes**\n\n    .. attribute:: http_method_names\n\n        The list of HTTP method names that this view will accept.\n\n        Default::\n\n            ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']\n\n    **Methods**\n\n    .. classmethod:: as_view(**initkwargs)\n\n        Returns a callable view that takes a request and returns a response::\n\n            response = MyView.as_view()(request)\n\n        The returned view has ``view_class`` and ``view_initkwargs``\n        attributes.\n\n        When the view is called during the request/response cycle, the\n        :meth:`setup` method assigns the :class:`~django.http.HttpRequest` to\n        the view's ``request`` attribute, and any positional and/or keyword\n        arguments :ref:`captured from the URL pattern\n        <how-django-processes-a-request>` to the ``args`` and ``kwargs``\n        attributes, respectively. Then :meth:`dispatch` is called.\n\n    .. method:: setup(request, *args, **kwargs)\n\n        Performs key view initialization prior to :meth:`dispatch`.\n\n        If overriding this method, you must call ``super()``.\n\n    .. method:: dispatch(request, *args, **kwargs)\n\n        The ``view`` part of the view -- the method that accepts a ``request``\n        argument plus arguments, and returns a HTTP response.\n\n        The default implementation will inspect the HTTP method and attempt to\n        delegate to a method that matches the HTTP method; a ``GET`` will be\n        delegated to ``get()``, a ``POST`` to ``post()``, and so on.\n\n        By default, a ``HEAD`` request will be delegated to ``get()``.\n        If you need to handle ``HEAD`` requests in a different way than ``GET``,\n        you can override the ``head()`` method. See\n        :ref:`supporting-other-http-methods` for an example.\n\n    .. method:: http_method_not_allowed(request, *args, **kwargs)\n\n        If the view was called with a HTTP method it doesn't support, this\n        method is called instead.\n\n        The default implementation returns ``HttpResponseNotAllowed`` with a\n        list of allowed methods in plain text.\n\n    .. method:: options(request, *args, **kwargs)\n\n        Handles responding to requests for the OPTIONS HTTP verb. Returns a\n        response with the ``Allow`` header containing a list of the view's\n        allowed HTTP method names.\n\n\n``TemplateView``\n================\n\n.. class:: django.views.generic.base.TemplateView\n\n    Renders a given template.\n\n    **Ancestors (MRO)**\n\n    This view inherits methods and attributes from the following views:\n\n    * :class:`django.views.generic.base.TemplateResponseMixin`\n    * :class:`django.views.generic.base.ContextMixin`\n    * :class:`django.views.generic.base.View`\n\n    **Method Flowchart**\n\n    #. :meth:`~django.views.generic.base.View.setup()`\n    #. :meth:`~django.views.generic.base.View.dispatch()`\n    #. :meth:`~django.views.generic.base.View.http_method_not_allowed()`\n    #. :meth:`~django.views.generic.base.ContextMixin.get_context_data()`\n\n    **Example views.py**::\n\n        from django.views.generic.base import TemplateView\n\n        from articles.models import Article\n\n        class HomePageView(TemplateView):\n\n            template_name = \"home.html\"\n\n            def get_context_data(self, **kwargs):\n                context = super().get_context_data(**kwargs)\n                context['latest_articles'] = Article.objects.all()[:5]\n                return context\n\n    **Example urls.py**::\n\n        from django.urls import path\n\n        from myapp.views import HomePageView\n\n        urlpatterns = [\n            path('', HomePageView.as_view(), name='home'),\n        ]\n\n    **Context**\n\n    * Populated (through :class:`~django.views.generic.base.ContextMixin`).\n    * You can also add context using the\n      :attr:`~django.views.generic.base.ContextMixin.extra_context` keyword\n      argument for :meth:`~django.views.generic.base.View.as_view`.\n\n    .. deprecated:: 3.1\n\n        Starting in Django 4.0, the keyword arguments captured from the URL\n        pattern won't be passed to the context. Reference them with\n        ``view.kwargs`` instead.\n\n``RedirectView``\n================\n\n.. class:: django.views.generic.base.RedirectView\n\n    Redirects to a given URL.\n\n    The given URL may contain dictionary-style string formatting, which will be\n    interpolated against the parameters captured in the URL. Because keyword\n    interpolation is *always* done (even if no arguments are passed in), any\n    ``\"%\"`` characters in the URL must be written as ``\"%%\"`` so that Python\n    will convert them to a single percent sign on output.\n\n    If the given URL is ``None``, Django will return an ``HttpResponseGone``\n    (410).\n\n    **Ancestors (MRO)**\n\n    This view inherits methods and attributes from the following view:\n\n    * :class:`django.views.generic.base.View`\n\n    **Method Flowchart**\n\n    #. :meth:`~django.views.generic.base.View.setup()`\n    #. :meth:`~django.views.generic.base.View.dispatch()`\n    #. :meth:`~django.views.generic.base.View.http_method_not_allowed()`\n    #. :meth:`get_redirect_url()`\n\n    **Example views.py**::\n\n        from django.shortcuts import get_object_or_404\n        from django.views.generic.base import RedirectView\n\n        from articles.models import Article\n\n        class ArticleCounterRedirectView(RedirectView):\n\n            permanent = False\n            query_string = True\n            pattern_name = 'article-detail'\n\n            def get_redirect_url(self, *args, **kwargs):\n                article = get_object_or_404(Article, pk=kwargs['pk'])\n                article.update_counter()\n                return super().get_redirect_url(*args, **kwargs)\n\n    **Example urls.py**::\n\n        from django.urls import path\n        from django.views.generic.base import RedirectView\n\n        from article.views import ArticleCounterRedirectView, ArticleDetail\n\n        urlpatterns = [\n            path('counter/<int:pk>/', ArticleCounterRedirectView.as_view(), name='article-counter'),\n            path('details/<int:pk>/', ArticleDetail.as_view(), name='article-detail'),\n            path('go-to-django/', RedirectView.as_view(url='https://djangoproject.com'), name='go-to-django'),\n        ]\n\n    **Attributes**\n\n    .. attribute:: url\n\n        The URL to redirect to, as a string. Or ``None`` to raise a 410 (Gone)\n        HTTP error.\n\n    .. attribute:: pattern_name\n\n        The name of the URL pattern to redirect to. Reversing will be done\n        using the same args and kwargs as are passed in for this view.\n\n    .. attribute:: permanent\n\n        Whether the redirect should be permanent. The only difference here is\n        the HTTP status code returned. If ``True``, then the redirect will use\n        status code 301. If ``False``, then the redirect will use status code\n        302. By default, ``permanent`` is ``False``.\n\n    .. attribute:: query_string\n\n        Whether to pass along the GET query string to the new location. If\n        ``True``, then the query string is appended to the URL. If ``False``,\n        then the query string is discarded. By default, ``query_string`` is\n        ``False``.\n\n    **Methods**\n\n    .. method:: get_redirect_url(*args, **kwargs)\n\n        Constructs the target URL for redirection.\n\n        The ``args`` and ``kwargs`` arguments are positional and/or keyword\n        arguments :ref:`captured from the URL pattern\n        <how-django-processes-a-request>`, respectively.\n\n        The default implementation uses :attr:`url` as a starting\n        string and performs expansion of ``%`` named parameters in that string\n        using the named groups captured in the URL.\n\n        If :attr:`url` is not set, ``get_redirect_url()`` tries to reverse the\n        :attr:`pattern_name` using what was captured in the URL (both named and\n        unnamed groups are used).\n\n        If requested by :attr:`query_string`, it will also append the query\n        string to the generated URL.\n        Subclasses may implement any behavior they wish, as long as the method\n        returns a redirect-ready URL string.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":160,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/ref/contrib/admin","text":"=====================\nThe Django admin site\n=====================\n\n.. module:: django.contrib.admin\n   :synopsis: Django's admin site.\n\nOne of the most powerful parts of Django is the automatic admin interface. It\nreads metadata from your models to provide a quick, model-centric interface\nwhere trusted users can manage content on your site. The admin's recommended\nuse is limited to an organization's internal management tool. It's not intended\nfor building your entire front end around.\n\nThe admin has many hooks for customization, but beware of trying to use those\nhooks exclusively. If you need to provide a more process-centric interface\nthat abstracts away the implementation details of database tables and fields,\nthen it's probably time to write your own views.\n\nIn this document we discuss how to activate, use, and customize Django's admin\ninterface.\n\nOverview\n========\n\nThe admin is enabled in the default project template used by\n:djadmin:`startproject`.\n\nIf you're not using the default project template, here are the requirements:\n\n#. Add ``'django.contrib.admin'`` and its dependencies -\n   :mod:`django.contrib.auth`, :mod:`django.contrib.contenttypes`,\n   :mod:`django.contrib.messages`, and :mod:`django.contrib.sessions` - to your\n   :setting:`INSTALLED_APPS` setting.\n\n#. Configure a :class:`~django.template.backends.django.DjangoTemplates`\n   backend in your :setting:`TEMPLATES` setting with\n   ``django.contrib.auth.context_processors.auth``,\n   ``django.contrib.messages.context_processors.request``, and\n   ``django.contrib.messages.context_processors.messages`` in\n   the ``'context_processors'`` option of :setting:`OPTIONS\n   <TEMPLATES-OPTIONS>`.\n\n   .. versionchanged:: 3.1\n\n       ``django.contrib.messages.context_processors.request`` was added as a\n       requirement in the ``'context_processors'`` option to support the new\n       :attr:`.AdminSite.enable_nav_sidebar`.\n\n#. If you've customized the :setting:`MIDDLEWARE` setting,\n   :class:`django.contrib.auth.middleware.AuthenticationMiddleware` and\n   :class:`django.contrib.messages.middleware.MessageMiddleware` must be\n   included.\n\n#. :ref:`Hook the admin's URLs into your URLconf\n   <hooking-adminsite-to-urlconf>`.\n\nAfter you've taken these steps, you'll be able to use the admin site by\nvisiting the URL you hooked it into (``/admin/``, by default).\n\nIf you need to create a user to login with, use the :djadmin:`createsuperuser`\ncommand. By default, logging in to the admin requires that the user has the\n:attr:`~.User.is_superuser` or :attr:`~.User.is_staff` attribute set to\n``True``.\n\nFinally, determine which of your application's models should be editable in the\nadmin interface. For each of those models, register them with the admin as\ndescribed in :class:`ModelAdmin`.\n\nOther topics\n------------\n\n.. toctree::\n   :maxdepth: 1\n\n   actions\n   admindocs\n   javascript\n\n.. seealso::\n\n    For information about serving the static files (images, JavaScript, and\n    CSS) associated with the admin in production, see :ref:`serving-files`.\n\n    Having problems?  Try :doc:`/faq/admin`.\n\n``ModelAdmin`` objects\n======================\n\n.. class:: ModelAdmin\n\n    The ``ModelAdmin`` class is the representation of a model in the admin\n    interface. Usually, these are stored in a file named ``admin.py`` in your\n    application. Let's take a look at an example of the ``ModelAdmin``::\n\n        from django.contrib import admin\n        from myproject.myapp.models import Author\n\n        class AuthorAdmin(admin.ModelAdmin):\n            pass\n        admin.site.register(Author, AuthorAdmin)\n\n    .. admonition:: Do you need a ``ModelAdmin`` object at all?\n\n        In the preceding example, the ``ModelAdmin`` class doesn't define any\n        custom values (yet). As a result, the default admin interface will be\n        provided. If you are happy with the default admin interface, you don't\n        need to define a ``ModelAdmin`` object at all -- you can register the\n        model class without providing a ``ModelAdmin`` description. The\n        preceding example could be simplified to::\n\n            from django.contrib import admin\n            from myproject.myapp.models import Author\n\n            admin.site.register(Author)\n\nThe ``register`` decorator\n--------------------------\n\n.. function:: register(*models, site=django.admin.sites.site)\n\n    There is also a decorator for registering your ``ModelAdmin`` classes::\n\n        from django.contrib import admin\n        from .models import Author\n\n        @admin.register(Author)\n        class AuthorAdmin(admin.ModelAdmin):\n            pass\n\n    It's given one or more model classes to register with the ``ModelAdmin``.\n    If you're using a custom :class:`AdminSite`, pass it using the ``site`` keyword\n    argument::\n\n        from django.contrib import admin\n        from .models import Author, Editor, Reader\n        from myproject.admin_site import custom_admin_site\n\n        @admin.register(Author, Reader, Editor, site=custom_admin_site)\n        class PersonAdmin(admin.ModelAdmin):\n            pass\n\n    You can't use this decorator if you have to reference your model admin\n    class in its ``__init__()`` method, e.g.\n    ``super(PersonAdmin, self).__init__(*args, **kwargs)``. You can use\n    ``super().__init__(*args, **kwargs)``.\n\nDiscovery of admin files\n------------------------\n\nWhen you put ``'django.contrib.admin'`` in your :setting:`INSTALLED_APPS`\nsetting, Django automatically looks for an ``admin`` module in each\napplication and imports it.\n\n.. class:: apps.AdminConfig\n\n    This is the default :class:`~django.apps.AppConfig` class for the admin.\n    It calls :func:`~django.contrib.admin.autodiscover()` when Django starts.\n\n.. class:: apps.SimpleAdminConfig\n\n    This class works like :class:`~django.contrib.admin.apps.AdminConfig`,\n    except it doesn't call :func:`~django.contrib.admin.autodiscover()`.\n\n    .. attribute:: default_site\n\n        A dotted import path to the default admin site's class or to a callable\n        that returns a site instance. Defaults to\n        ``'django.contrib.admin.sites.AdminSite'``. See\n        :ref:`overriding-default-admin-site` for usage.\n\n.. function:: autodiscover\n\n    This function attempts to import an ``admin`` module in each installed\n    application. Such modules are expected to register models with the admin.\n\n    Typically you won't need to call this function directly as\n    :class:`~django.contrib.admin.apps.AdminConfig` calls it when Django starts.\n\nIf you are using a custom ``AdminSite``, it is common to import all of the\n``ModelAdmin`` subclasses into your code and register them to the custom\n``AdminSite``. In that case, in order to disable auto-discovery, you should\nput ``'django.contrib.admin.apps.SimpleAdminConfig'`` instead of\n``'django.contrib.admin'`` in your :setting:`INSTALLED_APPS` setting.\n\n``ModelAdmin`` options\n----------------------\n\nThe ``ModelAdmin`` is very flexible. It has several options for dealing with\ncustomizing the interface. All options are defined on the ``ModelAdmin``\nsubclass::\n\n    from django.contrib import admin\n\n    class AuthorAdmin(admin.ModelAdmin):\n        date_hierarchy = 'pub_date'\n\n.. attribute:: ModelAdmin.actions\n\n    A list of actions to make available on the change list page. See\n    :doc:`/ref/contrib/admin/actions` for details.\n\n.. attribute:: ModelAdmin.actions_on_top\n.. attribute:: ModelAdmin.actions_on_bottom\n\n    Controls where on the page the actions bar appears. By default, the admin\n    changelist displays actions at the top of the page (``actions_on_top = True;\n    actions_on_bottom = False``).\n\n.. attribute:: ModelAdmin.actions_selection_counter\n\n    Controls whether a selection counter is displayed next to the action dropdown.\n    By default, the admin changelist will display it\n    (``actions_selection_counter = True``).\n\n.. attribute:: ModelAdmin.date_hierarchy\n\n    Set ``date_hierarchy`` to the name of a ``DateField`` or ``DateTimeField``\n    in your model, and the change list page will include a date-based drilldown\n    navigation by that field.\n\n    Example::\n\n        date_hierarchy = 'pub_date'\n\n    You can also specify a field on a related model using the ``__`` lookup,\n    for example::\n\n        date_hierarchy = 'author__pub_date'\n\n    This will intelligently populate itself based on available data,\n    e.g. if all the dates are in one month, it'll show the day-level\n    drill-down only.\n\n    .. note::\n\n        ``date_hierarchy`` uses :meth:`QuerySet.datetimes()\n        <django.db.models.query.QuerySet.datetimes>` internally. Please refer\n        to its documentation for some caveats when time zone support is\n        enabled (:setting:`USE_TZ = True <USE_TZ>`).\n\n.. attribute:: ModelAdmin.empty_value_display\n\n    This attribute overrides the default display value for record's fields that\n    are empty (``None``, empty string, etc.). The default value is ``-`` (a\n    dash). For example::\n\n        from django.contrib import admin\n\n        class AuthorAdmin(admin.ModelAdmin):\n            empty_value_display = '-empty-'\n\n    You can also override ``empty_value_display`` for all admin pages with\n    :attr:`AdminSite.empty_value_display`, or for specific fields like this::\n\n        from django.contrib import admin\n\n        class AuthorAdmin(admin.ModelAdmin):\n            fields = ('name', 'title', 'view_birth_date')\n\n            def view_birth_date(self, obj):\n                return obj.birth_date\n\n            view_birth_date.empty_value_display = '???'\n\n.. attribute:: ModelAdmin.exclude\n\n    This attribute, if given, should be a list of field names to exclude from\n    the form.\n\n    For example, let's consider the following model::\n\n        from django.db import models\n\n        class Author(models.Model):\n            name = models.CharField(max_length=100)\n            title = models.CharField(max_length=3)\n            birth_date = models.DateField(blank=True, null=True)\n\n    If you want a form for the ``Author`` model that includes only the ``name``\n    and ``title`` fields, you would specify ``fields`` or ``exclude`` like\n    this::\n\n        from django.contrib import admin\n\n        class AuthorAdmin(admin.ModelAdmin):\n            fields = ('name', 'title')\n\n        class AuthorAdmin(admin.ModelAdmin):\n            exclude = ('birth_date',)\n\n    Since the Author model only has three fields, ``name``, ``title``, and\n    ``birth_date``, the forms resulting from the above declarations will\n    contain exactly the same fields.\n\n.. attribute:: ModelAdmin.fields\n\n    Use the ``fields`` option to make simple layout changes in the forms on\n    the \"add\" and \"change\" pages such as showing only a subset of available\n    fields, modifying their order, or grouping them into rows. For example, you\n    could define a simpler version of the admin form for the\n    :class:`django.contrib.flatpages.models.FlatPage` model as follows::\n\n        class FlatPageAdmin(admin.ModelAdmin):\n            fields = ('url', 'title', 'content')\n\n    In the above example, only the fields ``url``, ``title`` and ``content``\n    will be displayed, sequentially, in the form. ``fields`` can contain\n    values defined in :attr:`ModelAdmin.readonly_fields` to be displayed as\n    read-only.\n\n    For more complex layout needs, see the :attr:`~ModelAdmin.fieldsets` option.\n\n    The ``fields`` option accepts the same types of values as\n    :attr:`~ModelAdmin.list_display`, except that callables aren't accepted.\n    Names of model and model admin methods will only be used if they're listed\n    in :attr:`~ModelAdmin.readonly_fields`.\n\n    To display multiple fields on the same line, wrap those fields in their own\n    tuple. In this example, the ``url`` and ``title`` fields will display on the\n    same line and the ``content`` field will be displayed below them on its\n    own line::\n\n        class FlatPageAdmin(admin.ModelAdmin):\n            fields = (('url', 'title'), 'content')\n\n    .. admonition:: Note\n\n        This ``fields`` option should not be confused with the ``fields``\n        dictionary key that is within the :attr:`~ModelAdmin.fieldsets` option,\n        as described in the next section.\n\n    If neither ``fields`` nor :attr:`~ModelAdmin.fieldsets` options are present,\n    Django will default to displaying each field that isn't an ``AutoField`` and\n    has ``editable=True``, in a single fieldset, in the same order as the fields\n    are defined in the model.\n\n.. attribute:: ModelAdmin.fieldsets\n\n    Set ``fieldsets`` to control the layout of admin \"add\" and \"change\" pages.\n\n    ``fieldsets`` is a list of two-tuples, in which each two-tuple represents a\n    ``<fieldset>`` on the admin form page. (A ``<fieldset>`` is a \"section\" of\n    the form.)\n\n    The two-tuples are in the format ``(name, field_options)``, where ``name``\n    is a string representing the title of the fieldset and ``field_options`` is\n    a dictionary of information about the fieldset, including a list of fields\n    to be displayed in it.\n\n    A full example, taken from the\n    :class:`django.contrib.flatpages.models.FlatPage` model::\n\n        from django.contrib import admin\n\n        class FlatPageAdmin(admin.ModelAdmin):\n            fieldsets = (\n                (None, {\n                    'fields': ('url', 'title', 'content', 'sites')\n                }),\n                ('Advanced options', {\n                    'classes': ('collapse',),\n                    'fields': ('registration_required', 'template_name'),\n                }),\n            )\n\n    This results in an admin page that looks like:\n\n    .. image:: _images/fieldsets.png\n\n    If neither ``fieldsets`` nor :attr:`~ModelAdmin.fields` options are present,\n    Django will default to displaying each field that isn't an ``AutoField`` and\n    has ``editable=True``, in a single fieldset, in the same order as the fields\n    are defined in the model.\n\n    The ``field_options`` dictionary can have the following keys:\n\n    * ``fields``\n        A tuple of field names to display in this fieldset. This key is\n        required.\n\n        Example::\n\n            {\n            'fields': ('first_name', 'last_name', 'address', 'city', 'state'),\n            }\n\n        As with the :attr:`~ModelAdmin.fields` option, to display multiple\n        fields on the same line, wrap those fields in their own tuple. In this\n        example, the ``first_name`` and ``last_name`` fields will display on\n        the same line::\n\n            {\n            'fields': (('first_name', 'last_name'), 'address', 'city', 'state'),\n            }\n\n        ``fields`` can contain values defined in\n        :attr:`~ModelAdmin.readonly_fields` to be displayed as read-only.\n\n        If you add the name of a callable to ``fields``, the same rule applies\n        as with the :attr:`~ModelAdmin.fields` option: the callable must be\n        listed in :attr:`~ModelAdmin.readonly_fields`.\n\n    * ``classes``\n        A list or tuple containing extra CSS classes to apply to the fieldset.\n\n        Example::\n\n            {\n            'classes': ('wide', 'extrapretty'),\n            }\n\n        Two useful classes defined by the default admin site stylesheet are\n        ``collapse`` and ``wide``. Fieldsets with the ``collapse`` style\n        will be initially collapsed in the admin and replaced with a small\n        \"click to expand\" link. Fieldsets with the ``wide`` style will be\n        given extra horizontal space.\n\n    * ``description``\n        A string of optional extra text to be displayed at the top of each\n        fieldset, under the heading of the fieldset. This string is not\n        rendered for :class:`~django.contrib.admin.TabularInline` due to its\n        layout.\n\n        Note that this value is *not* HTML-escaped when it's displayed in\n        the admin interface. This lets you include HTML if you so desire.\n        Alternatively you can use plain text and\n        :func:`django.utils.html.escape` to escape any HTML special\n        characters.\n\n.. attribute:: ModelAdmin.filter_horizontal\n\n    By default, a :class:`~django.db.models.ManyToManyField` is displayed in\n    the admin site with a ``<select multiple>``. However, multiple-select boxes\n    can be difficult to use when selecting many items. Adding a\n    :class:`~django.db.models.ManyToManyField` to this list will instead use\n    a nifty unobtrusive JavaScript \"filter\" interface that allows searching\n    within the options. The unselected and selected options appear in two boxes\n    side by side. See :attr:`~ModelAdmin.filter_vertical` to use a vertical\n    interface.\n\n.. attribute:: ModelAdmin.filter_vertical\n\n    Same as :attr:`~ModelAdmin.filter_horizontal`, but uses a vertical display\n    of the filter interface with the box of unselected options appearing above\n    the box of selected options.\n\n.. attribute:: ModelAdmin.form\n\n    By default a ``ModelForm`` is dynamically created for your model. It is\n    used to create the form presented on both the add/change pages. You can\n    easily provide your own ``ModelForm`` to override any default form behavior\n    on the add/change pages. Alternatively, you can customize the default\n    form rather than specifying an entirely new one by using the\n    :meth:`ModelAdmin.get_form` method.\n\n    For an example see the section :ref:`admin-custom-validation`.\n\n    .. admonition:: Note\n\n        If you define the ``Meta.model`` attribute on a\n        :class:`~django.forms.ModelForm`, you must also define the\n        ``Meta.fields`` attribute (or the ``Meta.exclude`` attribute). However,\n        since the admin has its own way of defining fields, the ``Meta.fields``\n        attribute will be ignored.\n\n        If the ``ModelForm`` is only going to be used for the admin, the easiest\n        solution is to omit the ``Meta.model`` attribute, since ``ModelAdmin``\n        will provide the correct model to use. Alternatively, you can set\n        ``fields = []`` in the ``Meta`` class to satisfy the validation on the\n        ``ModelForm``.\n\n    .. admonition:: Note\n\n        If your ``ModelForm`` and ``ModelAdmin`` both define an ``exclude``\n        option then ``ModelAdmin`` takes precedence::\n\n            from django import forms\n            from django.contrib import admin\n            from myapp.models import Person\n\n            class PersonForm(forms.ModelForm):\n\n                class Meta:\n                    model = Person\n                    exclude = ['name']\n\n            class PersonAdmin(admin.ModelAdmin):\n                exclude = ['age']\n                form = PersonForm\n\n        In the above example, the \"age\" field will be excluded but the \"name\"\n        field will be included in the generated form.\n\n.. attribute:: ModelAdmin.formfield_overrides\n\n    This provides a quick-and-dirty way to override some of the\n    :class:`~django.forms.Field` options for use in the admin.\n    ``formfield_overrides`` is a dictionary mapping a field class to a dict of\n    arguments to pass to the field at construction time.\n\n    Since that's a bit abstract, let's look at a concrete example. The most\n    common use of ``formfield_overrides`` is to add a custom widget for a\n    certain type of field. So, imagine we've written a ``RichTextEditorWidget``\n    that we'd like to use for large text fields instead of the default\n    ``<textarea>``. Here's how we'd do that::\n\n        from django.contrib import admin\n        from django.db import models\n\n        # Import our custom widget and our model from where they're defined\n        from myapp.models import MyModel\n        from myapp.widgets import RichTextEditorWidget\n\n        class MyModelAdmin(admin.ModelAdmin):\n            formfield_overrides = {\n                models.TextField: {'widget': RichTextEditorWidget},\n            }\n\n    Note that the key in the dictionary is the actual field class, *not* a\n    string. The value is another dictionary; these arguments will be passed to\n    the form field's ``__init__()`` method. See :doc:`/ref/forms/api` for\n    details.\n\n    .. warning::\n\n        If you want to use a custom widget with a relation field (i.e.\n        :class:`~django.db.models.ForeignKey` or\n        :class:`~django.db.models.ManyToManyField`), make sure you haven't\n        included that field's name in ``raw_id_fields``, ``radio_fields``, or\n        ``autocomplete_fields``.\n\n        ``formfield_overrides`` won't let you change the widget on relation\n        fields that have ``raw_id_fields``, ``radio_fields``, or\n        ``autocomplete_fields`` set. That's because ``raw_id_fields``,\n        ``radio_fields``, and ``autocomplete_fields`` imply custom widgets of\n        their own.\n\n.. attribute:: ModelAdmin.inlines\n\n    See :class:`InlineModelAdmin` objects below as well as\n    :meth:`ModelAdmin.get_formsets_with_inlines`.\n\n.. attribute:: ModelAdmin.list_display\n\n    Set ``list_display`` to control which fields are displayed on the change\n    list page of the admin.\n\n    Example::\n\n        list_display = ('first_name', 'last_name')\n\n    If you don't set ``list_display``, the admin site will display a single\n    column that displays the ``__str__()`` representation of each object.\n\n    There are four types of values that can be used in ``list_display``:\n\n    * The name of a model field. For example::\n\n          class PersonAdmin(admin.ModelAdmin):\n              list_display = ('first_name', 'last_name')\n\n    * A callable that accepts one argument, the model instance. For example::\n\n          def upper_case_name(obj):\n              return (\"%s %s\" % (obj.first_name, obj.last_name)).upper()\n          upper_case_name.short_description = 'Name'\n\n          class PersonAdmin(admin.ModelAdmin):\n              list_display = (upper_case_name,)\n\n    * A string representing a ``ModelAdmin`` method that accepts one argument,\n      the model instance. For example::\n\n          class PersonAdmin(admin.ModelAdmin):\n              list_display = ('upper_case_name',)\n\n              def upper_case_name(self, obj):\n                  return (\"%s %s\" % (obj.first_name, obj.last_name)).upper()\n              upper_case_name.short_description = 'Name'\n\n    * A string representing a model attribute or method (without any required\n      arguments). For example::\n\n          from django.contrib import admin\n          from django.db import models\n\n          class Person(models.Model):\n              name = models.CharField(max_length=50)\n              birthday = models.DateField()\n\n              def decade_born_in(self):\n                  return self.birthday.strftime('%Y')[:3] + \"0's\"\n              decade_born_in.short_description = 'Birth decade'\n\n          class PersonAdmin(admin.ModelAdmin):\n              list_display = ('name', 'decade_born_in')\n\n    A few special cases to note about ``list_display``:\n\n    * If the field is a ``ForeignKey``, Django will display the\n      ``__str__()`` of the related object.\n\n    * ``ManyToManyField`` fields aren't supported, because that would\n      entail executing a separate SQL statement for each row in the table.\n      If you want to do this nonetheless, give your model a custom method,\n      and add that method's name to ``list_display``. (See below for more\n      on custom methods in ``list_display``.)\n\n    * If the field is a ``BooleanField``, Django will display a pretty \"on\" or\n      \"off\" icon instead of ``True`` or ``False``.\n\n    * If the string given is a method of the model, ``ModelAdmin`` or a\n      callable, Django will HTML-escape the output by default. To escape\n      user input and allow your own unescaped tags, use\n      :func:`~django.utils.html.format_html`.\n\n      Here's a full example model::\n\n          from django.contrib import admin\n          from django.db import models\n          from django.utils.html import format_html\n\n          class Person(models.Model):\n              first_name = models.CharField(max_length=50)\n              last_name = models.CharField(max_length=50)\n              color_code = models.CharField(max_length=6)\n\n              def colored_name(self):\n                  return format_html(\n                      '<span style=\"color: #{};\">{} {}</span>',\n                      self.color_code,\n                      self.first_name,\n                      self.last_name,\n                  )\n\n          class PersonAdmin(admin.ModelAdmin):\n              list_display = ('first_name', 'last_name', 'colored_name')\n\n    * As some examples have already demonstrated, when using a callable, a\n      model method, or a ``ModelAdmin`` method, you can customize the column's\n      title by adding a ``short_description`` attribute to the callable.\n\n    * If the value of a field is ``None``, an empty string, or an iterable\n      without elements, Django will display ``-`` (a dash). You can override\n      this with :attr:`AdminSite.empty_value_display`::\n\n          from django.contrib import admin\n\n          admin.site.empty_value_display = '(None)'\n\n      You can also use :attr:`ModelAdmin.empty_value_display`::\n\n          class PersonAdmin(admin.ModelAdmin):\n              empty_value_display = 'unknown'\n\n      Or on a field level::\n\n          class PersonAdmin(admin.ModelAdmin):\n              list_display = ('name', 'birth_date_view')\n\n              def birth_date_view(self, obj):\n                   return obj.birth_date\n\n              birth_date_view.empty_value_display = 'unknown'\n\n    * If the string given is a method of the model, ``ModelAdmin`` or a\n      callable that returns True or False Django will display a pretty\n      \"on\" or \"off\" icon if you give the method a ``boolean`` attribute\n      whose value is ``True``.\n\n      Here's a full example model::\n\n          from django.contrib import admin\n          from django.db import models\n\n          class Person(models.Model):\n              first_name = models.CharField(max_length=50)\n              birthday = models.DateField()\n\n              def born_in_fifties(self):\n                  return self.birthday.strftime('%Y')[:3] == '195'\n              born_in_fifties.boolean = True\n\n          class PersonAdmin(admin.ModelAdmin):\n              list_display = ('name', 'born_in_fifties')\n\n    * The ``__str__()`` method is just as valid in ``list_display`` as any\n      other model method, so it's perfectly OK to do this::\n\n          list_display = ('__str__', 'some_other_field')\n\n    * Usually, elements of ``list_display`` that aren't actual database\n      fields can't be used in sorting (because Django does all the sorting\n      at the database level).\n\n      However, if an element of ``list_display`` represents a certain\n      database field, you can indicate this fact by setting the\n      ``admin_order_field`` attribute of the item.\n\n      For example::\n\n        from django.contrib import admin\n        from django.db import models\n        from django.utils.html import format_html\n\n        class Person(models.Model):\n            first_name = models.CharField(max_length=50)\n            color_code = models.CharField(max_length=6)\n\n            def colored_first_name(self):\n                return format_html(\n                    '<span style=\"color: #{};\">{}</span>',\n                    self.color_code,\n                    self.first_name,\n                )\n\n            colored_first_name.admin_order_field = 'first_name'\n\n        class PersonAdmin(admin.ModelAdmin):\n            list_display = ('first_name', 'colored_first_name')\n\n      The above will tell Django to order by the ``first_name`` field when\n      trying to sort by ``colored_first_name`` in the admin.\n\n      To indicate descending order with ``admin_order_field`` you can use a\n      hyphen prefix on the field name. Using the above example, this would\n      look like::\n\n          colored_first_name.admin_order_field = '-first_name'\n\n      ``admin_order_field`` supports query lookups to sort by values on related\n      models. This example includes an \"author first name\" column in the list\n      display and allows sorting it by first name::\n\n          class Blog(models.Model):\n              title = models.CharField(max_length=255)\n              author = models.ForeignKey(Person, on_delete=models.CASCADE)\n\n          class BlogAdmin(admin.ModelAdmin):\n              list_display = ('title', 'author', 'author_first_name')\n\n              def author_first_name(self, obj):\n                  return obj.author.first_name\n\n              author_first_name.admin_order_field = 'author__first_name'\n\n      :doc:`Query expressions </ref/models/expressions>` may be used in\n      ``admin_order_field``. For example::\n\n          from django.db.models import Value\n          from django.db.models.functions import Concat\n\n          class Person(models.Model):\n              first_name = models.CharField(max_length=50)\n              last_name = models.CharField(max_length=50)\n\n              def full_name(self):\n                  return self.first_name + ' ' + self.last_name\n              full_name.admin_order_field = Concat('first_name', Value(' '), 'last_name')\n\n    * Elements of ``list_display`` can also be properties. Please note however,\n      that due to the way properties work in Python, setting\n      ``short_description`` or ``admin_order_field`` on a property is only\n      possible when using the ``property()`` function and **not** with the\n      ``@property`` decorator.\n\n      For example::\n\n          class Person(models.Model):\n              first_name = models.CharField(max_length=50)\n              last_name = models.CharField(max_length=50)\n\n              def my_property(self):\n                  return self.first_name + ' ' + self.last_name\n              my_property.short_description = \"Full name of the person\"\n              my_property.admin_order_field = 'last_name'\n\n              full_name = property(my_property)\n\n          class PersonAdmin(admin.ModelAdmin):\n              list_display = ('full_name',)\n\n\n    * The field names in ``list_display`` will also appear as CSS classes in\n      the HTML output, in the form of ``column-<field_name>`` on each ``<th>``\n      element. This can be used to set column widths in a CSS file for example.\n\n    * Django will try to interpret every element of ``list_display`` in this\n      order:\n\n      * A field of the model.\n      * A callable.\n      * A string representing a ``ModelAdmin`` attribute.\n      * A string representing a model attribute.\n\n      For example if you have ``first_name`` as a model field and\n      as a ``ModelAdmin`` attribute, the model field will be used.\n\n\n.. attribute:: ModelAdmin.list_display_links\n\n    Use ``list_display_links`` to control if and which fields in\n    :attr:`list_display` should be linked to the \"change\" page for an object.\n\n    By default, the change list page will link the first column -- the first\n    field specified in ``list_display`` -- to the change page for each item.\n    But ``list_display_links`` lets you change this:\n\n    * Set it to ``None`` to get no links at all.\n    * Set it to a list or tuple of fields (in the same format as\n      ``list_display``) whose columns you want converted to links.\n\n      You can specify one or many fields. As long as the fields appear in\n      ``list_display``, Django doesn't care how many (or how few) fields are\n      linked. The only requirement is that if you want to use\n      ``list_display_links`` in this fashion, you must define ``list_display``.\n\n    In this example, the ``first_name`` and ``last_name`` fields will be\n    linked on the change list page::\n\n        class PersonAdmin(admin.ModelAdmin):\n            list_display = ('first_name', 'last_name', 'birthday')\n            list_display_links = ('first_name', 'last_name')\n\n    In this example, the change list page grid will have no links::\n\n        class AuditEntryAdmin(admin.ModelAdmin):\n            list_display = ('timestamp', 'message')\n            list_display_links = None\n\n.. _admin-list-editable:\n\n.. attribute:: ModelAdmin.list_editable\n\n    Set ``list_editable`` to a list of field names on the model which will\n    allow editing on the change list page. That is, fields listed in\n    ``list_editable`` will be displayed as form widgets on the change list\n    page, allowing users to edit and save multiple rows at once.\n\n    .. note::\n\n        ``list_editable`` interacts with a couple of other options in\n        particular ways; you should note the following rules:\n\n        * Any field in ``list_editable`` must also be in ``list_display``.\n          You can't edit a field that's not displayed!\n\n        * The same field can't be listed in both ``list_editable`` and\n          ``list_display_links`` -- a field can't be both a form and\n          a link.\n\n        You'll get a validation error if either of these rules are broken.\n\n.. attribute:: ModelAdmin.list_filter\n\n    Set ``list_filter`` to activate filters in the right sidebar of the change\n    list page of the admin, as illustrated in the following screenshot:\n\n    .. image:: _images/list_filter.png\n\n    ``list_filter`` should be a list or tuple of elements, where each element\n    should be of one of the following types:\n\n    * a field name, where the specified field should be either a\n      ``BooleanField``, ``CharField``, ``DateField``, ``DateTimeField``,\n      ``IntegerField``, ``ForeignKey`` or ``ManyToManyField``, for example::\n\n          class PersonAdmin(admin.ModelAdmin):\n              list_filter = ('is_staff', 'company')\n\n      Field names in ``list_filter`` can also span relations\n      using the ``__`` lookup, for example::\n\n          class PersonAdmin(admin.UserAdmin):\n              list_filter = ('company__name',)\n\n    * a class inheriting from ``django.contrib.admin.SimpleListFilter``,\n      which you need to provide the ``title`` and ``parameter_name``\n      attributes to and override the ``lookups`` and ``queryset`` methods,\n      e.g.::\n\n           from datetime import date\n\n           from django.contrib import admin\n           from django.utils.translation import gettext_lazy as _\n\n           class DecadeBornListFilter(admin.SimpleListFilter):\n               # Human-readable title which will be displayed in the\n               # right admin sidebar just above the filter options.\n               title = _('decade born')\n\n               # Parameter for the filter that will be used in the URL query.\n               parameter_name = 'decade'\n\n               def lookups(self, request, model_admin):\n                   \"\"\"\n                   Returns a list of tuples. The first element in each\n                   tuple is the coded value for the option that will\n                   appear in the URL query. The second element is the\n                   human-readable name for the option that will appear\n                   in the right sidebar.\n                   \"\"\"\n                   return (\n                       ('80s', _('in the eighties')),\n                       ('90s', _('in the nineties')),\n                   )\n\n               def queryset(self, request, queryset):\n                   \"\"\"\n                   Returns the filtered queryset based on the value\n                   provided in the query string and retrievable via\n                   `self.value()`.\n                   \"\"\"\n                   # Compare the requested value (either '80s' or '90s')\n                   # to decide how to filter the queryset.\n                   if self.value() == '80s':\n                       return queryset.filter(birthday__gte=date(1980, 1, 1),\n                                               birthday__lte=date(1989, 12, 31))\n                   if self.value() == '90s':\n                       return queryset.filter(birthday__gte=date(1990, 1, 1),\n                                               birthday__lte=date(1999, 12, 31))\n\n           class PersonAdmin(admin.ModelAdmin):\n               list_filter = (DecadeBornListFilter,)\n\n      .. note::\n\n          As a convenience, the ``HttpRequest`` object is passed to the\n          ``lookups`` and ``queryset`` methods, for example::\n\n              class AuthDecadeBornListFilter(DecadeBornListFilter):\n\n                  def lookups(self, request, model_admin):\n                      if request.user.is_superuser:\n                          return super().lookups(request, model_admin)\n\n                  def queryset(self, request, queryset):\n                      if request.user.is_superuser:\n                          return super().queryset(request, queryset)\n\n          Also as a convenience, the ``ModelAdmin`` object is passed to\n          the ``lookups`` method, for example if you want to base the\n          lookups on the available data::\n\n              class AdvancedDecadeBornListFilter(DecadeBornListFilter):\n\n                  def lookups(self, request, model_admin):\n                      \"\"\"\n                      Only show the lookups if there actually is\n                      anyone born in the corresponding decades.\n                      \"\"\"\n                      qs = model_admin.get_queryset(request)\n                      if qs.filter(birthday__gte=date(1980, 1, 1),\n                                    birthday__lte=date(1989, 12, 31)).exists():\n                          yield ('80s', _('in the eighties'))\n                      if qs.filter(birthday__gte=date(1990, 1, 1),\n                                    birthday__lte=date(1999, 12, 31)).exists():\n                          yield ('90s', _('in the nineties'))\n\n    * a tuple, where the first element is a field name and the second\n      element is a class inheriting from\n      ``django.contrib.admin.FieldListFilter``, for example::\n\n          class PersonAdmin(admin.ModelAdmin):\n              list_filter = (\n                  ('is_staff', admin.BooleanFieldListFilter),\n              )\n\n      You can limit the choices of a related model to the objects involved in\n      that relation using ``RelatedOnlyFieldListFilter``::\n\n          class BookAdmin(admin.ModelAdmin):\n              list_filter = (\n                  ('author', admin.RelatedOnlyFieldListFilter),\n              )\n\n      Assuming ``author`` is a ``ForeignKey`` to a ``User`` model, this will\n      limit the ``list_filter`` choices to the users who have written a book\n      instead of listing all users.\n\n      You can filter empty values using ``EmptyFieldListFilter``, which can\n      filter on both empty strings and nulls, depending on what the field\n      allows to store::\n\n          class BookAdmin(admin.ModelAdmin):\n              list_filter = (\n                  ('title', admin.EmptyFieldListFilter),\n              )\n\n      .. note::\n\n        The ``FieldListFilter`` API is considered internal and might be\n        changed.\n\n      .. versionadded:: 3.1\n\n          The ``EmptyFieldListFilter`` class was added.\n\n    List filter's typically appear only if the filter has more than one choice.\n    A filter's ``has_output()`` method controls whether or not it appears.\n\n    It is possible to specify a custom template for rendering a list filter::\n\n        class FilterWithCustomTemplate(admin.SimpleListFilter):\n            template = \"custom_template.html\"\n\n    See the default template provided by Django (``admin/filter.html``) for\n    a concrete example.\n\n.. attribute:: ModelAdmin.list_max_show_all\n\n    Set ``list_max_show_all`` to control how many items can appear on a \"Show\n    all\" admin change list page. The admin will display a \"Show all\" link on the\n    change list only if the total result count is less than or equal to this\n    setting. By default, this is set to ``200``.\n\n.. attribute:: ModelAdmin.list_per_page\n\n    Set ``list_per_page`` to control how many items appear on each paginated\n    admin change list page. By default, this is set to ``100``.\n\n.. attribute:: ModelAdmin.list_select_related\n\n    Set ``list_select_related`` to tell Django to use\n    :meth:`~django.db.models.query.QuerySet.select_related` in retrieving\n    the list of objects on the admin change list page. This can save you a\n    bunch of database queries.\n\n    The value should be either a boolean, a list or a tuple. Default is\n    ``False``.\n\n    When value is ``True``, ``select_related()`` will always be called. When\n    value is set to ``False``, Django will look at ``list_display`` and call\n    ``select_related()`` if any ``ForeignKey`` is present.\n\n    If you need more fine-grained control, use a tuple (or list) as value for\n    ``list_select_related``. Empty tuple will prevent Django from calling\n    ``select_related`` at all. Any other tuple will be passed directly to\n    ``select_related`` as parameters. For example::\n\n        class ArticleAdmin(admin.ModelAdmin):\n            list_select_related = ('author', 'category')\n\n    will call ``select_related('author', 'category')``.\n\n    If you need to specify a dynamic value based on the request, you can\n    implement a :meth:`~ModelAdmin.get_list_select_related` method.\n\n    .. note::\n\n        ``ModelAdmin`` ignores this attribute when\n        :meth:`~django.db.models.query.QuerySet.select_related` was already\n        called on the changelist's ``QuerySet``.\n\n.. attribute:: ModelAdmin.ordering\n\n    Set ``ordering`` to specify how lists of objects should be ordered in the\n    Django admin views. This should be a list or tuple in the same format as a\n    model's :attr:`~django.db.models.Options.ordering` parameter.\n\n    If this isn't provided, the Django admin will use the model's default\n    ordering.\n\n    If you need to specify a dynamic order (for example depending on user or\n    language) you can implement a :meth:`~ModelAdmin.get_ordering` method.\n\n    .. admonition:: Performance considerations with ordering and sorting\n\n        To ensure a deterministic ordering of results, the changelist adds\n        ``pk`` to the ordering if it can't find a single or unique together set\n        of fields that provide total ordering.\n\n        For example, if the default ordering is by a non-unique ``name`` field,\n        then the changelist is sorted by ``name`` and ``pk``. This could\n        perform poorly if you have a lot of rows and don't have an index on\n        ``name`` and ``pk``.\n\n.. attribute:: ModelAdmin.paginator\n\n    The paginator class to be used for pagination. By default,\n    :class:`django.core.paginator.Paginator` is used. If the custom paginator\n    class doesn't have the same constructor interface as\n    :class:`django.core.paginator.Paginator`, you will also need to\n    provide an implementation for :meth:`ModelAdmin.get_paginator`.\n\n.. attribute:: ModelAdmin.prepopulated_fields\n\n    Set ``prepopulated_fields`` to a dictionary mapping field names to the\n    fields it should prepopulate from::\n\n        class ArticleAdmin(admin.ModelAdmin):\n            prepopulated_fields = {\"slug\": (\"title\",)}\n\n    When set, the given fields will use a bit of JavaScript to populate from\n    the fields assigned. The main use for this functionality is to\n    automatically generate the value for ``SlugField`` fields from one or more\n    other fields. The generated value is produced by concatenating the values\n    of the source fields, and then by transforming that result into a valid\n    slug (e.g. substituting dashes for spaces; lowercasing ASCII letters; and\n    removing various English stop words such as 'a', 'an', 'as', and similar).\n\n    Prepopulated fields aren't modified by JavaScript after a value has been\n    saved. It's usually undesired that slugs change (which would cause an\n    object's URL to change if the slug is used in it).\n\n    ``prepopulated_fields`` doesn't accept ``DateTimeField``, ``ForeignKey``,\n    ``OneToOneField``, and ``ManyToManyField`` fields.\n\n.. attribute:: ModelAdmin.preserve_filters\n\n    The admin now preserves filters on the list view after creating, editing\n    or deleting an object. You can restore the previous behavior of clearing\n    filters by setting this attribute to ``False``.\n\n.. attribute:: ModelAdmin.radio_fields\n\n    By default, Django's admin uses a select-box interface (<select>) for\n    fields that are ``ForeignKey`` or have ``choices`` set. If a field is\n    present in ``radio_fields``, Django will use a radio-button interface\n    instead. Assuming ``group`` is a ``ForeignKey`` on the ``Person`` model::\n\n        class PersonAdmin(admin.ModelAdmin):\n            radio_fields = {\"group\": admin.VERTICAL}\n\n    You have the choice of using ``HORIZONTAL`` or ``VERTICAL`` from the\n    ``django.contrib.admin`` module.\n\n    Don't include a field in ``radio_fields`` unless it's a ``ForeignKey`` or has\n    ``choices`` set.\n\n.. attribute:: ModelAdmin.autocomplete_fields\n\n    ``autocomplete_fields`` is a list of ``ForeignKey`` and/or\n    ``ManyToManyField`` fields you would like to change to `Select2\n    <https://select2.org/>`_ autocomplete inputs.\n\n    By default, the admin uses a select-box interface (``<select>``) for\n    those fields. Sometimes you don't want to incur the overhead of selecting\n    all the related instances to display in the dropdown.\n\n    The Select2 input looks similar to the default input but comes with a\n    search feature that loads the options asynchronously. This is faster and\n    more user-friendly if the related model has many instances.\n\n    You must define :attr:`~ModelAdmin.search_fields` on the related object's\n    ``ModelAdmin`` because the autocomplete search uses it.\n\n    To avoid unauthorized data disclosure, users must have the ``view`` or\n    ``change`` permission to the related object in order to use autocomplete.\n\n    Ordering and pagination of the results are controlled by the related\n    ``ModelAdmin``'s :meth:`~ModelAdmin.get_ordering` and\n    :meth:`~ModelAdmin.get_paginator` methods.\n\n    In the following example, ``ChoiceAdmin`` has an autocomplete field for the\n    ``ForeignKey`` to the ``Question``. The results are filtered by the\n    ``question_text`` field and ordered by the ``date_created`` field::\n\n        class QuestionAdmin(admin.ModelAdmin):\n            ordering = ['date_created']\n            search_fields = ['question_text']\n\n        class ChoiceAdmin(admin.ModelAdmin):\n            autocomplete_fields = ['question']\n\n    .. admonition:: Performance considerations for large datasets\n\n        Ordering using :attr:`ModelAdmin.ordering` may cause performance\n        problems as sorting on a large queryset will be slow.\n\n        Also, if your search fields include fields that aren't indexed by the\n        database, you might encounter poor performance on extremely large\n        tables.\n\n        For those cases, it's a good idea to write your own\n        :func:`ModelAdmin.get_search_results` implementation using a\n        full-text indexed search.\n\n        You may also want to change the ``Paginator`` on very large tables\n        as the default paginator always performs a ``count()`` query.\n        For example, you could override the default implementation of the\n        ``Paginator.count`` property.\n\n.. attribute:: ModelAdmin.raw_id_fields\n\n    By default, Django's admin uses a select-box interface (<select>) for\n    fields that are ``ForeignKey``. Sometimes you don't want to incur the\n    overhead of having to select all the related instances to display in the\n    drop-down.\n\n    ``raw_id_fields`` is a list of fields you would like to change\n    into an ``Input`` widget for either a ``ForeignKey`` or\n    ``ManyToManyField``::\n\n        class ArticleAdmin(admin.ModelAdmin):\n            raw_id_fields = (\"newspaper\",)\n\n    The ``raw_id_fields`` ``Input`` widget should contain a primary key if the\n    field is a ``ForeignKey`` or a comma separated list of values if the field\n    is a ``ManyToManyField``.  The ``raw_id_fields`` widget shows a magnifying\n    glass button next to the field which allows users to search for and select\n    a value:\n\n    .. image:: _images/raw_id_fields.png\n\n.. attribute:: ModelAdmin.readonly_fields\n\n    By default the admin shows all fields as editable. Any fields in this\n    option (which should be a ``list`` or ``tuple``) will display its data\n    as-is and non-editable; they are also excluded from the\n    :class:`~django.forms.ModelForm` used for creating and editing. Note that\n    when specifying :attr:`ModelAdmin.fields` or :attr:`ModelAdmin.fieldsets`\n    the read-only fields must be present to be shown (they are ignored\n    otherwise).\n\n    If ``readonly_fields`` is used without defining explicit ordering through\n    :attr:`ModelAdmin.fields` or :attr:`ModelAdmin.fieldsets` they will be\n    added last after all editable fields.\n\n    A read-only field can not only display data from a model's field, it can\n    also display the output of a model's method or a method of the\n    ``ModelAdmin`` class itself. This is very similar to the way\n    :attr:`ModelAdmin.list_display` behaves. This provides a way to use the\n    admin interface to provide feedback on the status of the objects being\n    edited, for example::\n\n        from django.contrib import admin\n        from django.utils.html import format_html_join\n        from django.utils.safestring import mark_safe\n\n        class PersonAdmin(admin.ModelAdmin):\n            readonly_fields = ('address_report',)\n\n            def address_report(self, instance):\n                # assuming get_full_address() returns a list of strings\n                # for each line of the address and you want to separate each\n                # line by a linebreak\n                return format_html_join(\n                    mark_safe('<br>'),\n                    '{}',\n                    ((line,) for line in instance.get_full_address()),\n                ) or mark_safe(\"<span class='errors'>I can't determine this address.</span>\")\n\n            # short_description functions like a model field's verbose_name\n            address_report.short_description = \"Address\"\n\n.. attribute:: ModelAdmin.save_as\n\n    Set ``save_as`` to enable a \"save as new\" feature on admin change forms.\n\n    Normally, objects have three save options: \"Save\", \"Save and continue\n    editing\", and \"Save and add another\". If ``save_as`` is ``True``, \"Save\n    and add another\" will be replaced by a \"Save as new\" button that creates a\n    new object (with a new ID) rather than updating the existing object.\n\n    By default, ``save_as`` is set to ``False``.\n\n.. attribute:: ModelAdmin.save_as_continue\n\n    When :attr:`save_as=True <save_as>`, the default redirect after saving the\n    new object is to the change view for that object. If you set\n    ``save_as_continue=False``, the redirect will be to the changelist view.\n\n    By default, ``save_as_continue`` is set to ``True``.\n\n.. attribute:: ModelAdmin.save_on_top\n\n    Set ``save_on_top`` to add save buttons across the top of your admin change\n    forms.\n\n    Normally, the save buttons appear only at the bottom of the forms. If you\n    set ``save_on_top``, the buttons will appear both on the top and the\n    bottom.\n\n    By default, ``save_on_top`` is set to ``False``.\n\n.. attribute:: ModelAdmin.search_fields\n\n    Set ``search_fields`` to enable a search box on the admin change list page.\n    This should be set to a list of field names that will be searched whenever\n    somebody submits a search query in that text box.\n\n    These fields should be some kind of text field, such as ``CharField`` or\n    ``TextField``. You can also perform a related lookup on a ``ForeignKey`` or\n    ``ManyToManyField`` with the lookup API \"follow\" notation::\n\n        search_fields = ['foreign_key__related_fieldname']\n\n    For example, if you have a blog entry with an author, the following\n    definition would enable searching blog entries by the email address of the\n    author::\n\n        search_fields = ['user__email']\n\n    When somebody does a search in the admin search box, Django splits the\n    search query into words and returns all objects that contain each of the\n    words, case-insensitive (using the :lookup:`icontains` lookup), where each\n    word must be in at least one of ``search_fields``. For example, if\n    ``search_fields`` is set to ``['first_name', 'last_name']`` and a user\n    searches for ``john lennon``, Django will do the equivalent of this SQL\n    ``WHERE`` clause:\n\n    .. code-block:: sql\n\n        WHERE (first_name ILIKE '%john%' OR last_name ILIKE '%john%')\n        AND (first_name ILIKE '%lennon%' OR last_name ILIKE '%lennon%')\n\n    If you don't want to use ``icontains`` as the lookup, you can use any\n    lookup by appending it the field. For example, you could use :lookup:`exact`\n    by setting ``search_fields`` to ``['first_name__exact']``.\n\n    Beware that because query terms are split and ANDed as described earlier,\n    searching with :lookup:`exact` only works with a single search word since\n    two or more words can't all be an exact match unless all words are the same.\n\n    Some (older) shortcuts for specifying a field lookup are also available.\n    You can prefix a field in ``search_fields`` with the following characters\n    and it's equivalent to adding ``__<lookup>`` to the field:\n\n    ======  ====================\n    Prefix  Lookup\n    ======  ====================\n    ^       :lookup:`startswith`\n    =       :lookup:`iexact`\n    @       :lookup:`search`\n    None    :lookup:`icontains`\n    ======  ====================\n\n    If you need to customize search you can use\n    :meth:`ModelAdmin.get_search_results` to provide additional or alternate\n    search behavior.\n\n.. attribute:: ModelAdmin.show_full_result_count\n\n    Set ``show_full_result_count`` to control whether the full count of objects\n    should be displayed on a filtered admin page (e.g. ``99 results (103 total)``).\n    If this option is set to ``False``, a text like ``99 results (Show all)``\n    is displayed instead.\n\n    The default of ``show_full_result_count=True`` generates a query to perform\n    a full count on the table which can be expensive if the table contains a\n    large number of rows.\n\n.. attribute:: ModelAdmin.sortable_by\n\n    By default, the change list page allows sorting by all model fields (and\n    callables that have the ``admin_order_field`` property) specified in\n    :attr:`list_display`.\n\n    If you want to disable sorting for some columns, set ``sortable_by`` to\n    a collection (e.g. ``list``, ``tuple``, or ``set``) of the subset of\n    :attr:`list_display` that you want to be sortable. An empty collection\n    disables sorting for all columns.\n\n    If you need to specify this list dynamically, implement a\n    :meth:`~ModelAdmin.get_sortable_by` method instead.\n\n.. attribute:: ModelAdmin.view_on_site\n\n    Set ``view_on_site`` to control whether or not to display the \"View on site\" link.\n    This link should bring you to a URL where you can display the saved object.\n\n    This value can be either a boolean flag or a callable. If ``True`` (the\n    default), the object's :meth:`~django.db.models.Model.get_absolute_url`\n    method will be used to generate the url.\n\n    If your model has a :meth:`~django.db.models.Model.get_absolute_url` method\n    but you don't want the \"View on site\" button to appear, you only need to set\n    ``view_on_site`` to ``False``::\n\n        from django.contrib import admin\n\n        class PersonAdmin(admin.ModelAdmin):\n            view_on_site = False\n\n    In case it is a callable, it accepts the model instance as a parameter.\n    For example::\n\n        from django.contrib import admin\n        from django.urls import reverse\n\n        class PersonAdmin(admin.ModelAdmin):\n            def view_on_site(self, obj):\n                url = reverse('person-detail', kwargs={'slug': obj.slug})\n                return 'https://example.com' + url\n\nCustom template options\n~~~~~~~~~~~~~~~~~~~~~~~\n\nThe :ref:`admin-overriding-templates` section describes how to override or extend\nthe default admin templates.  Use the following options to override the default\ntemplates used by the :class:`ModelAdmin` views:\n\n.. attribute:: ModelAdmin.add_form_template\n\n    Path to a custom template, used by :meth:`add_view`.\n\n.. attribute:: ModelAdmin.change_form_template\n\n    Path to a custom template, used by :meth:`change_view`.\n\n.. attribute:: ModelAdmin.change_list_template\n\n    Path to a custom template, used by :meth:`changelist_view`.\n\n.. attribute:: ModelAdmin.delete_confirmation_template\n\n    Path to a custom template, used by :meth:`delete_view` for displaying a\n    confirmation page when deleting one or more objects.\n\n.. attribute:: ModelAdmin.delete_selected_confirmation_template\n\n    Path to a custom template, used by the ``delete_selected`` action method\n    for displaying a confirmation page when deleting one or more objects. See\n    the :doc:`actions documentation</ref/contrib/admin/actions>`.\n\n.. attribute:: ModelAdmin.object_history_template\n\n    Path to a custom template, used by :meth:`history_view`.\n\n.. attribute:: ModelAdmin.popup_response_template\n\n    Path to a custom template, used by :meth:`response_add`,\n    :meth:`response_change`, and :meth:`response_delete`.\n\n.. _model-admin-methods:\n\n``ModelAdmin`` methods\n----------------------\n\n.. warning::\n\n    When overriding :meth:`ModelAdmin.save_model` and\n    :meth:`ModelAdmin.delete_model`, your code must save/delete the\n    object. They aren't meant for veto purposes, rather they allow you to\n    perform extra operations.\n\n.. method:: ModelAdmin.save_model(request, obj, form, change)\n\n    The ``save_model`` method is given the ``HttpRequest``, a model instance,\n    a ``ModelForm`` instance, and a boolean value based on whether it is adding\n    or changing the object. Overriding this method allows doing pre- or\n    post-save operations. Call ``super().save_model()`` to save the object\n    using :meth:`.Model.save`.\n\n    For example to attach ``request.user`` to the object prior to saving::\n\n        from django.contrib import admin\n\n        class ArticleAdmin(admin.ModelAdmin):\n            def save_model(self, request, obj, form, change):\n                obj.user = request.user\n                super().save_model(request, obj, form, change)\n\n.. method:: ModelAdmin.delete_model(request, obj)\n\n    The ``delete_model`` method is given the ``HttpRequest`` and a model\n    instance. Overriding this method allows doing pre- or post-delete\n    operations. Call ``super().delete_model()`` to delete the object using\n    :meth:`.Model.delete`.\n\n.. method:: ModelAdmin.delete_queryset(request, queryset)\n\n    The ``delete_queryset()`` method is given the ``HttpRequest`` and a\n    ``QuerySet`` of objects to be deleted. Override this method to customize\n    the deletion process for the \"delete selected objects\" :doc:`action\n    <actions>`.\n\n.. method:: ModelAdmin.save_formset(request, form, formset, change)\n\n    The ``save_formset`` method is given the ``HttpRequest``, the parent\n    ``ModelForm`` instance and a boolean value based on whether it is adding or\n    changing the parent object.\n\n    For example, to attach ``request.user`` to each changed formset\n    model instance::\n\n        class ArticleAdmin(admin.ModelAdmin):\n            def save_formset(self, request, form, formset, change):\n                instances = formset.save(commit=False)\n                for obj in formset.deleted_objects:\n                    obj.delete()\n                for instance in instances:\n                    instance.user = request.user\n                    instance.save()\n                formset.save_m2m()\n\n    See also :ref:`saving-objects-in-the-formset`.\n\n.. method:: ModelAdmin.get_ordering(request)\n\n    The ``get_ordering`` method takes a ``request`` as parameter and\n    is expected to return a ``list`` or ``tuple`` for ordering similar\n    to the :attr:`ordering` attribute. For example::\n\n        class PersonAdmin(admin.ModelAdmin):\n\n            def get_ordering(self, request):\n                if request.user.is_superuser:\n                    return ['name', 'rank']\n                else:\n                    return ['name']\n\n.. method:: ModelAdmin.get_search_results(request, queryset, search_term)\n\n    The ``get_search_results`` method modifies the list of objects displayed\n    into those that match the provided search term. It accepts the request, a\n    queryset that applies the current filters, and the user-provided search term.\n    It returns a tuple containing a queryset modified to implement the search, and\n    a boolean indicating if the results may contain duplicates.\n\n    The default implementation searches the fields named in :attr:`ModelAdmin.search_fields`.\n\n    This method may be overridden with your own custom search method. For\n    example, you might wish to search by an integer field, or use an external\n    tool such as Solr or Haystack. You must establish if the queryset changes\n    implemented by your search method may introduce duplicates into the results,\n    and return ``True`` in the second element of the return value.\n\n    For example, to search by ``name`` and ``age``, you could use::\n\n        class PersonAdmin(admin.ModelAdmin):\n            list_display = ('name', 'age')\n            search_fields = ('name',)\n\n            def get_search_results(self, request, queryset, search_term):\n                queryset, use_distinct = super().get_search_results(request, queryset, search_term)\n                try:\n                    search_term_as_int = int(search_term)\n                except ValueError:\n                    pass\n                else:\n                    queryset |= self.model.objects.filter(age=search_term_as_int)\n                return queryset, use_distinct\n\n    This implementation is more efficient than ``search_fields =\n    ('name', '=age')`` which results in a string comparison for the numeric\n    field, for example ``... OR UPPER(\"polls_choice\".\"votes\"::text) = UPPER('4')``\n    on PostgreSQL.\n\n.. method:: ModelAdmin.save_related(request, form, formsets, change)\n\n    The ``save_related`` method is given the ``HttpRequest``, the parent\n    ``ModelForm`` instance, the list of inline formsets and a boolean value\n    based on whether the parent is being added or changed. Here you can do any\n    pre- or post-save operations for objects related to the parent. Note\n    that at this point the parent object and its form have already been saved.\n\n.. method:: ModelAdmin.get_autocomplete_fields(request)\n\n    The ``get_autocomplete_fields()`` method is given the ``HttpRequest`` and is\n    expected to return a ``list`` or ``tuple`` of field names that will be\n    displayed with an autocomplete widget as described above in the\n    :attr:`ModelAdmin.autocomplete_fields` section.\n\n.. method:: ModelAdmin.get_readonly_fields(request, obj=None)\n\n    The ``get_readonly_fields`` method is given the ``HttpRequest`` and the\n    ``obj`` being edited (or ``None`` on an add form) and is expected to return\n    a ``list`` or ``tuple`` of field names that will be displayed as read-only,\n    as described above in the :attr:`ModelAdmin.readonly_fields` section.\n\n.. method:: ModelAdmin.get_prepopulated_fields(request, obj=None)\n\n    The ``get_prepopulated_fields`` method is given the ``HttpRequest`` and the\n    ``obj`` being edited (or ``None`` on an add form) and is expected to return\n    a ``dictionary``, as described above in the :attr:`ModelAdmin.prepopulated_fields`\n    section.\n\n.. method:: ModelAdmin.get_list_display(request)\n\n    The ``get_list_display`` method is given the ``HttpRequest`` and is\n    expected to return a ``list`` or ``tuple`` of field names that will be\n    displayed on the changelist view as described above in the\n    :attr:`ModelAdmin.list_display` section.\n\n.. method:: ModelAdmin.get_list_display_links(request, list_display)\n\n    The ``get_list_display_links`` method is given the ``HttpRequest`` and\n    the ``list`` or ``tuple`` returned by :meth:`ModelAdmin.get_list_display`.\n    It is expected to return either ``None`` or a ``list`` or ``tuple`` of field\n    names on the changelist that will be linked to the change view, as described\n    in the :attr:`ModelAdmin.list_display_links` section.\n\n.. method:: ModelAdmin.get_exclude(request, obj=None)\n\n    The ``get_exclude`` method is given the ``HttpRequest`` and the ``obj``\n    being edited (or ``None`` on an add form) and is expected to return a list\n    of fields, as described in :attr:`ModelAdmin.exclude`.\n\n.. method:: ModelAdmin.get_fields(request, obj=None)\n\n    The ``get_fields`` method is given the ``HttpRequest`` and the ``obj``\n    being edited (or ``None`` on an add form) and is expected to return a list\n    of fields, as described above in the :attr:`ModelAdmin.fields` section.\n\n.. method:: ModelAdmin.get_fieldsets(request, obj=None)\n\n    The ``get_fieldsets`` method is given the ``HttpRequest`` and the ``obj``\n    being edited (or ``None`` on an add form) and is expected to return a list\n    of two-tuples, in which each two-tuple represents a ``<fieldset>`` on the\n    admin form page, as described above in the :attr:`ModelAdmin.fieldsets` section.\n\n.. method:: ModelAdmin.get_list_filter(request)\n\n    The ``get_list_filter`` method is given the ``HttpRequest`` and is expected\n    to return the same kind of sequence type as for the\n    :attr:`~ModelAdmin.list_filter` attribute.\n\n.. method:: ModelAdmin.get_list_select_related(request)\n\n    The ``get_list_select_related`` method is given the ``HttpRequest`` and\n    should return a boolean or list as :attr:`ModelAdmin.list_select_related`\n    does.\n\n.. method:: ModelAdmin.get_search_fields(request)\n\n    The ``get_search_fields`` method is given the ``HttpRequest`` and is expected\n    to return the same kind of sequence type as for the\n    :attr:`~ModelAdmin.search_fields` attribute.\n\n.. method:: ModelAdmin.get_sortable_by(request)\n\n    The ``get_sortable_by()`` method is passed the ``HttpRequest`` and is\n    expected to return a collection (e.g. ``list``, ``tuple``, or ``set``) of\n    field names that will be sortable in the change list page.\n\n    Its default implementation returns :attr:`sortable_by` if it's set,\n    otherwise it defers to :meth:`get_list_display`.\n\n    For example, to prevent one or more columns from being sortable::\n\n        class PersonAdmin(admin.ModelAdmin):\n\n            def get_sortable_by(self, request):\n                return {*self.get_list_display(request)} - {'rank'}\n\n.. method:: ModelAdmin.get_inline_instances(request, obj=None)\n\n    The ``get_inline_instances`` method is given the ``HttpRequest`` and the\n    ``obj`` being edited (or ``None`` on an add form) and is expected to return\n    a ``list`` or ``tuple`` of :class:`~django.contrib.admin.InlineModelAdmin`\n    objects, as described below in the :class:`~django.contrib.admin.InlineModelAdmin`\n    section. For example, the following would return inlines without the default\n    filtering based on add, change, delete, and view permissions::\n\n        class MyModelAdmin(admin.ModelAdmin):\n            inlines = (MyInline,)\n\n            def get_inline_instances(self, request, obj=None):\n                return [inline(self.model, self.admin_site) for inline in self.inlines]\n\n    If you override this method, make sure that the returned inlines are\n    instances of the classes defined in :attr:`inlines` or you might encounter\n    a \"Bad Request\" error when adding related objects.\n\n.. method:: ModelAdmin.get_inlines(request, obj)\n\n    The ``get_inlines`` method is given the ``HttpRequest`` and the\n    ``obj`` being edited (or ``None`` on an add form) and is expected to return\n    an iterable of inlines. You can override this method to dynamically add\n    inlines based on the request or model instance instead of specifying them\n    in :attr:`ModelAdmin.inlines`.\n\n.. method:: ModelAdmin.get_urls()\n\n    The ``get_urls`` method on a ``ModelAdmin`` returns the URLs to be used for\n    that ModelAdmin in the same way as a URLconf.  Therefore you can extend\n    them as documented in :doc:`/topics/http/urls`::\n\n        from django.contrib import admin\n        from django.template.response import TemplateResponse\n        from django.urls import path\n\n        class MyModelAdmin(admin.ModelAdmin):\n            def get_urls(self):\n                urls = super().get_urls()\n                my_urls = [\n                    path('my_view/', self.my_view),\n                ]\n                return my_urls + urls\n\n            def my_view(self, request):\n                # ...\n                context = dict(\n                   # Include common variables for rendering the admin template.\n                   self.admin_site.each_context(request),\n                   # Anything else you want in the context...\n                   key=value,\n                )\n                return TemplateResponse(request, \"sometemplate.html\", context)\n\n    If you want to use the admin layout, extend from ``admin/base_site.html``:\n\n    .. code-block:: html+django\n\n       {% extends \"admin/base_site.html\" %}\n       {% block content %}\n       ...\n       {% endblock %}\n\n    .. note::\n\n        Notice that the custom patterns are included *before* the regular admin\n        URLs: the admin URL patterns are very permissive and will match nearly\n        anything, so you'll usually want to prepend your custom URLs to the\n        built-in ones.\n\n        In this example, ``my_view`` will be accessed at\n        ``/admin/myapp/mymodel/my_view/`` (assuming the admin URLs are included\n        at ``/admin/``.)\n\n    However, the ``self.my_view`` function registered above suffers from two\n    problems:\n\n    * It will *not* perform any permission checks, so it will be accessible\n      to the general public.\n    * It will *not* provide any header details to prevent caching. This means\n      if the page retrieves data from the database, and caching middleware is\n      active, the page could show outdated information.\n\n    Since this is usually not what you want, Django provides a convenience\n    wrapper to check permissions and mark the view as non-cacheable. This\n    wrapper is ``AdminSite.admin_view()`` (i.e. ``self.admin_site.admin_view``\n    inside a ``ModelAdmin`` instance); use it like so::\n\n        class MyModelAdmin(admin.ModelAdmin):\n            def get_urls(self):\n                urls = super().get_urls()\n                my_urls = [\n                    path('my_view/', self.admin_site.admin_view(self.my_view))\n                ]\n                return my_urls + urls\n\n    Notice the wrapped view in the fifth line above::\n\n        path('my_view/', self.admin_site.admin_view(self.my_view))\n\n    This wrapping will protect ``self.my_view`` from unauthorized access and\n    will apply the :func:`django.views.decorators.cache.never_cache` decorator to\n    make sure it is not cached if the cache middleware is active.\n\n    If the page is cacheable, but you still want the permission check to be\n    performed, you can pass a ``cacheable=True`` argument to\n    ``AdminSite.admin_view()``::\n\n        path('my_view/', self.admin_site.admin_view(self.my_view, cacheable=True))\n\n    ``ModelAdmin`` views have ``model_admin`` attributes. Other\n    ``AdminSite`` views have ``admin_site`` attributes.\n\n.. method:: ModelAdmin.get_form(request, obj=None, **kwargs)\n\n    Returns a :class:`~django.forms.ModelForm` class for use in the admin add\n    and change views, see :meth:`add_view` and :meth:`change_view`.\n\n    The base implementation uses :func:`~django.forms.models.modelform_factory`\n    to subclass :attr:`~form`, modified by attributes such as :attr:`~fields`\n    and :attr:`~exclude`. So, for example, if you wanted to offer additional\n    fields to superusers, you could swap in a different base form like so::\n\n        class MyModelAdmin(admin.ModelAdmin):\n            def get_form(self, request, obj=None, **kwargs):\n                if request.user.is_superuser:\n                    kwargs['form'] = MySuperuserForm\n                return super().get_form(request, obj, **kwargs)\n\n    You may also return a custom :class:`~django.forms.ModelForm` class\n    directly.\n\n.. method:: ModelAdmin.get_formsets_with_inlines(request, obj=None)\n\n    Yields (``FormSet``, :class:`InlineModelAdmin`) pairs for use in admin add\n    and change views.\n\n    For example if you wanted to display a particular inline only in the change\n    view, you could override ``get_formsets_with_inlines`` as follows::\n\n        class MyModelAdmin(admin.ModelAdmin):\n            inlines = [MyInline, SomeOtherInline]\n\n            def get_formsets_with_inlines(self, request, obj=None):\n                for inline in self.get_inline_instances(request, obj):\n                    # hide MyInline in the add view\n                    if not isinstance(inline, MyInline) or obj is not None:\n                        yield inline.get_formset(request, obj), inline\n\n.. method:: ModelAdmin.formfield_for_foreignkey(db_field, request, **kwargs)\n\n    The ``formfield_for_foreignkey`` method on a ``ModelAdmin`` allows you to\n    override the default formfield for a foreign keys field. For example, to\n    return a subset of objects for this foreign key field based on the user::\n\n        class MyModelAdmin(admin.ModelAdmin):\n            def formfield_for_foreignkey(self, db_field, request, **kwargs):\n                if db_field.name == \"car\":\n                    kwargs[\"queryset\"] = Car.objects.filter(owner=request.user)\n                return super().formfield_for_foreignkey(db_field, request, **kwargs)\n\n    This uses the ``HttpRequest`` instance to filter the ``Car`` foreign key\n    field to only display the cars owned by the ``User`` instance.\n\n.. method:: ModelAdmin.formfield_for_manytomany(db_field, request, **kwargs)\n\n    Like the ``formfield_for_foreignkey`` method, the\n    ``formfield_for_manytomany`` method can be overridden to change the\n    default formfield for a many to many field. For example, if an owner can\n    own multiple cars and cars can belong to multiple owners -- a many to\n    many relationship -- you could filter the ``Car`` foreign key field to\n    only display the cars owned by the ``User``::\n\n        class MyModelAdmin(admin.ModelAdmin):\n            def formfield_for_manytomany(self, db_field, request, **kwargs):\n                if db_field.name == \"cars\":\n                    kwargs[\"queryset\"] = Car.objects.filter(owner=request.user)\n                return super().formfield_for_manytomany(db_field, request, **kwargs)\n\n.. method:: ModelAdmin.formfield_for_choice_field(db_field, request, **kwargs)\n\n    Like the ``formfield_for_foreignkey`` and ``formfield_for_manytomany``\n    methods, the ``formfield_for_choice_field`` method can be overridden to\n    change the default formfield for a field that has declared choices. For\n    example, if the choices available to a superuser should be different than\n    those available to regular staff, you could proceed as follows::\n\n        class MyModelAdmin(admin.ModelAdmin):\n            def formfield_for_choice_field(self, db_field, request, **kwargs):\n                if db_field.name == \"status\":\n                    kwargs['choices'] = (\n                        ('accepted', 'Accepted'),\n                        ('denied', 'Denied'),\n                    )\n                    if request.user.is_superuser:\n                        kwargs['choices'] += (('ready', 'Ready for deployment'),)\n                return super().formfield_for_choice_field(db_field, request, **kwargs)\n\n    .. admonition:: Note\n\n        Any ``choices`` attribute set on the formfield will be limited to the\n        form field only. If the corresponding field on the model has choices\n        set, the choices provided to the form must be a valid subset of those\n        choices, otherwise the form submission will fail with\n        a :exc:`~django.core.exceptions.ValidationError` when the model itself\n        is validated before saving.\n\n.. method:: ModelAdmin.get_changelist(request, **kwargs)\n\n    Returns the ``Changelist`` class to be used for listing. By default,\n    ``django.contrib.admin.views.main.ChangeList`` is used. By inheriting this\n    class you can change the behavior of the listing.\n\n.. method:: ModelAdmin.get_changelist_form(request, **kwargs)\n\n    Returns a :class:`~django.forms.ModelForm` class for use in the ``Formset``\n    on the changelist page. To use a custom form, for example::\n\n        from django import forms\n\n        class MyForm(forms.ModelForm):\n            pass\n\n        class MyModelAdmin(admin.ModelAdmin):\n            def get_changelist_form(self, request, **kwargs):\n                return MyForm\n\n    .. admonition:: Note\n\n        If you define the ``Meta.model`` attribute on a\n        :class:`~django.forms.ModelForm`, you must also define the\n        ``Meta.fields`` attribute (or the ``Meta.exclude`` attribute). However,\n        ``ModelAdmin`` ignores this value, overriding it with the\n        :attr:`ModelAdmin.list_editable` attribute. The easiest solution is to\n        omit the ``Meta.model`` attribute, since ``ModelAdmin`` will provide the\n        correct model to use.\n\n.. method::  ModelAdmin.get_changelist_formset(request, **kwargs)\n\n    Returns a :ref:`ModelFormSet <model-formsets>` class for use on the\n    changelist page if :attr:`~ModelAdmin.list_editable` is used. To use a\n    custom formset, for example::\n\n        from django.forms import BaseModelFormSet\n\n        class MyAdminFormSet(BaseModelFormSet):\n            pass\n\n        class MyModelAdmin(admin.ModelAdmin):\n            def get_changelist_formset(self, request, **kwargs):\n                kwargs['formset'] = MyAdminFormSet\n                return super().get_changelist_formset(request, **kwargs)\n\n.. method:: ModelAdmin.lookup_allowed(lookup, value)\n\n    The objects in the changelist page can be filtered with lookups from the\n    URL's query string. This is how :attr:`list_filter` works, for example. The\n    lookups are similar to what's used in :meth:`.QuerySet.filter` (e.g.\n    ``user__email=user@example.com``). Since the lookups in the query string\n    can be manipulated by the user, they must be sanitized to prevent\n    unauthorized data exposure.\n\n    The ``lookup_allowed()`` method is given a lookup path from the query string\n    (e.g. ``'user__email'``) and the corresponding value\n    (e.g. ``'user@example.com'``), and returns a boolean indicating whether\n    filtering the changelist's ``QuerySet`` using the parameters is permitted.\n    If ``lookup_allowed()`` returns ``False``, ``DisallowedModelAdminLookup``\n    (subclass of :exc:`~django.core.exceptions.SuspiciousOperation`) is raised.\n\n    By default, ``lookup_allowed()`` allows access to a model's local fields,\n    field paths used in :attr:`~ModelAdmin.list_filter` (but not paths from\n    :meth:`~ModelAdmin.get_list_filter`), and lookups required for\n    :attr:`~django.db.models.ForeignKey.limit_choices_to` to function\n    correctly in :attr:`~django.contrib.admin.ModelAdmin.raw_id_fields`.\n\n    Override this method to customize the lookups permitted for your\n    :class:`~django.contrib.admin.ModelAdmin` subclass.\n\n.. method:: ModelAdmin.has_view_permission(request, obj=None)\n\n    Should return ``True`` if viewing ``obj`` is permitted, ``False`` otherwise.\n    If obj is ``None``, should return ``True`` or ``False`` to indicate whether\n    viewing of objects of this type is permitted in general (e.g., ``False``\n    will be interpreted as meaning that the current user is not permitted to\n    view any object of this type).\n\n    The default implementation returns ``True`` if the user has either the\n    \"change\" or \"view\" permission.\n\n.. method:: ModelAdmin.has_add_permission(request)\n\n    Should return ``True`` if adding an object is permitted, ``False``\n    otherwise.\n\n.. method:: ModelAdmin.has_change_permission(request, obj=None)\n\n    Should return ``True`` if editing ``obj`` is permitted, ``False``\n    otherwise. If ``obj`` is ``None``, should return ``True`` or ``False`` to\n    indicate whether editing of objects of this type is permitted in general\n    (e.g., ``False`` will be interpreted as meaning that the current user is\n    not permitted to edit any object of this type).\n\n.. method:: ModelAdmin.has_delete_permission(request, obj=None)\n\n    Should return ``True`` if deleting ``obj`` is permitted, ``False``\n    otherwise. If ``obj`` is ``None``, should return ``True`` or ``False`` to\n    indicate whether deleting objects of this type is permitted in general\n    (e.g., ``False`` will be interpreted as meaning that the current user is\n    not permitted to delete any object of this type).\n\n.. method:: ModelAdmin.has_module_permission(request)\n\n    Should return ``True`` if displaying the module on the admin index page and\n    accessing the module's index page is permitted, ``False`` otherwise.\n    Uses :meth:`User.has_module_perms()\n    <django.contrib.auth.models.User.has_module_perms>` by default. Overriding\n    it does not restrict access to the view, add, change, or delete views,\n    :meth:`~ModelAdmin.has_view_permission`,\n    :meth:`~ModelAdmin.has_add_permission`,\n    :meth:`~ModelAdmin.has_change_permission`, and\n    :meth:`~ModelAdmin.has_delete_permission` should be used for that.\n\n.. method:: ModelAdmin.get_queryset(request)\n\n    The ``get_queryset`` method on a ``ModelAdmin`` returns a\n    :class:`~django.db.models.query.QuerySet` of all model instances that\n    can be edited by the admin site. One use case for overriding this method\n    is to show objects owned by the logged-in user::\n\n        class MyModelAdmin(admin.ModelAdmin):\n            def get_queryset(self, request):\n                qs = super().get_queryset(request)\n                if request.user.is_superuser:\n                    return qs\n                return qs.filter(author=request.user)\n\n.. method:: ModelAdmin.message_user(request, message, level=messages.INFO, extra_tags='', fail_silently=False)\n\n    Sends a message to the user using the :mod:`django.contrib.messages`\n    backend.  See the :ref:`custom ModelAdmin example <custom-admin-action>`.\n\n    Keyword arguments allow you to change the message level, add extra CSS\n    tags, or fail silently if the ``contrib.messages`` framework is not\n    installed. These keyword arguments match those for\n    :func:`django.contrib.messages.add_message`, see that function's\n    documentation for more details. One difference is that the level may be\n    passed as a string label in addition to integer/constant.\n\n.. method:: ModelAdmin.get_paginator(request, queryset, per_page, orphans=0, allow_empty_first_page=True)\n\n    Returns an instance of the paginator to use for this view. By default,\n    instantiates an instance of :attr:`paginator`.\n\n.. method:: ModelAdmin.response_add(request, obj, post_url_continue=None)\n\n    Determines the :class:`~django.http.HttpResponse` for the\n    :meth:`add_view` stage.\n\n    ``response_add`` is called after the admin form is submitted and\n    just after the object and all the related instances have\n    been created and saved. You can override it to change the default behavior\n    after the object has been created.\n\n.. method:: ModelAdmin.response_change(request, obj)\n\n    Determines the :class:`~django.http.HttpResponse` for the\n    :meth:`change_view` stage.\n\n    ``response_change`` is called after the admin form is submitted and\n    just after the object and all the related instances have\n    been saved. You can override it to change the default\n    behavior after the object has been changed.\n\n.. method:: ModelAdmin.response_delete(request, obj_display, obj_id)\n\n    Determines the :class:`~django.http.HttpResponse` for the\n    :meth:`delete_view` stage.\n\n    ``response_delete`` is called after the object has been\n    deleted. You can override it to change the default\n    behavior after the object has been deleted.\n\n    ``obj_display`` is a string with the name of the deleted\n    object.\n\n    ``obj_id`` is the serialized identifier used to retrieve the object to be\n    deleted.\n\n.. method:: ModelAdmin.get_changeform_initial_data(request)\n\n    A hook for the initial data on admin change forms. By default, fields are\n    given initial values from ``GET`` parameters. For instance,\n    ``?name=initial_value`` will set the ``name`` field's initial value to be\n    ``initial_value``.\n\n    This method should return a dictionary in the form\n    ``{'fieldname': 'fieldval'}``::\n\n        def get_changeform_initial_data(self, request):\n            return {'name': 'custom_initial_value'}\n\n.. method:: ModelAdmin.get_deleted_objects(objs, request)\n\n    A hook for customizing the deletion process of the :meth:`delete_view` and\n    the \"delete selected\" :doc:`action <actions>`.\n\n    The ``objs`` argument is a homogeneous iterable of objects (a ``QuerySet``\n    or a list of model instances) to be deleted, and ``request`` is the\n    :class:`~django.http.HttpRequest`.\n\n    This method must return a 4-tuple of\n    ``(deleted_objects, model_count, perms_needed, protected)``.\n\n    ``deleted_objects`` is a list of strings representing all the objects that\n    will be deleted. If there are any related objects to be deleted, the list\n    is nested and includes those related objects. The list is formatted in the\n    template using the :tfilter:`unordered_list` filter.\n\n    ``model_count`` is a dictionary mapping each model's\n    :attr:`~django.db.models.Options.verbose_name_plural` to the number of\n    objects that will be deleted.\n\n    ``perms_needed`` is a set of :attr:`~django.db.models.Options.verbose_name`\\s\n    of the models that the user doesn't have permission to delete.\n\n    ``protected`` is a list of strings representing of all the protected\n    related objects that can't be deleted. The list is displayed in the\n    template.\n\nOther methods\n~~~~~~~~~~~~~\n\n.. method:: ModelAdmin.add_view(request, form_url='', extra_context=None)\n\n    Django view for the model instance addition page. See note below.\n\n.. method:: ModelAdmin.change_view(request, object_id, form_url='', extra_context=None)\n\n    Django view for the model instance editing page. See note below.\n\n.. method:: ModelAdmin.changelist_view(request, extra_context=None)\n\n    Django view for the model instances change list/actions page. See note\n    below.\n\n.. method:: ModelAdmin.delete_view(request, object_id, extra_context=None)\n\n    Django view for the model instance(s) deletion confirmation page. See note\n    below.\n\n.. method:: ModelAdmin.history_view(request, object_id, extra_context=None)\n\n    Django view for the page that shows the modification history for a given\n    model instance.\n\nUnlike the hook-type ``ModelAdmin`` methods detailed in the previous section,\nthese five methods are in reality designed to be invoked as Django views from\nthe admin application URL dispatching handler to render the pages that deal\nwith model instances CRUD operations. As a result, completely overriding these\nmethods will significantly change the behavior of the admin application.\n\nOne common reason for overriding these methods is to augment the context data\nthat is provided to the template that renders the view. In the following\nexample, the change view is overridden so that the rendered template is\nprovided some extra mapping data that would not otherwise be available::\n\n    class MyModelAdmin(admin.ModelAdmin):\n\n        # A template for a very customized change view:\n        change_form_template = 'admin/myapp/extras/openstreetmap_change_form.html'\n\n        def get_osm_info(self):\n            # ...\n            pass\n\n        def change_view(self, request, object_id, form_url='', extra_context=None):\n            extra_context = extra_context or {}\n            extra_context['osm_data'] = self.get_osm_info()\n            return super().change_view(\n                request, object_id, form_url, extra_context=extra_context,\n            )\n\nThese views return :class:`~django.template.response.TemplateResponse`\ninstances which allow you to easily customize the response data before\nrendering. For more details, see the :doc:`TemplateResponse documentation\n</ref/template-response>`.\n\n.. _modeladmin-asset-definitions:\n\n``ModelAdmin`` asset definitions\n--------------------------------\n\nThere are times where you would like add a bit of CSS and/or JavaScript to\nthe add/change views. This can be accomplished by using a ``Media`` inner class\non your ``ModelAdmin``::\n\n    class ArticleAdmin(admin.ModelAdmin):\n        class Media:\n            css = {\n                \"all\": (\"my_styles.css\",)\n            }\n            js = (\"my_code.js\",)\n\nThe :doc:`staticfiles app </ref/contrib/staticfiles>` prepends\n:setting:`STATIC_URL` (or :setting:`MEDIA_URL` if :setting:`STATIC_URL` is\n``None``) to any asset paths. The same rules apply as :ref:`regular asset\ndefinitions on forms <form-asset-paths>`.\n\n.. _contrib-admin-jquery:\n\njQuery\n~~~~~~\n\nDjango admin JavaScript makes use of the `jQuery`_ library.\n\nTo avoid conflicts with user-supplied scripts or libraries, Django's jQuery\n(version 3.5.1) is namespaced as ``django.jQuery``. If you want to use jQuery\nin your own admin JavaScript without including a second copy, you can use the\n``django.jQuery`` object on changelist and add/edit views.\n\n.. versionchanged:: 3.1\n\n    jQuery was upgraded from 3.4.1 to 3.5.1.\n\nThe :class:`ModelAdmin` class requires jQuery by default, so there is no need\nto add jQuery to your ``ModelAdmin``’s list of media resources unless you have\na specific need. For example, if you require the jQuery library to be in the\nglobal namespace (for example when using third-party jQuery plugins) or if you\nneed a newer version of jQuery, you will have to include your own copy.\n\nDjango provides both uncompressed and 'minified' versions of jQuery, as\n``jquery.js`` and ``jquery.min.js`` respectively.\n\n:class:`ModelAdmin` and :class:`InlineModelAdmin` have a ``media`` property\nthat returns a list of ``Media`` objects which store paths to the JavaScript\nfiles for the forms and/or formsets. If :setting:`DEBUG` is ``True`` it will\nreturn the uncompressed versions of the various JavaScript files, including\n``jquery.js``; if not, it will return the 'minified' versions.\n\n.. _jQuery: https://jquery.com\n\n.. _admin-custom-validation:\n\nAdding custom validation to the admin\n-------------------------------------\n\nYou can also add custom validation of data in the admin. The automatic admin\ninterface reuses :mod:`django.forms`, and the ``ModelAdmin`` class gives you\nthe ability define your own form::\n\n    class ArticleAdmin(admin.ModelAdmin):\n        form = MyArticleAdminForm\n\n``MyArticleAdminForm`` can be defined anywhere as long as you import where\nneeded. Now within your form you can add your own custom validation for\nany field::\n\n    class MyArticleAdminForm(forms.ModelForm):\n        def clean_name(self):\n            # do something that validates your data\n            return self.cleaned_data[\"name\"]\n\nIt is important you use a ``ModelForm`` here otherwise things can break. See\nthe :doc:`forms </ref/forms/index>` documentation on :doc:`custom validation\n</ref/forms/validation>` and, more specifically, the\n:ref:`model form validation notes <overriding-modelform-clean-method>` for more\ninformation.\n\n.. _admin-inlines:\n\n``InlineModelAdmin`` objects\n============================\n\n.. class:: InlineModelAdmin\n.. class:: TabularInline\n.. class:: StackedInline\n\n    The admin interface has the ability to edit models on the same page as a\n    parent model. These are called inlines. Suppose you have these two models::\n\n         from django.db import models\n\n         class Author(models.Model):\n            name = models.CharField(max_length=100)\n\n         class Book(models.Model):\n            author = models.ForeignKey(Author, on_delete=models.CASCADE)\n            title = models.CharField(max_length=100)\n\n    You can edit the books authored by an author on the author page. You add\n    inlines to a model by specifying them in a ``ModelAdmin.inlines``::\n\n        from django.contrib import admin\n\n        class BookInline(admin.TabularInline):\n            model = Book\n\n        class AuthorAdmin(admin.ModelAdmin):\n            inlines = [\n                BookInline,\n            ]\n\n    Django provides two subclasses of ``InlineModelAdmin`` and they are:\n\n    * :class:`~django.contrib.admin.TabularInline`\n    * :class:`~django.contrib.admin.StackedInline`\n\n    The difference between these two is merely the template used to render\n    them.\n\n``InlineModelAdmin`` options\n-----------------------------\n\n``InlineModelAdmin`` shares many of the same features as ``ModelAdmin``, and\nadds some of its own (the shared features are actually defined in the\n``BaseModelAdmin`` superclass). The shared features are:\n\n- :attr:`~InlineModelAdmin.form`\n- :attr:`~ModelAdmin.fieldsets`\n- :attr:`~ModelAdmin.fields`\n- :attr:`~ModelAdmin.formfield_overrides`\n- :attr:`~ModelAdmin.exclude`\n- :attr:`~ModelAdmin.filter_horizontal`\n- :attr:`~ModelAdmin.filter_vertical`\n- :attr:`~ModelAdmin.ordering`\n- :attr:`~ModelAdmin.prepopulated_fields`\n- :meth:`~ModelAdmin.get_fieldsets`\n- :meth:`~ModelAdmin.get_queryset`\n- :attr:`~ModelAdmin.radio_fields`\n- :attr:`~ModelAdmin.readonly_fields`\n- :attr:`~InlineModelAdmin.raw_id_fields`\n- :meth:`~ModelAdmin.formfield_for_choice_field`\n- :meth:`~ModelAdmin.formfield_for_foreignkey`\n- :meth:`~ModelAdmin.formfield_for_manytomany`\n- :meth:`~ModelAdmin.has_module_permission`\n\nThe ``InlineModelAdmin`` class adds or customizes:\n\n.. attribute:: InlineModelAdmin.model\n\n    The model which the inline is using. This is required.\n\n.. attribute:: InlineModelAdmin.fk_name\n\n    The name of the foreign key on the model. In most cases this will be dealt\n    with automatically, but ``fk_name`` must be specified explicitly if there\n    are more than one foreign key to the same parent model.\n\n.. attribute:: InlineModelAdmin.formset\n\n    This defaults to :class:`~django.forms.models.BaseInlineFormSet`. Using\n    your own formset can give you many possibilities of customization. Inlines\n    are built around :ref:`model formsets <model-formsets>`.\n\n.. attribute:: InlineModelAdmin.form\n\n    The value for ``form`` defaults to ``ModelForm``. This is what is passed\n    through to :func:`~django.forms.models.inlineformset_factory` when\n    creating the formset for this inline.\n\n.. warning::\n    When writing custom validation for ``InlineModelAdmin`` forms, be cautious\n    of writing validation that relies on features of the parent model. If the\n    parent model fails to validate, it may be left in an inconsistent state as\n    described in the warning in :ref:`validation-on-modelform`.\n\n.. attribute:: InlineModelAdmin.classes\n\n    A list or tuple containing extra CSS classes to apply to the fieldset that\n    is rendered for the inlines. Defaults to ``None``. As with classes\n    configured in :attr:`~ModelAdmin.fieldsets`, inlines with a ``collapse``\n    class will be initially collapsed and their header will have a small \"show\"\n    link.\n\n.. attribute:: InlineModelAdmin.extra\n\n    This controls the number of extra forms the formset will display in\n    addition to the initial forms. Defaults to 3. See the\n    :doc:`formsets documentation </topics/forms/formsets>` for more\n    information.\n\n    For users with JavaScript-enabled browsers, an \"Add another\" link is\n    provided to enable any number of additional inlines to be added in addition\n    to those provided as a result of the ``extra`` argument.\n\n    The dynamic link will not appear if the number of currently displayed forms\n    exceeds ``max_num``, or if the user does not have JavaScript enabled.\n\n    :meth:`InlineModelAdmin.get_extra` also allows you to customize the number\n    of extra forms.\n\n.. attribute:: InlineModelAdmin.max_num\n\n    This controls the maximum number of forms to show in the inline. This\n    doesn't directly correlate to the number of objects, but can if the value\n    is small enough. See :ref:`model-formsets-max-num` for more information.\n\n    :meth:`InlineModelAdmin.get_max_num` also allows you to customize the\n    maximum number of extra forms.\n\n.. attribute:: InlineModelAdmin.min_num\n\n    This controls the minimum number of forms to show in the inline.\n    See :func:`~django.forms.models.modelformset_factory` for more information.\n\n    :meth:`InlineModelAdmin.get_min_num` also allows you to customize the\n    minimum number of displayed forms.\n\n.. attribute:: InlineModelAdmin.raw_id_fields\n\n    By default, Django's admin uses a select-box interface (<select>) for\n    fields that are ``ForeignKey``. Sometimes you don't want to incur the\n    overhead of having to select all the related instances to display in the\n    drop-down.\n\n    ``raw_id_fields`` is a list of fields you would like to change into an\n    ``Input`` widget for either a ``ForeignKey`` or ``ManyToManyField``::\n\n        class BookInline(admin.TabularInline):\n            model = Book\n            raw_id_fields = (\"pages\",)\n\n\n.. attribute:: InlineModelAdmin.template\n\n    The template used to render the inline on the page.\n\n.. attribute:: InlineModelAdmin.verbose_name\n\n    An override to the ``verbose_name`` found in the model's inner ``Meta``\n    class.\n\n.. attribute:: InlineModelAdmin.verbose_name_plural\n\n    An override to the ``verbose_name_plural`` found in the model's inner\n    ``Meta`` class.\n\n.. attribute:: InlineModelAdmin.can_delete\n\n    Specifies whether or not inline objects can be deleted in the inline.\n    Defaults to ``True``.\n\n.. attribute:: InlineModelAdmin.show_change_link\n\n    Specifies whether or not inline objects that can be changed in the\n    admin have a link to the change form. Defaults to ``False``.\n\n.. method:: InlineModelAdmin.get_formset(request, obj=None, **kwargs)\n\n    Returns a :class:`~django.forms.models.BaseInlineFormSet` class for use in\n    admin add/change views. ``obj`` is the parent object being edited or\n    ``None`` when adding a new parent. See the example for\n    :class:`ModelAdmin.get_formsets_with_inlines`.\n\n.. method:: InlineModelAdmin.get_extra(request, obj=None, **kwargs)\n\n    Returns the number of extra inline forms to use. By default, returns the\n    :attr:`InlineModelAdmin.extra` attribute.\n\n    Override this method to programmatically determine the number of extra\n    inline forms. For example, this may be based on the model instance\n    (passed as the keyword argument ``obj``)::\n\n        class BinaryTreeAdmin(admin.TabularInline):\n            model = BinaryTree\n\n            def get_extra(self, request, obj=None, **kwargs):\n                extra = 2\n                if obj:\n                    return extra - obj.binarytree_set.count()\n                return extra\n\n.. method:: InlineModelAdmin.get_max_num(request, obj=None, **kwargs)\n\n    Returns the maximum number of extra inline forms to use. By default,\n    returns the :attr:`InlineModelAdmin.max_num` attribute.\n\n    Override this method to programmatically determine the maximum number of\n    inline forms. For example, this may be based on the model instance\n    (passed as the keyword argument ``obj``)::\n\n        class BinaryTreeAdmin(admin.TabularInline):\n            model = BinaryTree\n\n            def get_max_num(self, request, obj=None, **kwargs):\n                max_num = 10\n                if obj and obj.parent:\n                    return max_num - 5\n                return max_num\n\n.. method:: InlineModelAdmin.get_min_num(request, obj=None, **kwargs)\n\n    Returns the minimum number of inline forms to use. By default,\n    returns the :attr:`InlineModelAdmin.min_num` attribute.\n\n    Override this method to programmatically determine the minimum number of\n    inline forms. For example, this may be based on the model instance\n    (passed as the keyword argument ``obj``).\n\n.. method:: InlineModelAdmin.has_add_permission(request, obj)\n\n    Should return ``True`` if adding an inline object is permitted, ``False``\n    otherwise. ``obj`` is the parent object being edited or ``None`` when\n    adding a new parent.\n\n.. method:: InlineModelAdmin.has_change_permission(request, obj=None)\n\n    Should return ``True`` if editing an inline object is permitted, ``False``\n    otherwise. ``obj`` is the parent object being edited.\n\n.. method:: InlineModelAdmin.has_delete_permission(request, obj=None)\n\n    Should return ``True`` if deleting an inline object is permitted, ``False``\n    otherwise. ``obj`` is the parent object being edited.\n\n.. note::\n    The ``obj`` argument passed to ``InlineModelAdmin`` methods is the parent\n    object being edited or ``None`` when adding a new parent.\n\nWorking with a model with two or more foreign keys to the same parent model\n---------------------------------------------------------------------------\n\nIt is sometimes possible to have more than one foreign key to the same model.\nTake this model for instance::\n\n    from django.db import models\n\n    class Friendship(models.Model):\n        to_person = models.ForeignKey(Person, on_delete=models.CASCADE, related_name=\"friends\")\n        from_person = models.ForeignKey(Person, on_delete=models.CASCADE, related_name=\"from_friends\")\n\nIf you wanted to display an inline on the ``Person`` admin add/change pages\nyou need to explicitly define the foreign key since it is unable to do so\nautomatically::\n\n    from django.contrib import admin\n    from myapp.models import Friendship\n\n    class FriendshipInline(admin.TabularInline):\n        model = Friendship\n        fk_name = \"to_person\"\n\n    class PersonAdmin(admin.ModelAdmin):\n        inlines = [\n            FriendshipInline,\n        ]\n\nWorking with many-to-many models\n--------------------------------\n\nBy default, admin widgets for many-to-many relations will be displayed\non whichever model contains the actual reference to the\n:class:`~django.db.models.ManyToManyField`. Depending on your ``ModelAdmin``\ndefinition, each many-to-many field in your model will be represented by a\nstandard HTML ``<select multiple>``, a horizontal or vertical filter, or a\n``raw_id_admin`` widget. However, it is also possible to replace these\nwidgets with inlines.\n\nSuppose we have the following models::\n\n    from django.db import models\n\n    class Person(models.Model):\n        name = models.CharField(max_length=128)\n\n    class Group(models.Model):\n        name = models.CharField(max_length=128)\n        members = models.ManyToManyField(Person, related_name='groups')\n\nIf you want to display many-to-many relations using an inline, you can do\nso by defining an ``InlineModelAdmin`` object for the relationship::\n\n    from django.contrib import admin\n\n    class MembershipInline(admin.TabularInline):\n        model = Group.members.through\n\n    class PersonAdmin(admin.ModelAdmin):\n        inlines = [\n            MembershipInline,\n        ]\n\n    class GroupAdmin(admin.ModelAdmin):\n        inlines = [\n            MembershipInline,\n        ]\n        exclude = ('members',)\n\nThere are two features worth noting in this example.\n\nFirstly - the ``MembershipInline`` class references ``Group.members.through``.\nThe ``through`` attribute is a reference to the model that manages the\nmany-to-many relation. This model is automatically created by Django when you\ndefine a many-to-many field.\n\nSecondly, the ``GroupAdmin`` must manually exclude the ``members`` field.\nDjango displays an admin widget for a many-to-many field on the model that\ndefines the relation (in this case, ``Group``). If you want to use an inline\nmodel to represent the many-to-many relationship, you must tell Django's admin\nto *not* display this widget - otherwise you will end up with two widgets on\nyour admin page for managing the relation.\n\nNote that when using this technique the\n:data:`~django.db.models.signals.m2m_changed` signals aren't triggered. This\nis because as far as the admin is concerned, ``through`` is just a model with\ntwo foreign key fields rather than a many-to-many relation.\n\nIn all other respects, the ``InlineModelAdmin`` is exactly the same as any\nother. You can customize the appearance using any of the normal\n``ModelAdmin`` properties.\n\nWorking with many-to-many intermediary models\n---------------------------------------------\n\nWhen you specify an intermediary model using the ``through`` argument to a\n:class:`~django.db.models.ManyToManyField`, the admin will not display a\nwidget by default. This is because each instance of that intermediary model\nrequires more information than could be displayed in a single widget, and the\nlayout required for multiple widgets will vary depending on the intermediate\nmodel.\n\nHowever, we still want to be able to edit that information inline. Fortunately,\nwe can do this with inline admin models. Suppose we have the following models::\n\n    from django.db import models\n\n    class Person(models.Model):\n        name = models.CharField(max_length=128)\n\n    class Group(models.Model):\n        name = models.CharField(max_length=128)\n        members = models.ManyToManyField(Person, through='Membership')\n\n    class Membership(models.Model):\n        person = models.ForeignKey(Person, on_delete=models.CASCADE)\n        group = models.ForeignKey(Group, on_delete=models.CASCADE)\n        date_joined = models.DateField()\n        invite_reason = models.CharField(max_length=64)\n\nThe first step in displaying this intermediate model in the admin is to\ndefine an inline class for the ``Membership`` model::\n\n    class MembershipInline(admin.TabularInline):\n        model = Membership\n        extra = 1\n\nThis example uses the default ``InlineModelAdmin`` values for the\n``Membership`` model, and limits the extra add forms to one. This could be\ncustomized using any of the options available to ``InlineModelAdmin`` classes.\n\nNow create admin views for the ``Person`` and ``Group`` models::\n\n    class PersonAdmin(admin.ModelAdmin):\n        inlines = (MembershipInline,)\n\n    class GroupAdmin(admin.ModelAdmin):\n        inlines = (MembershipInline,)\n\nFinally, register your ``Person`` and ``Group`` models with the admin site::\n\n    admin.site.register(Person, PersonAdmin)\n    admin.site.register(Group, GroupAdmin)\n\nNow your admin site is set up to edit ``Membership`` objects inline from\neither the ``Person`` or the ``Group`` detail pages.\n\n.. _using-generic-relations-as-an-inline:\n\nUsing generic relations as an inline\n------------------------------------\n\nIt is possible to use an inline with generically related objects. Let's say\nyou have the following models::\n\n    from django.contrib.contenttypes.fields import GenericForeignKey\n    from django.db import models\n\n    class Image(models.Model):\n        image = models.ImageField(upload_to=\"images\")\n        content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)\n        object_id = models.PositiveIntegerField()\n        content_object = GenericForeignKey(\"content_type\", \"object_id\")\n\n    class Product(models.Model):\n        name = models.CharField(max_length=100)\n\nIf you want to allow editing and creating an ``Image`` instance on the\n``Product``, add/change views you can use\n:class:`~django.contrib.contenttypes.admin.GenericTabularInline`\nor :class:`~django.contrib.contenttypes.admin.GenericStackedInline` (both\nsubclasses of :class:`~django.contrib.contenttypes.admin.GenericInlineModelAdmin`)\nprovided by :mod:`~django.contrib.contenttypes.admin`. They implement tabular\nand stacked visual layouts for the forms representing the inline objects,\nrespectively, just like their non-generic counterparts. They behave just like\nany other inline. In your ``admin.py`` for this example app::\n\n    from django.contrib import admin\n    from django.contrib.contenttypes.admin import GenericTabularInline\n\n    from myproject.myapp.models import Image, Product\n\n    class ImageInline(GenericTabularInline):\n        model = Image\n\n    class ProductAdmin(admin.ModelAdmin):\n        inlines = [\n            ImageInline,\n        ]\n\n    admin.site.register(Product, ProductAdmin)\n\nSee the :doc:`contenttypes documentation </ref/contrib/contenttypes>` for more\nspecific information.\n\n.. _admin-overriding-templates:\n\nOverriding admin templates\n==========================\n\nYou can override many of the templates which the admin module uses to generate\nthe various pages of an admin site. You can even override a few of these\ntemplates for a specific app, or a specific model.\n\nSet up your projects admin template directories\n-----------------------------------------------\n\nThe admin template files are located in the ``contrib/admin/templates/admin``\ndirectory.\n\nIn order to override one or more of them, first create an ``admin`` directory\nin your project's ``templates`` directory. This can be any of the directories\nyou specified in the :setting:`DIRS <TEMPLATES-DIRS>` option of the\n``DjangoTemplates`` backend in the :setting:`TEMPLATES` setting. If you have\ncustomized the ``'loaders'`` option, be sure\n``'django.template.loaders.filesystem.Loader'`` appears before\n``'django.template.loaders.app_directories.Loader'`` so that your custom\ntemplates will be found by the template loading system before those that are\nincluded with :mod:`django.contrib.admin`.\n\nWithin this ``admin`` directory, create sub-directories named after your app.\nWithin these app subdirectories create sub-directories named after your models.\nNote, that the admin app will lowercase the model name when looking for the\ndirectory, so make sure you name the directory in all lowercase if you are\ngoing to run your app on a case-sensitive filesystem.\n\nTo override an admin template for a specific app, copy and edit the template\nfrom the ``django/contrib/admin/templates/admin`` directory, and save it to one\nof the directories you just created.\n\nFor example, if we wanted to add a tool to the change list view for all the\nmodels in an app named ``my_app``, we would copy\n``contrib/admin/templates/admin/change_list.html`` to the\n``templates/admin/my_app/`` directory of our project, and make any necessary\nchanges.\n\nIf we wanted to add a tool to the change list view for only a specific model\nnamed 'Page', we would copy that same file to the\n``templates/admin/my_app/page`` directory of our project.\n\nOverriding vs. replacing an admin template\n------------------------------------------\n\nBecause of the modular design of the admin templates, it is usually neither\nnecessary nor advisable to replace an entire template. It is almost always\nbetter to override only the section of the template which you need to change.\n\nTo continue the example above, we want to add a new link next to the\n``History`` tool for the ``Page`` model. After looking at ``change_form.html``\nwe determine that we only need to override the ``object-tools-items`` block.\nTherefore here is our new ``change_form.html`` :\n\n.. code-block:: html+django\n\n    {% extends \"admin/change_form.html\" %}\n    {% load i18n admin_urls %}\n    {% block object-tools-items %}\n        <li>\n            <a href=\"{% url opts|admin_urlname:'history' original.pk|admin_urlquote %}\" class=\"historylink\">{% translate \"History\" %}</a>\n        </li>\n        <li>\n            <a href=\"mylink/\" class=\"historylink\">My Link</a>\n        </li>\n        {% if has_absolute_url %}\n            <li>\n                <a href=\"{% url 'admin:view_on_site' content_type_id original.pk %}\" class=\"viewsitelink\">{% translate \"View on site\" %}</a>\n            </li>\n        {% endif %}\n    {% endblock %}\n\nAnd that's it! If we placed this file in the ``templates/admin/my_app``\ndirectory, our link would appear on the change form for all models within\nmy_app.\n\n.. _admin-templates-overridden-per-app-or-model:\n\nTemplates which may be overridden per app or model\n--------------------------------------------------\n\nNot every template in ``contrib/admin/templates/admin`` may be overridden per\napp or per model. The following can:\n\n* ``actions.html``\n* ``app_index.html``\n* ``change_form.html``\n* ``change_form_object_tools.html``\n* ``change_list.html``\n* ``change_list_object_tools.html``\n* ``change_list_results.html``\n* ``date_hierarchy.html``\n* ``delete_confirmation.html``\n* ``object_history.html``\n* ``pagination.html``\n* ``popup_response.html``\n* ``prepopulated_fields_js.html``\n* ``search_form.html``\n* ``submit_line.html``\n\nFor those templates that cannot be overridden in this way, you may still\noverride them for your entire project by placing the new version in your\n``templates/admin`` directory. This is particularly useful to create custom 404\nand 500 pages.\n\n.. note::\n\n    Some of the admin templates, such as ``change_list_results.html`` are used\n    to render custom inclusion tags. These may be overridden, but in such cases\n    you are probably better off creating your own version of the tag in\n    question and giving it a different name. That way you can use it\n    selectively.\n\nRoot and login templates\n------------------------\n\nIf you wish to change the index, login or logout templates, you are better off\ncreating your own ``AdminSite`` instance (see below), and changing the\n:attr:`AdminSite.index_template` , :attr:`AdminSite.login_template` or\n:attr:`AdminSite.logout_template` properties.\n\n``AdminSite`` objects\n=====================\n\n.. class:: AdminSite(name='admin')\n\n    A Django administrative site is represented by an instance of\n    ``django.contrib.admin.sites.AdminSite``; by default, an instance of\n    this class is created as ``django.contrib.admin.site`` and you can\n    register your models and ``ModelAdmin`` instances with it.\n\n    If you want to customize the default admin site, you can :ref:`override it\n    <overriding-default-admin-site>`.\n\n    When constructing an instance of an ``AdminSite``, you can provide\n    a unique instance name using the ``name`` argument to the constructor. This\n    instance name is used to identify the instance, especially when\n    :ref:`reversing admin URLs <admin-reverse-urls>`. If no instance name is\n    provided, a default instance name of ``admin`` will be used.\n    See :ref:`customizing-adminsite` for an example of customizing the\n    :class:`AdminSite` class.\n\n``AdminSite`` attributes\n------------------------\n\nTemplates can override or extend base admin templates as described in\n:ref:`admin-overriding-templates`.\n\n.. attribute:: AdminSite.site_header\n\n    The text to put at the top of each admin page, as an ``<h1>`` (a string).\n    By default, this is \"Django administration\".\n\n.. attribute:: AdminSite.site_title\n\n    The text to put at the end of each admin page's ``<title>`` (a string). By\n    default, this is \"Django site admin\".\n\n.. attribute:: AdminSite.site_url\n\n    The URL for the \"View site\" link at the top of each admin page. By default,\n    ``site_url`` is ``/``. Set it to ``None`` to remove the link.\n\n    For sites running on a subpath, the :meth:`each_context` method checks if\n    the current request has ``request.META['SCRIPT_NAME']`` set and uses that\n    value if ``site_url`` isn't set to something other than ``/``.\n\n.. attribute:: AdminSite.index_title\n\n    The text to put at the top of the admin index page (a string). By default,\n    this is \"Site administration\".\n\n.. attribute:: AdminSite.index_template\n\n    Path to a custom template that will be used by the admin site main index\n    view.\n\n.. attribute:: AdminSite.app_index_template\n\n    Path to a custom template that will be used by the admin site app index view.\n\n.. attribute:: AdminSite.empty_value_display\n\n    The string to use for displaying empty values in the admin site's change\n    list. Defaults to a dash. The value can also be overridden on a per\n    ``ModelAdmin`` basis and on a custom field within a ``ModelAdmin`` by\n    setting an ``empty_value_display`` attribute on the field. See\n    :attr:`ModelAdmin.empty_value_display` for examples.\n\n.. attribute:: AdminSite.enable_nav_sidebar\n\n    .. versionadded:: 3.1\n\n    A boolean value that determines whether to show the navigation sidebar\n    on larger screens. By default, it is set to ``True``.\n\n.. attribute:: AdminSite.login_template\n\n    Path to a custom template that will be used by the admin site login view.\n\n.. attribute:: AdminSite.login_form\n\n    Subclass of :class:`~django.contrib.auth.forms.AuthenticationForm` that\n    will be used by the admin site login view.\n\n.. attribute:: AdminSite.logout_template\n\n    Path to a custom template that will be used by the admin site logout view.\n\n.. attribute:: AdminSite.password_change_template\n\n    Path to a custom template that will be used by the admin site password\n    change view.\n\n.. attribute:: AdminSite.password_change_done_template\n\n    Path to a custom template that will be used by the admin site password\n    change done view.\n\n``AdminSite`` methods\n---------------------\n\n.. method:: AdminSite.each_context(request)\n\n    Returns a dictionary of variables to put in the template context for\n    every page in the admin site.\n\n    Includes the following variables and values by default:\n\n    * ``site_header``: :attr:`AdminSite.site_header`\n    * ``site_title``: :attr:`AdminSite.site_title`\n    * ``site_url``: :attr:`AdminSite.site_url`\n    * ``has_permission``: :meth:`AdminSite.has_permission`\n    * ``available_apps``: a list of applications from the :doc:`application registry\n      </ref/applications/>` available for the current user. Each entry in the\n      list is a dict representing an application with the following keys:\n\n      * ``app_label``: the application label\n      * ``app_url``: the URL of the application index in the admin\n      * ``has_module_perms``: a boolean indicating if displaying and accessing of\n        the module's index page is permitted for the current user\n      * ``models``: a list of the models available in the application\n\n      Each model is a dict with the following keys:\n\n      * ``object_name``: class name of the model\n      * ``name``: plural name of the model\n      * ``perms``: a ``dict`` tracking ``add``, ``change``, ``delete``, and\n        ``view`` permissions\n      * ``admin_url``: admin changelist URL for the model\n      * ``add_url``: admin URL to add a new model instance\n\n.. method:: AdminSite.has_permission(request)\n\n    Returns ``True`` if the user for the given ``HttpRequest`` has permission\n    to view at least one page in the admin site. Defaults to requiring both\n    :attr:`User.is_active <django.contrib.auth.models.User.is_active>` and\n    :attr:`User.is_staff <django.contrib.auth.models.User.is_staff>` to be\n    ``True``.\n\n.. method:: AdminSite.register(model_or_iterable, admin_class=None, **options)\n\n    Registers the given model class (or iterable of classes) with the given\n    ``admin_class``. ``admin_class`` defaults to\n    :class:`~django.contrib.admin.ModelAdmin` (the default admin options). If\n    keyword arguments are given -- e.g. ``list_display`` -- they'll be applied\n    as options to the admin class.\n\n    Raises :class:`~django.core.exceptions.ImproperlyConfigured` if a model is\n    abstract. and ``django.contrib.admin.sites.AlreadyRegistered`` if a model\n    is already registered.\n\n.. _hooking-adminsite-to-urlconf:\n\nHooking ``AdminSite`` instances into your URLconf\n-------------------------------------------------\n\nThe last step in setting up the Django admin is to hook your ``AdminSite``\ninstance into your URLconf. Do this by pointing a given URL at the\n``AdminSite.urls`` method. It is not necessary to use\n:func:`~django.urls.include()`.\n\nIn this example, we register the default ``AdminSite`` instance\n``django.contrib.admin.site`` at the URL ``/admin/`` ::\n\n    # urls.py\n    from django.contrib import admin\n    from django.urls import path\n\n    urlpatterns = [\n        path('admin/', admin.site.urls),\n    ]\n\n.. _customizing-adminsite:\n\nCustomizing the :class:`AdminSite` class\n----------------------------------------\n\nIf you'd like to set up your own admin site with custom behavior, you're free\nto subclass ``AdminSite`` and override or add anything you like. Then, create\nan instance of your ``AdminSite`` subclass (the same way you'd instantiate any\nother Python class) and register your models and ``ModelAdmin`` subclasses with\nit instead of with the default site. Finally, update :file:`myproject/urls.py`\nto reference your :class:`AdminSite` subclass.\n\n.. code-block:: python\n    :caption: myapp/admin.py\n\n    from django.contrib.admin import AdminSite\n\n    from .models import MyModel\n\n    class MyAdminSite(AdminSite):\n        site_header = 'Monty Python administration'\n\n    admin_site = MyAdminSite(name='myadmin')\n    admin_site.register(MyModel)\n\n\n.. code-block:: python\n    :caption: myproject/urls.py\n\n    from django.urls import path\n\n    from myapp.admin import admin_site\n\n    urlpatterns = [\n        path('myadmin/', admin_site.urls),\n    ]\n\nNote that you may not want autodiscovery of ``admin`` modules when using your\nown ``AdminSite`` instance since you will likely be importing all the per-app\n``admin`` modules in your ``myproject.admin`` module. This means you need to\nput ``'django.contrib.admin.apps.SimpleAdminConfig'`` instead of\n``'django.contrib.admin'`` in your :setting:`INSTALLED_APPS` setting.\n\n.. _overriding-default-admin-site:\n\nOverriding the default admin site\n---------------------------------\n\nYou can override the default ``django.contrib.admin.site`` by setting the\n:attr:`~.SimpleAdminConfig.default_site` attribute of a custom ``AppConfig``\nto the dotted import path of either a ``AdminSite`` subclass or a callable that\nreturns a site instance.\n\n.. code-block:: python\n    :caption: myproject/admin.py\n\n    from django.contrib import admin\n\n    class MyAdminSite(admin.AdminSite):\n        ...\n\n.. code-block:: python\n    :caption: myproject/apps.py\n\n    from django.contrib.admin.apps import AdminConfig\n\n    class MyAdminConfig(AdminConfig):\n        default_site = 'myproject.admin.MyAdminSite'\n\n.. code-block:: python\n    :caption: myproject/settings.py\n\n    INSTALLED_APPS = [\n        ...\n        'myproject.apps.MyAdminConfig',  # replaces 'django.contrib.admin'\n        ...\n    ]\n\n.. _multiple-admin-sites:\n\nMultiple admin sites in the same URLconf\n----------------------------------------\n\nYou can create multiple instances of the admin site on the same Django-powered\nwebsite. Create multiple instances of ``AdminSite`` and place each one at a\ndifferent URL.\n\nIn this example, the URLs ``/basic-admin/`` and ``/advanced-admin/`` feature\nseparate versions of the admin site -- using the ``AdminSite`` instances\n``myproject.admin.basic_site`` and ``myproject.admin.advanced_site``,\nrespectively::\n\n    # urls.py\n    from django.urls import path\n    from myproject.admin import advanced_site, basic_site\n\n    urlpatterns = [\n        path('basic-admin/', basic_site.urls),\n        path('advanced-admin/', advanced_site.urls),\n    ]\n\n``AdminSite`` instances take a single argument to their constructor, their\nname, which can be anything you like. This argument becomes the prefix to the\nURL names for the purposes of :ref:`reversing them<admin-reverse-urls>`. This\nis only necessary if you are using more than one ``AdminSite``.\n\nAdding views to admin sites\n---------------------------\n\nJust like :class:`ModelAdmin`, :class:`AdminSite` provides a\n:meth:`~django.contrib.admin.ModelAdmin.get_urls()` method\nthat can be overridden to define additional views for the site. To add\na new view to your admin site, extend the base\n:meth:`~django.contrib.admin.ModelAdmin.get_urls()` method to include\na pattern for your new view.\n\n.. note::\n\n    Any view you render that uses the admin templates, or extends the base\n    admin template, should set ``request.current_app`` before rendering the\n    template. It should be set to either ``self.name`` if your view is on an\n    ``AdminSite`` or ``self.admin_site.name`` if your view is on a\n    ``ModelAdmin``.\n\n.. _auth_password_reset:\n\nAdding a password reset feature\n-------------------------------\n\nYou can add a password reset feature to the admin site by adding a few lines to\nyour URLconf. Specifically, add these four patterns::\n\n    from django.contrib.auth import views as auth_views\n\n    path(\n        'admin/password_reset/',\n        auth_views.PasswordResetView.as_view(),\n        name='admin_password_reset',\n    ),\n    path(\n        'admin/password_reset/done/',\n        auth_views.PasswordResetDoneView.as_view(),\n        name='password_reset_done',\n    ),\n    path(\n        'reset/<uidb64>/<token>/',\n        auth_views.PasswordResetConfirmView.as_view(),\n        name='password_reset_confirm',\n    ),\n    path(\n        'reset/done/',\n        auth_views.PasswordResetCompleteView.as_view(),\n        name='password_reset_complete',\n    ),\n\n(This assumes you've added the admin at ``admin/`` and requires that you put\nthe URLs starting with ``^admin/`` before the line that includes the admin app\nitself).\n\nThe presence of the ``admin_password_reset`` named URL will cause a \"forgotten\nyour password?\" link to appear on the default admin log-in page under the\npassword box.\n\n``LogEntry`` objects\n====================\n\n.. class:: models.LogEntry\n\n    The ``LogEntry`` class tracks additions, changes, and deletions of objects\n    done through the admin interface.\n\n.. currentmodule:: django.contrib.admin.models\n\n``LogEntry`` attributes\n-----------------------\n\n.. attribute:: LogEntry.action_time\n\n    The date and time of the action.\n\n.. attribute:: LogEntry.user\n\n    The user (an :setting:`AUTH_USER_MODEL` instance) who performed the\n    action.\n\n.. attribute:: LogEntry.content_type\n\n    The :class:`~django.contrib.contenttypes.models.ContentType` of the\n    modified object.\n\n.. attribute:: LogEntry.object_id\n\n    The textual representation of the modified object's primary key.\n\n.. attribute:: LogEntry.object_repr\n\n    The object`s ``repr()`` after the modification.\n\n.. attribute:: LogEntry.action_flag\n\n    The type of action logged: ``ADDITION``, ``CHANGE``, ``DELETION``.\n\n    For example, to get a list of all additions done through the admin::\n\n        from django.contrib.admin.models import ADDITION, LogEntry\n\n        LogEntry.objects.filter(action_flag=ADDITION)\n\n.. attribute:: LogEntry.change_message\n\n    The detailed description of the modification. In the case of an edit, for\n    example, the message contains a list of the edited fields. The Django admin\n    site formats this content as a JSON structure, so that\n    :meth:`get_change_message` can recompose a message translated in the current\n    user language. Custom code might set this as a plain string though. You are\n    advised to use the :meth:`get_change_message` method to retrieve this value\n    instead of accessing it directly.\n\n``LogEntry`` methods\n--------------------\n\n.. method:: LogEntry.get_edited_object()\n\n    A shortcut that returns the referenced object.\n\n.. method:: LogEntry.get_change_message()\n\n    Formats and translates :attr:`change_message` into the current user\n    language. Messages created before Django 1.10 will always be displayed in\n    the language in which they were logged.\n\n.. currentmodule:: django.contrib.admin\n\n.. _admin-reverse-urls:\n\nReversing admin URLs\n====================\n\nWhen an :class:`AdminSite` is deployed, the views provided by that site are\naccessible using Django's :ref:`URL reversing system <naming-url-patterns>`.\n\nThe :class:`AdminSite` provides the following named URL patterns:\n\n=========================  ========================  ==================================\nPage                       URL name                  Parameters\n=========================  ========================  ==================================\nIndex                      ``index``\nLogin                      ``login``\nLogout                     ``logout``\nPassword change            ``password_change``\nPassword change done       ``password_change_done``\ni18n JavaScript            ``jsi18n``\nApplication index page     ``app_list``              ``app_label``\nRedirect to object's page  ``view_on_site``          ``content_type_id``, ``object_id``\n=========================  ========================  ==================================\n\nEach :class:`ModelAdmin` instance provides an additional set of named URLs:\n\n======================  ===============================================   =============\nPage                    URL name                                          Parameters\n======================  ===============================================   =============\nChangelist              ``{{ app_label }}_{{ model_name }}_changelist``\nAdd                     ``{{ app_label }}_{{ model_name }}_add``\nHistory                 ``{{ app_label }}_{{ model_name }}_history``      ``object_id``\nDelete                  ``{{ app_label }}_{{ model_name }}_delete``       ``object_id``\nChange                  ``{{ app_label }}_{{ model_name }}_change``       ``object_id``\n======================  ===============================================   =============\n\nThe ``UserAdmin`` provides a named URL:\n\n======================  ===============================================   =============\nPage                    URL name                                          Parameters\n======================  ===============================================   =============\nPassword change         ``auth_user_password_change``                     ``user_id``\n======================  ===============================================   =============\n\nThese named URLs are registered with the application namespace ``admin``, and\nwith an instance namespace corresponding to the name of the Site instance.\n\nSo - if you wanted to get a reference to the Change view for a particular\n``Choice`` object (from the polls application) in the default admin, you would\ncall::\n\n    >>> from django.urls import reverse\n    >>> c = Choice.objects.get(...)\n    >>> change_url = reverse('admin:polls_choice_change', args=(c.id,))\n\nThis will find the first registered instance of the admin application\n(whatever the instance name), and resolve to the view for changing\n``poll.Choice`` instances in that instance.\n\nIf you want to find a URL in a specific admin instance, provide the name of\nthat instance as a ``current_app`` hint to the reverse call. For example,\nif you specifically wanted the admin view from the admin instance named\n``custom``, you would need to call::\n\n    >>> change_url = reverse('admin:polls_choice_change', args=(c.id,), current_app='custom')\n\nFor more details, see the documentation on :ref:`reversing namespaced URLs\n<topics-http-reversing-url-namespaces>`.\n\nTo allow easier reversing of the admin urls in templates, Django provides an\n``admin_urlname`` filter which takes an action as argument:\n\n.. code-block:: html+django\n\n    {% load admin_urls %}\n    <a href=\"{% url opts|admin_urlname:'add' %}\">Add user</a>\n    <a href=\"{% url opts|admin_urlname:'delete' user.pk %}\">Delete this user</a>\n\nThe action in the examples above match the last part of the URL names for\n:class:`ModelAdmin` instances described above. The ``opts`` variable can be any\nobject which has an ``app_label`` and ``model_name`` attributes and is usually\nsupplied by the admin views for the current model.\n\n.. currentmodule:: django.contrib.admin.views.decorators\n\nThe ``staff_member_required`` decorator\n=======================================\n\n.. function:: staff_member_required(redirect_field_name='next', login_url='admin:login')\n\n    This decorator is used on the admin views that require authorization. A\n    view decorated with this function will having the following behavior:\n\n    * If the user is logged in, is a staff member (``User.is_staff=True``), and\n      is active (``User.is_active=True``), execute the view normally.\n\n    * Otherwise, the request will be redirected to the URL specified by the\n      ``login_url`` parameter, with the originally requested path in a query\n      string variable specified by ``redirect_field_name``. For example:\n      ``/admin/login/?next=/admin/polls/question/3/``.\n\n    Example usage::\n\n        from django.contrib.admin.views.decorators import staff_member_required\n\n        @staff_member_required\n        def my_view(request):\n            ...\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":161,"nodeType":"TextFile","repoName":null,"name":"flattened-index.txt","path":"docs/ref/class-based-views","text":"===========================================\nClass-based generic views - flattened index\n===========================================\n\nThis index provides an alternate organization of the reference documentation\nfor class-based views. For each view, the effective attributes and methods from\nthe class tree are represented under that view. For the reference\ndocumentation organized by the class which defines the behavior, see\n:doc:`Class-based views</ref/class-based-views/index>`.\n\n.. seealso::\n\n   `Classy Class-Based Views <https://ccbv.co.uk/>`_ provides a nice interface\n   to navigate the class hierarchy of the built-in class-based views.\n\nSimple generic views\n====================\n\n``View``\n--------\n\n.. class:: View()\n\n**Attributes** (with optional accessor):\n\n* :attr:`~django.views.generic.base.View.http_method_names`\n\n**Methods**\n\n* :meth:`~django.views.generic.base.View.as_view`\n* :meth:`~django.views.generic.base.View.dispatch`\n* ``head()``\n* :meth:`~django.views.generic.base.View.http_method_not_allowed`\n* :meth:`~django.views.generic.base.View.setup`\n\n``TemplateView``\n----------------\n\n.. class:: TemplateView()\n\n**Attributes** (with optional accessor):\n\n* :attr:`~django.views.generic.base.TemplateResponseMixin.content_type`\n* :attr:`~django.views.generic.base.ContextMixin.extra_context`\n* :attr:`~django.views.generic.base.View.http_method_names`\n* :attr:`~django.views.generic.base.TemplateResponseMixin.response_class` [:meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_engine`\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_name` [:meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names`]\n\n**Methods**\n\n* :meth:`~django.views.generic.base.View.as_view`\n* :meth:`~django.views.generic.base.View.dispatch`\n* ``get()``\n* :meth:`~django.views.generic.base.ContextMixin.get_context_data`\n* ``head()``\n* :meth:`~django.views.generic.base.View.http_method_not_allowed`\n* :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`\n* :meth:`~django.views.generic.base.View.setup`\n\n``RedirectView``\n----------------\n\n.. class:: RedirectView()\n\n**Attributes** (with optional accessor):\n\n* :attr:`~django.views.generic.base.View.http_method_names`\n* :attr:`~django.views.generic.base.RedirectView.pattern_name`\n* :attr:`~django.views.generic.base.RedirectView.permanent`\n* :attr:`~django.views.generic.base.RedirectView.query_string`\n* :attr:`~django.views.generic.base.RedirectView.url` [:meth:`~django.views.generic.base.RedirectView.get_redirect_url`]\n\n**Methods**\n\n* :meth:`~django.views.generic.base.View.as_view`\n* ``delete()``\n* :meth:`~django.views.generic.base.View.dispatch`\n* ``get()``\n* ``head()``\n* :meth:`~django.views.generic.base.View.http_method_not_allowed`\n* ``options()``\n* ``post()``\n* ``put()``\n* :meth:`~django.views.generic.base.View.setup`\n\nDetail Views\n============\n\n``DetailView``\n--------------\n\n.. class:: DetailView()\n\n**Attributes** (with optional accessor):\n\n* :attr:`~django.views.generic.base.TemplateResponseMixin.content_type`\n* :attr:`~django.views.generic.detail.SingleObjectMixin.context_object_name` [:meth:`~django.views.generic.detail.SingleObjectMixin.get_context_object_name`]\n* :attr:`~django.views.generic.base.ContextMixin.extra_context`\n* :attr:`~django.views.generic.base.View.http_method_names`\n* :attr:`~django.views.generic.detail.SingleObjectMixin.model`\n* :attr:`~django.views.generic.detail.SingleObjectMixin.pk_url_kwarg`\n* :attr:`~django.views.generic.detail.SingleObjectMixin.queryset` [:meth:`~django.views.generic.detail.SingleObjectMixin.get_queryset`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.response_class` [:meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`]\n* :attr:`~django.views.generic.detail.SingleObjectMixin.slug_field` [:meth:`~django.views.generic.detail.SingleObjectMixin.get_slug_field`]\n* :attr:`~django.views.generic.detail.SingleObjectMixin.slug_url_kwarg`\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_engine`\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_name` [:meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names`]\n* :attr:`~django.views.generic.detail.SingleObjectTemplateResponseMixin.template_name_field`\n* :attr:`~django.views.generic.detail.SingleObjectTemplateResponseMixin.template_name_suffix`\n\n**Methods**\n\n* :meth:`~django.views.generic.base.View.as_view`\n* :meth:`~django.views.generic.base.View.dispatch`\n* ``get()``\n* :meth:`~django.views.generic.detail.SingleObjectMixin.get_context_data`\n* :meth:`~django.views.generic.detail.SingleObjectMixin.get_object`\n* ``head()``\n* :meth:`~django.views.generic.base.View.http_method_not_allowed`\n* :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`\n* :meth:`~django.views.generic.base.View.setup`\n\nList Views\n==========\n\n``ListView``\n------------\n\n.. class:: ListView()\n\n**Attributes** (with optional accessor):\n\n* :attr:`~django.views.generic.list.MultipleObjectMixin.allow_empty` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_allow_empty`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.content_type`\n* :attr:`~django.views.generic.list.MultipleObjectMixin.context_object_name` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_context_object_name`]\n* :attr:`~django.views.generic.base.ContextMixin.extra_context`\n* :attr:`~django.views.generic.base.View.http_method_names`\n* :attr:`~django.views.generic.list.MultipleObjectMixin.model`\n* :attr:`~django.views.generic.list.MultipleObjectMixin.ordering` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_ordering`]\n* :attr:`~django.views.generic.list.MultipleObjectMixin.paginate_by` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_paginate_by`]\n* :attr:`~django.views.generic.list.MultipleObjectMixin.paginate_orphans` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_paginate_orphans`]\n* :attr:`~django.views.generic.list.MultipleObjectMixin.paginator_class`\n* :attr:`~django.views.generic.list.MultipleObjectMixin.queryset` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_queryset`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.response_class` [:meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_engine`\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_name` [:meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names`]\n* :attr:`~django.views.generic.list.MultipleObjectTemplateResponseMixin.template_name_suffix`\n\n**Methods**\n\n* :meth:`~django.views.generic.base.View.as_view`\n* :meth:`~django.views.generic.base.View.dispatch`\n* :meth:`~django.views.generic.list.BaseListView.get`\n* :meth:`~django.views.generic.list.MultipleObjectMixin.get_context_data`\n* :meth:`~django.views.generic.list.MultipleObjectMixin.get_paginator`\n* ``head()``\n* :meth:`~django.views.generic.base.View.http_method_not_allowed`\n* :meth:`~django.views.generic.list.MultipleObjectMixin.paginate_queryset`\n* :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`\n* :meth:`~django.views.generic.base.View.setup`\n\nEditing views\n=============\n\n``FormView``\n------------\n\n.. class:: FormView()\n\n**Attributes** (with optional accessor):\n\n* :attr:`~django.views.generic.base.TemplateResponseMixin.content_type`\n* :attr:`~django.views.generic.base.ContextMixin.extra_context`\n* :attr:`~django.views.generic.edit.FormMixin.form_class` [:meth:`~django.views.generic.edit.FormMixin.get_form_class`]\n* :attr:`~django.views.generic.base.View.http_method_names`\n* :attr:`~django.views.generic.edit.FormMixin.initial` [:meth:`~django.views.generic.edit.FormMixin.get_initial`]\n* :attr:`~django.views.generic.edit.FormMixin.prefix` [:meth:`~django.views.generic.edit.FormMixin.get_prefix`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.response_class` [:meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`]\n* :attr:`~django.views.generic.edit.FormMixin.success_url` [:meth:`~django.views.generic.edit.FormMixin.get_success_url`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_engine`\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_name` [:meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names`]\n\n**Methods**\n\n* :meth:`~django.views.generic.base.View.as_view`\n* :meth:`~django.views.generic.base.View.dispatch`\n* :meth:`~django.views.generic.edit.FormMixin.form_invalid`\n* :meth:`~django.views.generic.edit.FormMixin.form_valid`\n* :meth:`~django.views.generic.edit.ProcessFormView.get`\n* :meth:`~django.views.generic.edit.FormMixin.get_context_data`\n* :meth:`~django.views.generic.edit.FormMixin.get_form`\n* :meth:`~django.views.generic.edit.FormMixin.get_form_kwargs`\n* :meth:`~django.views.generic.base.View.http_method_not_allowed`\n* :meth:`~django.views.generic.edit.ProcessFormView.post`\n* :meth:`~django.views.generic.edit.ProcessFormView.put`\n* :meth:`~django.views.generic.base.View.setup`\n\n``CreateView``\n--------------\n\n.. class:: CreateView()\n\n**Attributes** (with optional accessor):\n\n* :attr:`~django.views.generic.base.TemplateResponseMixin.content_type`\n* :attr:`~django.views.generic.detail.SingleObjectMixin.context_object_name` [:meth:`~django.views.generic.detail.SingleObjectMixin.get_context_object_name`]\n* :attr:`~django.views.generic.base.ContextMixin.extra_context`\n* :attr:`~django.views.generic.edit.ModelFormMixin.fields`\n* :attr:`~django.views.generic.edit.FormMixin.form_class` [:meth:`~django.views.generic.edit.ModelFormMixin.get_form_class`]\n* :attr:`~django.views.generic.base.View.http_method_names`\n* :attr:`~django.views.generic.edit.FormMixin.initial` [:meth:`~django.views.generic.edit.FormMixin.get_initial`]\n* :attr:`~django.views.generic.detail.SingleObjectMixin.model`\n* :attr:`~django.views.generic.detail.SingleObjectMixin.pk_url_kwarg`\n* :attr:`~django.views.generic.edit.FormMixin.prefix` [:meth:`~django.views.generic.edit.FormMixin.get_prefix`]\n* :attr:`~django.views.generic.detail.SingleObjectMixin.queryset` [:meth:`~django.views.generic.detail.SingleObjectMixin.get_queryset`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.response_class` [:meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`]\n* :attr:`~django.views.generic.detail.SingleObjectMixin.slug_field` [:meth:`~django.views.generic.detail.SingleObjectMixin.get_slug_field`]\n* :attr:`~django.views.generic.detail.SingleObjectMixin.slug_url_kwarg`\n* :attr:`~django.views.generic.edit.FormMixin.success_url` [:meth:`~django.views.generic.edit.ModelFormMixin.get_success_url`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_engine`\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_name` [:meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names`]\n* :attr:`~django.views.generic.detail.SingleObjectTemplateResponseMixin.template_name_field`\n* :attr:`~django.views.generic.detail.SingleObjectTemplateResponseMixin.template_name_suffix`\n\n**Methods**\n\n* :meth:`~django.views.generic.base.View.as_view`\n* :meth:`~django.views.generic.base.View.dispatch`\n* :meth:`~django.views.generic.edit.FormMixin.form_invalid`\n* :meth:`~django.views.generic.edit.ModelFormMixin.form_valid`\n* :meth:`~django.views.generic.edit.ProcessFormView.get`\n* :meth:`~django.views.generic.edit.FormMixin.get_context_data`\n* :meth:`~django.views.generic.edit.FormMixin.get_form`\n* :meth:`~django.views.generic.edit.ModelFormMixin.get_form_kwargs`\n* :meth:`~django.views.generic.detail.SingleObjectMixin.get_object`\n* ``head()``\n* :meth:`~django.views.generic.base.View.http_method_not_allowed`\n* :meth:`~django.views.generic.edit.ProcessFormView.post`\n* ``put()``\n* :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`\n* :meth:`~django.views.generic.base.View.setup`\n\n``UpdateView``\n--------------\n\n.. class:: UpdateView()\n\n**Attributes** (with optional accessor):\n\n* :attr:`~django.views.generic.base.TemplateResponseMixin.content_type`\n* :attr:`~django.views.generic.detail.SingleObjectMixin.context_object_name` [:meth:`~django.views.generic.detail.SingleObjectMixin.get_context_object_name`]\n* :attr:`~django.views.generic.base.ContextMixin.extra_context`\n* :attr:`~django.views.generic.edit.ModelFormMixin.fields`\n* :attr:`~django.views.generic.edit.FormMixin.form_class` [:meth:`~django.views.generic.edit.ModelFormMixin.get_form_class`]\n* :attr:`~django.views.generic.base.View.http_method_names`\n* :attr:`~django.views.generic.edit.FormMixin.initial` [:meth:`~django.views.generic.edit.FormMixin.get_initial`]\n* :attr:`~django.views.generic.detail.SingleObjectMixin.model`\n* :attr:`~django.views.generic.detail.SingleObjectMixin.pk_url_kwarg`\n* :attr:`~django.views.generic.edit.FormMixin.prefix` [:meth:`~django.views.generic.edit.FormMixin.get_prefix`]\n* :attr:`~django.views.generic.detail.SingleObjectMixin.queryset` [:meth:`~django.views.generic.detail.SingleObjectMixin.get_queryset`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.response_class` [:meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`]\n* :attr:`~django.views.generic.detail.SingleObjectMixin.slug_field` [:meth:`~django.views.generic.detail.SingleObjectMixin.get_slug_field`]\n* :attr:`~django.views.generic.detail.SingleObjectMixin.slug_url_kwarg`\n* :attr:`~django.views.generic.edit.FormMixin.success_url` [:meth:`~django.views.generic.edit.ModelFormMixin.get_success_url`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_engine`\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_name` [:meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names`]\n* :attr:`~django.views.generic.detail.SingleObjectTemplateResponseMixin.template_name_field`\n* :attr:`~django.views.generic.detail.SingleObjectTemplateResponseMixin.template_name_suffix`\n\n**Methods**\n\n* :meth:`~django.views.generic.base.View.as_view`\n* :meth:`~django.views.generic.base.View.dispatch`\n* :meth:`~django.views.generic.edit.FormMixin.form_invalid`\n* :meth:`~django.views.generic.edit.ModelFormMixin.form_valid`\n* :meth:`~django.views.generic.edit.ProcessFormView.get`\n* :meth:`~django.views.generic.edit.FormMixin.get_context_data`\n* :meth:`~django.views.generic.edit.FormMixin.get_form`\n* :meth:`~django.views.generic.edit.ModelFormMixin.get_form_kwargs`\n* :meth:`~django.views.generic.detail.SingleObjectMixin.get_object`\n* ``head()``\n* :meth:`~django.views.generic.base.View.http_method_not_allowed`\n* :meth:`~django.views.generic.edit.ProcessFormView.post`\n* ``put()``\n* :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`\n* :meth:`~django.views.generic.base.View.setup`\n\n``DeleteView``\n--------------\n\n.. class:: DeleteView()\n\n**Attributes** (with optional accessor):\n\n* :attr:`~django.views.generic.base.TemplateResponseMixin.content_type`\n* :attr:`~django.views.generic.detail.SingleObjectMixin.context_object_name` [:meth:`~django.views.generic.detail.SingleObjectMixin.get_context_object_name`]\n* :attr:`~django.views.generic.base.ContextMixin.extra_context`\n* :attr:`~django.views.generic.base.View.http_method_names`\n* :attr:`~django.views.generic.detail.SingleObjectMixin.model`\n* :attr:`~django.views.generic.detail.SingleObjectMixin.pk_url_kwarg`\n* :attr:`~django.views.generic.detail.SingleObjectMixin.queryset` [:meth:`~django.views.generic.detail.SingleObjectMixin.get_queryset`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.response_class` [:meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`]\n* :attr:`~django.views.generic.detail.SingleObjectMixin.slug_field` [:meth:`~django.views.generic.detail.SingleObjectMixin.get_slug_field`]\n* :attr:`~django.views.generic.detail.SingleObjectMixin.slug_url_kwarg`\n* :attr:`~django.views.generic.edit.DeletionMixin.success_url` [:meth:`~django.views.generic.edit.DeletionMixin.get_success_url`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_engine`\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_name` [:meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names`]\n* :attr:`~django.views.generic.detail.SingleObjectTemplateResponseMixin.template_name_field`\n* :attr:`~django.views.generic.detail.SingleObjectTemplateResponseMixin.template_name_suffix`\n\n**Methods**\n\n* :meth:`~django.views.generic.base.View.as_view`\n* ``delete()``\n* :meth:`~django.views.generic.base.View.dispatch`\n* ``get()``\n* :meth:`~django.views.generic.detail.SingleObjectMixin.get_context_data`\n* :meth:`~django.views.generic.detail.SingleObjectMixin.get_object`\n* ``head()``\n* :meth:`~django.views.generic.base.View.http_method_not_allowed`\n* ``post()``\n* :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`\n* :meth:`~django.views.generic.base.View.setup`\n\nDate-based views\n================\n\n``ArchiveIndexView``\n--------------------\n\n.. class:: ArchiveIndexView()\n\n**Attributes** (with optional accessor):\n\n* :attr:`~django.views.generic.list.MultipleObjectMixin.allow_empty` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_allow_empty`]\n* :attr:`~django.views.generic.dates.DateMixin.allow_future` [:meth:`~django.views.generic.dates.DateMixin.get_allow_future`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.content_type`\n* :attr:`~django.views.generic.list.MultipleObjectMixin.context_object_name` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_context_object_name`]\n* :attr:`~django.views.generic.dates.DateMixin.date_field` [:meth:`~django.views.generic.dates.DateMixin.get_date_field`]\n* :attr:`~django.views.generic.base.ContextMixin.extra_context`\n* :attr:`~django.views.generic.base.View.http_method_names`\n* :attr:`~django.views.generic.list.MultipleObjectMixin.model`\n* :attr:`~django.views.generic.list.MultipleObjectMixin.ordering` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_ordering`]\n* :attr:`~django.views.generic.list.MultipleObjectMixin.paginate_by` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_paginate_by`]\n* :attr:`~django.views.generic.list.MultipleObjectMixin.paginate_orphans` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_paginate_orphans`]\n* :attr:`~django.views.generic.list.MultipleObjectMixin.paginator_class`\n* :attr:`~django.views.generic.list.MultipleObjectMixin.queryset` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_queryset`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.response_class` [:meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_engine`\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_name` [:meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names`]\n* :attr:`~django.views.generic.list.MultipleObjectTemplateResponseMixin.template_name_suffix`\n\n**Methods**\n\n* :meth:`~django.views.generic.base.View.as_view`\n* :meth:`~django.views.generic.base.View.dispatch`\n* ``get()``\n* :meth:`~django.views.generic.list.MultipleObjectMixin.get_context_data`\n* :meth:`~django.views.generic.dates.BaseDateListView.get_date_list`\n* :meth:`~django.views.generic.dates.BaseDateListView.get_dated_items`\n* :meth:`~django.views.generic.dates.BaseDateListView.get_dated_queryset`\n* :meth:`~django.views.generic.list.MultipleObjectMixin.get_paginator`\n* ``head()``\n* :meth:`~django.views.generic.base.View.http_method_not_allowed`\n* :meth:`~django.views.generic.list.MultipleObjectMixin.paginate_queryset`\n* :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`\n* :meth:`~django.views.generic.base.View.setup`\n\n``YearArchiveView``\n-------------------\n\n.. class:: YearArchiveView()\n\n**Attributes** (with optional accessor):\n\n* :attr:`~django.views.generic.list.MultipleObjectMixin.allow_empty` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_allow_empty`]\n* :attr:`~django.views.generic.dates.DateMixin.allow_future` [:meth:`~django.views.generic.dates.DateMixin.get_allow_future`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.content_type`\n* :attr:`~django.views.generic.list.MultipleObjectMixin.context_object_name` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_context_object_name`]\n* :attr:`~django.views.generic.dates.DateMixin.date_field` [:meth:`~django.views.generic.dates.DateMixin.get_date_field`]\n* :attr:`~django.views.generic.base.ContextMixin.extra_context`\n* :attr:`~django.views.generic.base.View.http_method_names`\n* :attr:`~django.views.generic.dates.YearArchiveView.make_object_list` [:meth:`~django.views.generic.dates.YearArchiveView.get_make_object_list`]\n* :attr:`~django.views.generic.list.MultipleObjectMixin.model`\n* :attr:`~django.views.generic.list.MultipleObjectMixin.ordering` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_ordering`]\n* :attr:`~django.views.generic.list.MultipleObjectMixin.paginate_by` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_paginate_by`]\n* :attr:`~django.views.generic.list.MultipleObjectMixin.paginate_orphans` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_paginate_orphans`]\n* :attr:`~django.views.generic.list.MultipleObjectMixin.paginator_class`\n* :attr:`~django.views.generic.list.MultipleObjectMixin.queryset` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_queryset`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.response_class` [:meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_engine`\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_name` [:meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names`]\n* :attr:`~django.views.generic.list.MultipleObjectTemplateResponseMixin.template_name_suffix`\n* :attr:`~django.views.generic.dates.YearMixin.year` [:meth:`~django.views.generic.dates.YearMixin.get_year`]\n* :attr:`~django.views.generic.dates.YearMixin.year_format` [:meth:`~django.views.generic.dates.YearMixin.get_year_format`]\n\n**Methods**\n\n* :meth:`~django.views.generic.base.View.as_view`\n* :meth:`~django.views.generic.base.View.dispatch`\n* ``get()``\n* :meth:`~django.views.generic.list.MultipleObjectMixin.get_context_data`\n* :meth:`~django.views.generic.dates.BaseDateListView.get_date_list`\n* :meth:`~django.views.generic.dates.BaseDateListView.get_dated_items`\n* :meth:`~django.views.generic.dates.BaseDateListView.get_dated_queryset`\n* :meth:`~django.views.generic.list.MultipleObjectMixin.get_paginator`\n* ``head()``\n* :meth:`~django.views.generic.base.View.http_method_not_allowed`\n* :meth:`~django.views.generic.list.MultipleObjectMixin.paginate_queryset`\n* :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`\n* :meth:`~django.views.generic.base.View.setup`\n\n``MonthArchiveView``\n--------------------\n\n.. class:: MonthArchiveView()\n\n**Attributes** (with optional accessor):\n\n* :attr:`~django.views.generic.list.MultipleObjectMixin.allow_empty` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_allow_empty`]\n* :attr:`~django.views.generic.dates.DateMixin.allow_future` [:meth:`~django.views.generic.dates.DateMixin.get_allow_future`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.content_type`\n* :attr:`~django.views.generic.list.MultipleObjectMixin.context_object_name` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_context_object_name`]\n* :attr:`~django.views.generic.dates.DateMixin.date_field` [:meth:`~django.views.generic.dates.DateMixin.get_date_field`]\n* :attr:`~django.views.generic.base.ContextMixin.extra_context`\n* :attr:`~django.views.generic.base.View.http_method_names`\n* :attr:`~django.views.generic.list.MultipleObjectMixin.model`\n* :attr:`~django.views.generic.dates.MonthMixin.month` [:meth:`~django.views.generic.dates.MonthMixin.get_month`]\n* :attr:`~django.views.generic.dates.MonthMixin.month_format` [:meth:`~django.views.generic.dates.MonthMixin.get_month_format`]\n* :attr:`~django.views.generic.list.MultipleObjectMixin.ordering` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_ordering`]\n* :attr:`~django.views.generic.list.MultipleObjectMixin.paginate_by` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_paginate_by`]\n* :attr:`~django.views.generic.list.MultipleObjectMixin.paginate_orphans` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_paginate_orphans`]\n* :attr:`~django.views.generic.list.MultipleObjectMixin.paginator_class`\n* :attr:`~django.views.generic.list.MultipleObjectMixin.queryset` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_queryset`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.response_class` [:meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_engine`\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_name` [:meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names`]\n* :attr:`~django.views.generic.list.MultipleObjectTemplateResponseMixin.template_name_suffix`\n* :attr:`~django.views.generic.dates.YearMixin.year` [:meth:`~django.views.generic.dates.YearMixin.get_year`]\n* :attr:`~django.views.generic.dates.YearMixin.year_format` [:meth:`~django.views.generic.dates.YearMixin.get_year_format`]\n\n**Methods**\n\n* :meth:`~django.views.generic.base.View.as_view`\n* :meth:`~django.views.generic.base.View.dispatch`\n* ``get()``\n* :meth:`~django.views.generic.list.MultipleObjectMixin.get_context_data`\n* :meth:`~django.views.generic.dates.BaseDateListView.get_date_list`\n* :meth:`~django.views.generic.dates.BaseDateListView.get_dated_items`\n* :meth:`~django.views.generic.dates.BaseDateListView.get_dated_queryset`\n* :meth:`~django.views.generic.dates.MonthMixin.get_next_month`\n* :meth:`~django.views.generic.list.MultipleObjectMixin.get_paginator`\n* :meth:`~django.views.generic.dates.MonthMixin.get_previous_month`\n* ``head()``\n* :meth:`~django.views.generic.base.View.http_method_not_allowed`\n* :meth:`~django.views.generic.list.MultipleObjectMixin.paginate_queryset`\n* :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`\n* :meth:`~django.views.generic.base.View.setup`\n\n``WeekArchiveView``\n-------------------\n\n.. class:: WeekArchiveView()\n\n**Attributes** (with optional accessor):\n\n* :attr:`~django.views.generic.list.MultipleObjectMixin.allow_empty` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_allow_empty`]\n* :attr:`~django.views.generic.dates.DateMixin.allow_future` [:meth:`~django.views.generic.dates.DateMixin.get_allow_future`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.content_type`\n* :attr:`~django.views.generic.list.MultipleObjectMixin.context_object_name` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_context_object_name`]\n* :attr:`~django.views.generic.dates.DateMixin.date_field` [:meth:`~django.views.generic.dates.DateMixin.get_date_field`]\n* :attr:`~django.views.generic.base.ContextMixin.extra_context`\n* :attr:`~django.views.generic.base.View.http_method_names`\n* :attr:`~django.views.generic.list.MultipleObjectMixin.model`\n* :attr:`~django.views.generic.list.MultipleObjectMixin.ordering` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_ordering`]\n* :attr:`~django.views.generic.list.MultipleObjectMixin.paginate_by` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_paginate_by`]\n* :attr:`~django.views.generic.list.MultipleObjectMixin.paginate_orphans` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_paginate_orphans`]\n* :attr:`~django.views.generic.list.MultipleObjectMixin.paginator_class`\n* :attr:`~django.views.generic.list.MultipleObjectMixin.queryset` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_queryset`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.response_class` [:meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_engine`\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_name` [:meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names`]\n* :attr:`~django.views.generic.list.MultipleObjectTemplateResponseMixin.template_name_suffix`\n* :attr:`~django.views.generic.dates.WeekMixin.week` [:meth:`~django.views.generic.dates.WeekMixin.get_week`]\n* :attr:`~django.views.generic.dates.WeekMixin.week_format` [:meth:`~django.views.generic.dates.WeekMixin.get_week_format`]\n* :attr:`~django.views.generic.dates.YearMixin.year` [:meth:`~django.views.generic.dates.YearMixin.get_year`]\n* :attr:`~django.views.generic.dates.YearMixin.year_format` [:meth:`~django.views.generic.dates.YearMixin.get_year_format`]\n\n**Methods**\n\n* :meth:`~django.views.generic.base.View.as_view`\n* :meth:`~django.views.generic.base.View.dispatch`\n* ``get()``\n* :meth:`~django.views.generic.list.MultipleObjectMixin.get_context_data`\n* :meth:`~django.views.generic.dates.BaseDateListView.get_date_list`\n* :meth:`~django.views.generic.dates.BaseDateListView.get_dated_items`\n* :meth:`~django.views.generic.dates.BaseDateListView.get_dated_queryset`\n* :meth:`~django.views.generic.list.MultipleObjectMixin.get_paginator`\n* ``head()``\n* :meth:`~django.views.generic.base.View.http_method_not_allowed`\n* :meth:`~django.views.generic.list.MultipleObjectMixin.paginate_queryset`\n* :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`\n* :meth:`~django.views.generic.base.View.setup`\n\n``DayArchiveView``\n------------------\n\n.. class:: DayArchiveView()\n\n**Attributes** (with optional accessor):\n\n* :attr:`~django.views.generic.list.MultipleObjectMixin.allow_empty` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_allow_empty`]\n* :attr:`~django.views.generic.dates.DateMixin.allow_future` [:meth:`~django.views.generic.dates.DateMixin.get_allow_future`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.content_type`\n* :attr:`~django.views.generic.list.MultipleObjectMixin.context_object_name` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_context_object_name`]\n* :attr:`~django.views.generic.dates.DateMixin.date_field` [:meth:`~django.views.generic.dates.DateMixin.get_date_field`]\n* :attr:`~django.views.generic.dates.DayMixin.day` [:meth:`~django.views.generic.dates.DayMixin.get_day`]\n* :attr:`~django.views.generic.dates.DayMixin.day_format` [:meth:`~django.views.generic.dates.DayMixin.get_day_format`]\n* :attr:`~django.views.generic.base.ContextMixin.extra_context`\n* :attr:`~django.views.generic.base.View.http_method_names`\n* :attr:`~django.views.generic.list.MultipleObjectMixin.model`\n* :attr:`~django.views.generic.dates.MonthMixin.month` [:meth:`~django.views.generic.dates.MonthMixin.get_month`]\n* :attr:`~django.views.generic.dates.MonthMixin.month_format` [:meth:`~django.views.generic.dates.MonthMixin.get_month_format`]\n* :attr:`~django.views.generic.list.MultipleObjectMixin.ordering` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_ordering`]\n* :attr:`~django.views.generic.list.MultipleObjectMixin.paginate_by` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_paginate_by`]\n* :attr:`~django.views.generic.list.MultipleObjectMixin.paginate_orphans` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_paginate_orphans`]\n* :attr:`~django.views.generic.list.MultipleObjectMixin.paginator_class`\n* :attr:`~django.views.generic.list.MultipleObjectMixin.queryset` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_queryset`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.response_class` [:meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_engine`\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_name` [:meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names`]\n* :attr:`~django.views.generic.list.MultipleObjectTemplateResponseMixin.template_name_suffix`\n* :attr:`~django.views.generic.dates.YearMixin.year` [:meth:`~django.views.generic.dates.YearMixin.get_year`]\n* :attr:`~django.views.generic.dates.YearMixin.year_format` [:meth:`~django.views.generic.dates.YearMixin.get_year_format`]\n\n**Methods**\n\n* :meth:`~django.views.generic.base.View.as_view`\n* :meth:`~django.views.generic.base.View.dispatch`\n* ``get()``\n* :meth:`~django.views.generic.list.MultipleObjectMixin.get_context_data`\n* :meth:`~django.views.generic.dates.BaseDateListView.get_date_list`\n* :meth:`~django.views.generic.dates.BaseDateListView.get_dated_items`\n* :meth:`~django.views.generic.dates.BaseDateListView.get_dated_queryset`\n* :meth:`~django.views.generic.dates.DayMixin.get_next_day`\n* :meth:`~django.views.generic.dates.MonthMixin.get_next_month`\n* :meth:`~django.views.generic.list.MultipleObjectMixin.get_paginator`\n* :meth:`~django.views.generic.dates.DayMixin.get_previous_day`\n* :meth:`~django.views.generic.dates.MonthMixin.get_previous_month`\n* ``head()``\n* :meth:`~django.views.generic.base.View.http_method_not_allowed`\n* :meth:`~django.views.generic.list.MultipleObjectMixin.paginate_queryset`\n* :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`\n* :meth:`~django.views.generic.base.View.setup`\n\n``TodayArchiveView``\n--------------------\n\n.. class:: TodayArchiveView()\n\n**Attributes** (with optional accessor):\n\n* :attr:`~django.views.generic.list.MultipleObjectMixin.allow_empty` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_allow_empty`]\n* :attr:`~django.views.generic.dates.DateMixin.allow_future` [:meth:`~django.views.generic.dates.DateMixin.get_allow_future`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.content_type`\n* :attr:`~django.views.generic.list.MultipleObjectMixin.context_object_name` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_context_object_name`]\n* :attr:`~django.views.generic.dates.DateMixin.date_field` [:meth:`~django.views.generic.dates.DateMixin.get_date_field`]\n* :attr:`~django.views.generic.dates.DayMixin.day` [:meth:`~django.views.generic.dates.DayMixin.get_day`]\n* :attr:`~django.views.generic.dates.DayMixin.day_format` [:meth:`~django.views.generic.dates.DayMixin.get_day_format`]\n* :attr:`~django.views.generic.base.ContextMixin.extra_context`\n* :attr:`~django.views.generic.base.View.http_method_names`\n* :attr:`~django.views.generic.list.MultipleObjectMixin.model`\n* :attr:`~django.views.generic.dates.MonthMixin.month` [:meth:`~django.views.generic.dates.MonthMixin.get_month`]\n* :attr:`~django.views.generic.dates.MonthMixin.month_format` [:meth:`~django.views.generic.dates.MonthMixin.get_month_format`]\n* :attr:`~django.views.generic.list.MultipleObjectMixin.ordering` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_ordering`]\n* :attr:`~django.views.generic.list.MultipleObjectMixin.paginate_by` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_paginate_by`]\n* :attr:`~django.views.generic.list.MultipleObjectMixin.paginate_orphans` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_paginate_orphans`]\n* :attr:`~django.views.generic.list.MultipleObjectMixin.paginator_class`\n* :attr:`~django.views.generic.list.MultipleObjectMixin.queryset` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_queryset`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.response_class` [:meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_engine`\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_name` [:meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names`]\n* :attr:`~django.views.generic.list.MultipleObjectTemplateResponseMixin.template_name_suffix`\n* :attr:`~django.views.generic.dates.YearMixin.year` [:meth:`~django.views.generic.dates.YearMixin.get_year`]\n* :attr:`~django.views.generic.dates.YearMixin.year_format` [:meth:`~django.views.generic.dates.YearMixin.get_year_format`]\n\n**Methods**\n\n* :meth:`~django.views.generic.base.View.as_view`\n* :meth:`~django.views.generic.base.View.dispatch`\n* ``get()``\n* :meth:`~django.views.generic.list.MultipleObjectMixin.get_context_data`\n* :meth:`~django.views.generic.dates.BaseDateListView.get_date_list`\n* :meth:`~django.views.generic.dates.BaseDateListView.get_dated_items`\n* :meth:`~django.views.generic.dates.BaseDateListView.get_dated_queryset`\n* :meth:`~django.views.generic.dates.DayMixin.get_next_day`\n* :meth:`~django.views.generic.dates.MonthMixin.get_next_month`\n* :meth:`~django.views.generic.list.MultipleObjectMixin.get_paginator`\n* :meth:`~django.views.generic.dates.DayMixin.get_previous_day`\n* :meth:`~django.views.generic.dates.MonthMixin.get_previous_month`\n* ``head()``\n* :meth:`~django.views.generic.base.View.http_method_not_allowed`\n* :meth:`~django.views.generic.list.MultipleObjectMixin.paginate_queryset`\n* :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`\n* :meth:`~django.views.generic.base.View.setup`\n\n``DateDetailView``\n------------------\n\n.. class:: DateDetailView()\n\n**Attributes** (with optional accessor):\n\n* :attr:`~django.views.generic.dates.DateMixin.allow_future` [:meth:`~django.views.generic.dates.DateMixin.get_allow_future`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.content_type`\n* :attr:`~django.views.generic.detail.SingleObjectMixin.context_object_name` [:meth:`~django.views.generic.detail.SingleObjectMixin.get_context_object_name`]\n* :attr:`~django.views.generic.dates.DateMixin.date_field` [:meth:`~django.views.generic.dates.DateMixin.get_date_field`]\n* :attr:`~django.views.generic.dates.DayMixin.day` [:meth:`~django.views.generic.dates.DayMixin.get_day`]\n* :attr:`~django.views.generic.dates.DayMixin.day_format` [:meth:`~django.views.generic.dates.DayMixin.get_day_format`]\n* :attr:`~django.views.generic.base.ContextMixin.extra_context`\n* :attr:`~django.views.generic.base.View.http_method_names`\n* :attr:`~django.views.generic.detail.SingleObjectMixin.model`\n* :attr:`~django.views.generic.dates.MonthMixin.month` [:meth:`~django.views.generic.dates.MonthMixin.get_month`]\n* :attr:`~django.views.generic.dates.MonthMixin.month_format` [:meth:`~django.views.generic.dates.MonthMixin.get_month_format`]\n* :attr:`~django.views.generic.detail.SingleObjectMixin.pk_url_kwarg`\n* :attr:`~django.views.generic.detail.SingleObjectMixin.queryset` [:meth:`~django.views.generic.detail.SingleObjectMixin.get_queryset`]\n* :attr:`~django.views.generic.base.TemplateResponseMixin.response_class` [:meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`]\n* :attr:`~django.views.generic.detail.SingleObjectMixin.slug_field` [:meth:`~django.views.generic.detail.SingleObjectMixin.get_slug_field`]\n* :attr:`~django.views.generic.detail.SingleObjectMixin.slug_url_kwarg`\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_engine`\n* :attr:`~django.views.generic.base.TemplateResponseMixin.template_name` [:meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names`]\n* :attr:`~django.views.generic.detail.SingleObjectTemplateResponseMixin.template_name_field`\n* :attr:`~django.views.generic.detail.SingleObjectTemplateResponseMixin.template_name_suffix`\n* :attr:`~django.views.generic.dates.YearMixin.year` [:meth:`~django.views.generic.dates.YearMixin.get_year`]\n* :attr:`~django.views.generic.dates.YearMixin.year_format` [:meth:`~django.views.generic.dates.YearMixin.get_year_format`]\n\n**Methods**\n\n* :meth:`~django.views.generic.base.View.as_view`\n* :meth:`~django.views.generic.base.View.dispatch`\n* ``get()``\n* :meth:`~django.views.generic.detail.SingleObjectMixin.get_context_data`\n* :meth:`~django.views.generic.dates.DayMixin.get_next_day`\n* :meth:`~django.views.generic.dates.MonthMixin.get_next_month`\n* :meth:`~django.views.generic.detail.SingleObjectMixin.get_object`\n* :meth:`~django.views.generic.dates.DayMixin.get_previous_day`\n* :meth:`~django.views.generic.dates.MonthMixin.get_previous_month`\n* ``head()``\n* :meth:`~django.views.generic.base.View.http_method_not_allowed`\n* :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`\n* :meth:`~django.views.generic.base.View.setup`\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":162,"nodeType":"TextFile","repoName":null,"name":"mixins-date-based.txt","path":"docs/ref/class-based-views","text":"=================\nDate-based mixins\n=================\n\n.. currentmodule:: django.views.generic.dates\n\n.. note::\n\n    All the date formatting attributes in these mixins use\n    :func:`~time.strftime` format characters. Do not try to use the format\n    characters from the :ttag:`now` template tag as they are not compatible.\n\n``YearMixin``\n=============\n\n.. class:: YearMixin\n\n    A mixin that can be used to retrieve and provide parsing information for a\n    year component of a date.\n\n    **Methods and Attributes**\n\n    .. attribute:: year_format\n\n        The :func:`~time.strftime` format to use when parsing the year.\n        By default, this is ``'%Y'``.\n\n    .. attribute:: year\n\n        **Optional** The value for the year, as a string. By default, set to\n        ``None``, which means the year will be determined using other means.\n\n    .. method:: get_year_format()\n\n        Returns the :func:`~time.strftime` format to use when parsing the\n        year. Returns :attr:`~YearMixin.year_format` by default.\n\n    .. method:: get_year()\n\n        Returns the year for which this view will display data, as a string.\n        Tries the following sources, in order:\n\n        * The value of the :attr:`YearMixin.year` attribute.\n        * The value of the ``year`` argument captured in the URL pattern.\n        * The value of the ``year`` ``GET`` query argument.\n\n        Raises a 404 if no valid year specification can be found.\n\n    .. method:: get_next_year(date)\n\n        Returns a date object containing the first day of the year after the\n        date provided. This function can also return ``None`` or raise an\n        :class:`~django.http.Http404` exception, depending on the values of\n        :attr:`~BaseDateListView.allow_empty` and\n        :attr:`~DateMixin.allow_future`.\n\n    .. method:: get_previous_year(date)\n\n        Returns a date object containing the first day of the year before the\n        date provided. This function can also return ``None`` or raise an\n        :class:`~django.http.Http404` exception, depending on the values of\n        :attr:`~BaseDateListView.allow_empty` and\n        :attr:`~DateMixin.allow_future`.\n\n``MonthMixin``\n==============\n\n.. class:: MonthMixin\n\n    A mixin that can be used to retrieve and provide parsing information for a\n    month component of a date.\n\n    **Methods and Attributes**\n\n    .. attribute:: month_format\n\n        The :func:`~time.strftime` format to use when parsing the month. By\n        default, this is ``'%b'``.\n\n    .. attribute:: month\n\n        **Optional** The value for the month, as a string. By default, set to\n        ``None``, which means the month will be determined using other means.\n\n    .. method:: get_month_format()\n\n        Returns the :func:`~time.strftime` format to use when parsing the\n        month. Returns :attr:`~MonthMixin.month_format` by default.\n\n    .. method:: get_month()\n\n        Returns the month for which this view will display data, as a string.\n        Tries the following sources, in order:\n\n        * The value of the :attr:`MonthMixin.month` attribute.\n        * The value of the ``month`` argument captured in the URL pattern.\n        * The value of the ``month`` ``GET`` query argument.\n\n        Raises a 404 if no valid month specification can be found.\n\n    .. method:: get_next_month(date)\n\n        Returns a date object containing the first day of the month after the\n        date provided. This function can also return ``None`` or raise an\n        :class:`~django.http.Http404` exception, depending on the values of\n        :attr:`~BaseDateListView.allow_empty` and\n        :attr:`~DateMixin.allow_future`.\n\n    .. method:: get_previous_month(date)\n\n        Returns a date object containing the first day of the month before the\n        date provided. This function can also return ``None`` or raise an\n        :class:`~django.http.Http404` exception, depending on the values of\n        :attr:`~BaseDateListView.allow_empty` and\n        :attr:`~DateMixin.allow_future`.\n\n``DayMixin``\n============\n\n.. class:: DayMixin\n\n    A mixin that can be used to retrieve and provide parsing information for a\n    day component of a date.\n\n    **Methods and Attributes**\n\n    .. attribute:: day_format\n\n        The :func:`~time.strftime` format to use when parsing the day. By\n        default, this is ``'%d'``.\n\n    .. attribute:: day\n\n        **Optional** The value for the day, as a string. By default, set to\n        ``None``, which means the day will be determined using other means.\n\n    .. method:: get_day_format()\n\n        Returns the :func:`~time.strftime` format to use when parsing the day.\n        Returns :attr:`~DayMixin.day_format` by default.\n\n    .. method:: get_day()\n\n        Returns the day for which this view will display data, as a string.\n        Tries the following sources, in order:\n\n        * The value of the :attr:`DayMixin.day` attribute.\n        * The value of the ``day`` argument captured in the URL pattern.\n        * The value of the ``day`` ``GET`` query argument.\n\n        Raises a 404 if no valid day specification can be found.\n\n    .. method:: get_next_day(date)\n\n        Returns a date object containing the next valid day after the date\n        provided. This function can also return ``None`` or raise an\n        :class:`~django.http.Http404` exception, depending on the values of\n        :attr:`~BaseDateListView.allow_empty` and\n        :attr:`~DateMixin.allow_future`.\n\n    .. method:: get_previous_day(date)\n\n        Returns a date object containing the previous valid day. This function\n        can also return ``None`` or raise an :class:`~django.http.Http404`\n        exception, depending on the values of\n        :attr:`~BaseDateListView.allow_empty` and\n        :attr:`~DateMixin.allow_future`.\n\n``WeekMixin``\n=============\n\n.. class:: WeekMixin\n\n    A mixin that can be used to retrieve and provide parsing information for a\n    week component of a date.\n\n    **Methods and Attributes**\n\n    .. attribute:: week_format\n\n        The :func:`~time.strftime` format to use when parsing the week. By\n        default, this is ``'%U'``, which means the week starts on Sunday. Set\n        it to ``'%W'`` if your week starts on Monday.\n\n    .. attribute:: week\n\n        **Optional** The value for the week, as a string. By default, set to\n        ``None``, which means the week will be determined using other means.\n\n    .. method:: get_week_format()\n\n        Returns the :func:`~time.strftime` format to use when parsing the\n        week. Returns :attr:`~WeekMixin.week_format` by default.\n\n    .. method:: get_week()\n\n        Returns the week for which this view will display data, as a string.\n        Tries the following sources, in order:\n\n        * The value of the :attr:`WeekMixin.week` attribute.\n        * The value of the ``week`` argument captured in the URL pattern\n        * The value of the ``week`` ``GET`` query argument.\n\n        Raises a 404 if no valid week specification can be found.\n\n    .. method:: get_next_week(date)\n\n        Returns a date object containing the first day of the week after the\n        date provided. This function can also return ``None`` or raise an\n        :class:`~django.http.Http404` exception, depending on the values of\n        :attr:`~BaseDateListView.allow_empty` and\n        :attr:`~DateMixin.allow_future`.\n\n    .. method:: get_prev_week(date)\n\n        Returns a date object containing the first day of the week before the\n        date provided. This function can also return ``None`` or raise an\n        :class:`~django.http.Http404` exception, depending on the values of\n        :attr:`~BaseDateListView.allow_empty` and\n        :attr:`~DateMixin.allow_future`.\n\n``DateMixin``\n=============\n\n.. class:: DateMixin\n\n    A mixin class providing common behavior for all date-based views.\n\n    **Methods and Attributes**\n\n    .. attribute:: date_field\n\n        The name of the ``DateField`` or ``DateTimeField`` in the\n        ``QuerySet``’s model that the date-based archive should use to\n        determine the list of objects to display on the page.\n\n        When :doc:`time zone support </topics/i18n/timezones>` is enabled and\n        ``date_field`` is a ``DateTimeField``, dates are assumed to be in the\n        current time zone. Otherwise, the queryset could include objects from\n        the previous or the next day in the end user's time zone.\n\n        .. warning::\n\n            In this situation, if you have implemented per-user time zone\n            selection, the same URL may show a different set of objects,\n            depending on the end user's time zone. To avoid this, you should\n            use a ``DateField`` as the ``date_field`` attribute.\n\n    .. attribute:: allow_future\n\n        A boolean specifying whether to include \"future\" objects on this page,\n        where \"future\" means objects in which the field specified in\n        ``date_field`` is greater than the current date/time. By default, this\n        is ``False``.\n\n    .. method:: get_date_field()\n\n        Returns the name of the field that contains the date data that this\n        view will operate on. Returns :attr:`~DateMixin.date_field` by default.\n\n    .. method:: get_allow_future()\n\n        Determine whether to include \"future\" objects on this page, where\n        \"future\" means objects in which the field specified in ``date_field``\n        is greater than the current date/time. Returns\n        :attr:`~DateMixin.allow_future` by default.\n\n``BaseDateListView``\n====================\n\n.. class:: BaseDateListView\n\n    A base class that provides common behavior for all date-based views. There\n    won't normally be a reason to instantiate\n    :class:`~django.views.generic.dates.BaseDateListView`; instantiate one of\n    the subclasses instead.\n\n    While this view (and its subclasses) are executing, ``self.object_list``\n    will contain the list of objects that the view is operating upon, and\n    ``self.date_list`` will contain the list of dates for which data is\n    available.\n\n    **Mixins**\n\n    * :class:`~django.views.generic.dates.DateMixin`\n    * :class:`~django.views.generic.list.MultipleObjectMixin`\n\n    **Methods and Attributes**\n\n    .. attribute:: allow_empty\n\n        A boolean specifying whether to display the page if no objects are\n        available. If this is ``True`` and no objects are available, the view\n        will display an empty page instead of raising a 404.\n\n        This is identical to\n        :attr:`django.views.generic.list.MultipleObjectMixin.allow_empty`,\n        except for the default value, which is ``False``.\n\n    .. attribute:: date_list_period\n\n        **Optional** A string defining the aggregation period for\n        ``date_list``. It must be one of ``'year'`` (default), ``'month'``, or\n        ``'day'``.\n\n    .. method:: get_dated_items()\n\n        Returns a 3-tuple containing (``date_list``, ``object_list``,\n        ``extra_context``).\n\n        ``date_list`` is the list of dates for which data is available.\n        ``object_list`` is the list of objects. ``extra_context`` is a\n        dictionary of context data that will be added to any context data\n        provided by the\n        :class:`~django.views.generic.list.MultipleObjectMixin`.\n\n    .. method:: get_dated_queryset(**lookup)\n\n        Returns a queryset, filtered using the query arguments defined by\n        ``lookup``. Enforces any restrictions on the queryset, such as\n        ``allow_empty`` and ``allow_future``.\n\n    .. method:: get_date_list_period()\n\n        Returns the aggregation period for ``date_list``. Returns\n        :attr:`~BaseDateListView.date_list_period` by default.\n\n    .. method:: get_date_list(queryset, date_type=None, ordering='ASC')\n\n        Returns the list of dates of type ``date_type`` for which ``queryset``\n        contains entries. For example, ``get_date_list(qs, 'year')`` will\n        return the list of years for which ``qs`` has entries. If\n        ``date_type`` isn't provided, the result of\n        :meth:`~BaseDateListView.get_date_list_period` is used. ``date_type``\n        and ``ordering`` are passed to\n        :meth:`QuerySet.dates()<django.db.models.query.QuerySet.dates>`.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":163,"nodeType":"TextFile","repoName":null,"name":"mixins-multiple-object.txt","path":"docs/ref/class-based-views","text":"======================\nMultiple object mixins\n======================\n\n``MultipleObjectMixin``\n=======================\n\n.. class:: django.views.generic.list.MultipleObjectMixin\n\n    A mixin that can be used to display a list of objects.\n\n    If ``paginate_by`` is specified, Django will paginate the results returned\n    by this. You can specify the page number in the URL in one of two ways:\n\n    * Use the ``page`` parameter in the URLconf. For example, this is what\n      your URLconf might look like::\n\n        path('objects/page<int:page>/', PaginatedView.as_view()),\n\n    * Pass the page number via the ``page`` query-string parameter. For\n      example, a URL would look like this::\n\n        /objects/?page=3\n\n    These values and lists are 1-based, not 0-based, so the first page would be\n    represented as page ``1``.\n\n    For more on pagination, read the :doc:`pagination documentation\n    </topics/pagination>`.\n\n    As a special case, you are also permitted to use ``last`` as a value for\n    ``page``::\n\n        /objects/?page=last\n\n    This allows you to access the final page of results without first having to\n    determine how many pages there are.\n\n    Note that ``page`` *must* be either a valid page number or the value\n    ``last``; any other value for ``page`` will result in a 404 error.\n\n    **Extends**\n\n    * :class:`django.views.generic.base.ContextMixin`\n\n    **Methods and Attributes**\n\n    .. attribute:: allow_empty\n\n        A boolean specifying whether to display the page if no objects are\n        available. If this is ``False`` and no objects are available, the view\n        will raise a 404 instead of displaying an empty page. By default, this\n        is ``True``.\n\n    .. attribute:: model\n\n        The model that this view will display data for. Specifying ``model\n        = Foo`` is effectively the same as specifying ``queryset =\n        Foo.objects.all()``, where ``objects`` stands for ``Foo``’s\n        :ref:`default manager <default-managers>`.\n\n    .. attribute:: queryset\n\n        A ``QuerySet`` that represents the objects. If provided, the value of\n        ``queryset`` supersedes the value provided for :attr:`model`.\n\n        .. warning::\n\n            ``queryset`` is a class attribute with a *mutable* value so care\n            must be taken when using it directly. Before using it, either call\n            its :meth:`~django.db.models.query.QuerySet.all` method or\n            retrieve it with :meth:`get_queryset` which takes care of the\n            cloning behind the scenes.\n\n    .. attribute:: ordering\n\n        A string or list of strings specifying the ordering to apply to the ``queryset``.\n        Valid values are the same as those for :meth:`~django.db.models.query.QuerySet.order_by`.\n\n    .. attribute:: paginate_by\n\n        An integer specifying how many objects should be displayed per page. If\n        this is given, the view will paginate objects with\n        ``paginate_by`` objects per page. The view will\n        expect either a ``page`` query string parameter (via ``request.GET``)\n        or a ``page`` variable specified in the URLconf.\n\n    .. attribute:: paginate_orphans\n\n        An integer specifying the number of \"overflow\" objects the last page\n        can contain. This extends the :attr:`paginate_by` limit on the last\n        page by up to ``paginate_orphans``, in order to keep the last page from\n        having a very small number of objects.\n\n    .. attribute:: page_kwarg\n\n        A string specifying the name to use for the page parameter.\n        The view will expect this parameter to be available either as a query\n        string parameter (via ``request.GET``) or as a kwarg variable specified\n        in the URLconf. Defaults to ``page``.\n\n    .. attribute:: paginator_class\n\n       The paginator class to be used for pagination. By default,\n       :class:`django.core.paginator.Paginator` is used. If the custom paginator\n       class doesn't have the same constructor interface as\n       :class:`django.core.paginator.Paginator`, you will also need to\n       provide an implementation for :meth:`get_paginator`.\n\n    .. attribute:: context_object_name\n\n        Designates the name of the variable to use in the context.\n\n    .. method:: get_queryset()\n\n        Get the list of items for this view. This must be an iterable and may\n        be a queryset (in which queryset-specific behavior will be enabled).\n\n    .. method:: get_ordering()\n\n        Returns a string (or iterable of strings) that defines the ordering that\n        will be applied to the ``queryset``.\n\n        Returns :attr:`ordering` by default.\n\n    .. method:: paginate_queryset(queryset, page_size)\n\n        Returns a 4-tuple containing (``paginator``, ``page``, ``object_list``,\n        ``is_paginated``).\n\n        Constructed by paginating ``queryset`` into pages of size ``page_size``.\n        If the request contains a ``page`` argument, either as a captured URL\n        argument or as a GET argument, ``object_list`` will correspond to the\n        objects from that page.\n\n    .. method:: get_paginate_by(queryset)\n\n        Returns the number of items to paginate by, or ``None`` for no\n        pagination. By default this returns the value of :attr:`paginate_by`.\n\n    .. method:: get_paginator(queryset, per_page, orphans=0, allow_empty_first_page=True)\n\n        Returns an instance of the paginator to use for this view. By default,\n        instantiates an instance of :attr:`paginator_class`.\n\n    .. method:: get_paginate_orphans()\n\n        An integer specifying the number of \"overflow\" objects the last page\n        can contain. By default this returns the value of\n        :attr:`paginate_orphans`.\n\n    .. method:: get_allow_empty()\n\n        Return a boolean specifying whether to display the page if no objects\n        are available. If this method returns ``False`` and no objects are\n        available, the view will raise a 404 instead of displaying an empty\n        page. By default, this is ``True``.\n\n    .. method:: get_context_object_name(object_list)\n\n        Return the context variable name that will be used to contain\n        the list of data that this view is manipulating. If\n        ``object_list`` is a queryset of Django objects and\n        :attr:`context_object_name` is not set,\n        the context name will be the ``model_name`` of the model that\n        the queryset is composed from, with postfix ``'_list'``\n        appended. For example, the model ``Article`` would have a\n        context object named ``article_list``.\n\n    .. method:: get_context_data(**kwargs)\n\n        Returns context data for displaying the list of objects.\n\n    **Context**\n\n    * ``object_list``: The list of objects that this view is displaying. If\n      ``context_object_name`` is specified, that variable will also be set\n      in the context, with the same value as ``object_list``.\n\n    * ``is_paginated``: A boolean representing whether the results are\n      paginated. Specifically, this is set to ``False`` if no page size has\n      been specified, or if the available objects do not span multiple\n      pages.\n\n    * ``paginator``: An instance of\n      :class:`django.core.paginator.Paginator`. If the page is not\n      paginated, this context variable will be ``None``.\n\n    * ``page_obj``: An instance of\n      :class:`django.core.paginator.Page`. If the page is not paginated,\n      this context variable will be ``None``.\n\n\n``MultipleObjectTemplateResponseMixin``\n=======================================\n\n.. class:: django.views.generic.list.MultipleObjectTemplateResponseMixin\n\n    A mixin class that performs template-based response rendering for views\n    that operate upon a list of object instances. Requires that the view it is\n    mixed with provides ``self.object_list``, the list of object instances that\n    the view is operating on. ``self.object_list`` may be, but is not required\n    to be, a :class:`~django.db.models.query.QuerySet`.\n\n    **Extends**\n\n    * :class:`~django.views.generic.base.TemplateResponseMixin`\n\n    **Methods and Attributes**\n\n    .. attribute:: template_name_suffix\n\n        The suffix to append to the auto-generated candidate template name.\n        Default suffix is ``_list``.\n\n    .. method:: get_template_names()\n\n        Returns a list of candidate template names. Returns the following list:\n\n        * the value of ``template_name`` on the view (if provided)\n        * ``<app_label>/<model_name><template_name_suffix>.html``\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":164,"nodeType":"TextFile","repoName":null,"name":"language.txt","path":"docs/ref/templates","text":"============================\nThe Django template language\n============================\n\nThis document explains the language syntax of the Django template system. If\nyou're looking for a more technical perspective on how it works and how to\nextend it, see :doc:`/ref/templates/api`.\n\nDjango's template language is designed to strike a balance between power and\nease. It's designed to feel comfortable to those used to working with HTML. If\nyou have any exposure to other text-based template languages, such as Smarty_\nor Jinja2_, you should feel right at home with Django's templates.\n\n.. admonition:: Philosophy\n\n    If you have a background in programming, or if you're used to languages\n    which mix programming code directly into HTML, you'll want to bear in\n    mind that the Django template system is not simply Python embedded into\n    HTML. This is by design: the template system is meant to express\n    presentation, not program logic.\n\n    The Django template system provides tags which function similarly to some\n    programming constructs -- an :ttag:`if` tag for boolean tests, a :ttag:`for`\n    tag for looping, etc. -- but these are not simply executed as the\n    corresponding Python code, and the template system will not execute\n    arbitrary Python expressions. Only the tags, filters and syntax listed below\n    are supported by default (although you can add :doc:`your own extensions\n    </howto/custom-template-tags>` to the template language as needed).\n\n.. _`The Django template language: For Python programmers`: ../templates_python/\n.. _Smarty: https://www.smarty.net/\n.. _Jinja2: https://palletsprojects.com/p/jinja/\n\nTemplates\n=========\n\n.. highlight:: html+django\n\nA template is a text file. It can generate any text-based format (HTML, XML,\nCSV, etc.).\n\nA template contains **variables**, which get replaced with values when the\ntemplate is evaluated, and **tags**, which control the logic of the template.\n\nBelow is a minimal template that illustrates a few basics. Each element will be\nexplained later in this document.\n\n.. code-block:: html+django\n\n    {% extends \"base_generic.html\" %}\n\n    {% block title %}{{ section.title }}{% endblock %}\n\n    {% block content %}\n    <h1>{{ section.title }}</h1>\n\n    {% for story in story_list %}\n    <h2>\n      <a href=\"{{ story.get_absolute_url }}\">\n        {{ story.headline|upper }}\n      </a>\n    </h2>\n    <p>{{ story.tease|truncatewords:\"100\" }}</p>\n    {% endfor %}\n    {% endblock %}\n\n.. admonition:: Philosophy\n\n    Why use a text-based template instead of an XML-based one (like Zope's\n    TAL)? We wanted Django's template language to be usable for more than\n    just XML/HTML templates. You can use the template language for any\n    text-based format such as emails, JavaScript and CSV.\n\n.. _template-variables:\n\nVariables\n=========\n\nVariables look like this: ``{{ variable }}``. When the template engine\nencounters a variable, it evaluates that variable and replaces it with the\nresult. Variable names consist of any combination of alphanumeric characters\nand the underscore (``\"_\"``) but may not start with an underscore. The dot\n(``\".\"``) also appears in variable sections, although that has a special\nmeaning, as indicated below. Importantly, *you cannot have spaces or\npunctuation characters in variable names.*\n\nUse a dot (``.``) to access attributes of a variable.\n\n.. admonition:: Behind the scenes\n\n    Technically, when the template system encounters a dot, it tries the\n    following lookups, in this order:\n\n    * Dictionary lookup\n    * Attribute or method lookup\n    * Numeric index lookup\n\n    If the resulting value is callable, it is called with no arguments. The\n    result of the call becomes the template value.\n\n    This lookup order can cause some unexpected behavior with objects that\n    override dictionary lookup. For example, consider the following code snippet\n    that attempts to loop over a ``collections.defaultdict``::\n\n        {% for k, v in defaultdict.items %}\n            Do something with k and v here...\n        {% endfor %}\n\n    Because dictionary lookup happens first, that behavior kicks in and provides\n    a default value instead of using the intended ``.items()`` method. In this\n    case, consider converting to a dictionary first.\n\nIn the above example, ``{{ section.title }}`` will be replaced with the\n``title`` attribute of the ``section`` object.\n\nIf you use a variable that doesn't exist, the template system will insert the\nvalue of the ``string_if_invalid`` option, which is set to ``''`` (the empty\nstring) by default.\n\nNote that \"bar\" in a template expression like ``{{ foo.bar }}`` will be\ninterpreted as a literal string and not using the value of the variable \"bar\",\nif one exists in the template context.\n\nVariable attributes that begin with an underscore may not be accessed as\nthey're generally considered private.\n\nFilters\n=======\n\nYou can modify variables for display by using **filters**.\n\nFilters look like this: ``{{ name|lower }}``. This displays the value of the\n``{{ name }}`` variable after being filtered through the :tfilter:`lower`\nfilter, which converts text to lowercase. Use a pipe (``|``) to apply a filter.\n\nFilters can be \"chained.\" The output of one filter is applied to the next.\n``{{ text|escape|linebreaks }}`` is a common idiom for escaping text contents,\nthen converting line breaks to ``<p>`` tags.\n\nSome filters take arguments. A filter argument looks like this: ``{{\nbio|truncatewords:30 }}``. This will display the first 30 words of the ``bio``\nvariable.\n\nFilter arguments that contain spaces must be quoted; for example, to join a\nlist with commas and spaces you'd use ``{{ list|join:\", \" }}``.\n\nDjango provides about sixty built-in template filters. You can read all about\nthem in the :ref:`built-in filter reference <ref-templates-builtins-filters>`.\nTo give you a taste of what's available, here are some of the more commonly\nused template filters:\n\n:tfilter:`default`\n    If a variable is false or empty, use given default. Otherwise, use the\n    value of the variable. For example::\n\n        {{ value|default:\"nothing\" }}\n\n    If ``value`` isn't provided or is empty, the above will display\n    \"``nothing``\".\n\n:tfilter:`length`\n    Returns the length of the value. This works for both strings and lists.\n    For example::\n\n        {{ value|length }}\n\n    If ``value`` is ``['a', 'b', 'c', 'd']``, the output will be ``4``.\n\n:tfilter:`filesizeformat`\n    Formats the value like a \"human-readable\" file size (i.e. ``'13 KB'``,\n    ``'4.1 MB'``, ``'102 bytes'``, etc.). For example::\n\n        {{ value|filesizeformat }}\n\n    If ``value`` is 123456789, the output would be ``117.7 MB``.\n\nAgain, these are just a few examples; see the :ref:`built-in filter reference\n<ref-templates-builtins-filters>` for the complete list.\n\nYou can also create your own custom template filters; see\n:doc:`/howto/custom-template-tags`.\n\n.. seealso::\n\n    Django's admin interface can include a complete reference of all template\n    tags and filters available for a given site. See\n    :doc:`/ref/contrib/admin/admindocs`.\n\nTags\n====\n\nTags look like this: ``{% tag %}``. Tags are more complex than variables: Some\ncreate text in the output, some control flow by performing loops or logic, and\nsome load external information into the template to be used by later variables.\n\nSome tags require beginning and ending tags (i.e. ``{% tag %} ... tag contents\n... {% endtag %}``).\n\nDjango ships with about two dozen built-in template tags. You can read all about\nthem in the :ref:`built-in tag reference <ref-templates-builtins-tags>`. To give\nyou a taste of what's available, here are some of the more commonly used\ntags:\n\n:ttag:`for`\n    Loop over each item in an array.  For example, to display a list of athletes\n    provided in ``athlete_list``::\n\n        <ul>\n        {% for athlete in athlete_list %}\n            <li>{{ athlete.name }}</li>\n        {% endfor %}\n        </ul>\n\n:ttag:`if`, ``elif``, and ``else``\n    Evaluates a variable, and if that variable is \"true\" the contents of the\n    block are displayed::\n\n        {% if athlete_list %}\n            Number of athletes: {{ athlete_list|length }}\n        {% elif athlete_in_locker_room_list %}\n            Athletes should be out of the locker room soon!\n        {% else %}\n            No athletes.\n        {% endif %}\n\n    In the above, if ``athlete_list`` is not empty, the number of athletes\n    will be displayed by the ``{{ athlete_list|length }}`` variable. Otherwise,\n    if ``athlete_in_locker_room_list`` is not empty, the message \"Athletes\n    should be out...\" will be displayed. If both lists are empty,\n    \"No athletes.\" will be displayed.\n\n    You can also use filters and various operators in the :ttag:`if` tag::\n\n        {% if athlete_list|length > 1 %}\n           Team: {% for athlete in athlete_list %} ... {% endfor %}\n        {% else %}\n           Athlete: {{ athlete_list.0.name }}\n        {% endif %}\n\n    While the above example works, be aware that most template filters return\n    strings, so mathematical comparisons using filters will generally not work\n    as you expect. :tfilter:`length` is an exception.\n\n:ttag:`block` and :ttag:`extends`\n    Set up `template inheritance`_ (see below), a powerful way\n    of cutting down on \"boilerplate\" in templates.\n\nAgain, the above is only a selection of the whole list; see the :ref:`built-in\ntag reference <ref-templates-builtins-tags>` for the complete list.\n\nYou can also create your own custom template tags; see\n:doc:`/howto/custom-template-tags`.\n\n.. seealso::\n\n    Django's admin interface can include a complete reference of all template\n    tags and filters available for a given site. See\n    :doc:`/ref/contrib/admin/admindocs`.\n\n.. _template-comments:\n\nComments\n========\n\nTo comment-out part of a line in a template, use the comment syntax: ``{# #}``.\n\nFor example, this template would render as ``'hello'``::\n\n    {# greeting #}hello\n\nA comment can contain any template code, invalid or not. For example::\n\n    {# {% if foo %}bar{% else %} #}\n\nThis syntax can only be used for single-line comments (no newlines are permitted\nbetween the ``{#`` and ``#}`` delimiters). If you need to comment out a\nmultiline portion of the template, see the :ttag:`comment` tag.\n\n.. _template-inheritance:\n\nTemplate inheritance\n====================\n\nThe most powerful -- and thus the most complex -- part of Django's template\nengine is template inheritance. Template inheritance allows you to build a base\n\"skeleton\" template that contains all the common elements of your site and\ndefines **blocks** that child templates can override.\n\nLet's look at template inheritance by starting with an example::\n\n    <!DOCTYPE html>\n    <html lang=\"en\">\n    <head>\n        <link rel=\"stylesheet\" href=\"style.css\">\n        <title>{% block title %}My amazing site{% endblock %}</title>\n    </head>\n\n    <body>\n        <div id=\"sidebar\">\n            {% block sidebar %}\n            <ul>\n                <li><a href=\"/\">Home</a></li>\n                <li><a href=\"/blog/\">Blog</a></li>\n            </ul>\n            {% endblock %}\n        </div>\n\n        <div id=\"content\">\n            {% block content %}{% endblock %}\n        </div>\n    </body>\n    </html>\n\nThis template, which we'll call ``base.html``, defines an HTML skeleton\ndocument that you might use for a two-column page. It's the job of \"child\"\ntemplates to fill the empty blocks with content.\n\nIn this example, the :ttag:`block` tag defines three blocks that child\ntemplates can fill in. All the :ttag:`block` tag does is to tell the template\nengine that a child template may override those portions of the template.\n\nA child template might look like this::\n\n    {% extends \"base.html\" %}\n\n    {% block title %}My amazing blog{% endblock %}\n\n    {% block content %}\n    {% for entry in blog_entries %}\n        <h2>{{ entry.title }}</h2>\n        <p>{{ entry.body }}</p>\n    {% endfor %}\n    {% endblock %}\n\nThe :ttag:`extends` tag is the key here. It tells the template engine that\nthis template \"extends\" another template. When the template system evaluates\nthis template, first it locates the parent -- in this case, \"base.html\".\n\nAt that point, the template engine will notice the three :ttag:`block` tags\nin ``base.html`` and replace those blocks with the contents of the child\ntemplate. Depending on the value of ``blog_entries``, the output might look\nlike::\n\n    <!DOCTYPE html>\n    <html lang=\"en\">\n    <head>\n        <link rel=\"stylesheet\" href=\"style.css\">\n        <title>My amazing blog</title>\n    </head>\n\n    <body>\n        <div id=\"sidebar\">\n            <ul>\n                <li><a href=\"/\">Home</a></li>\n                <li><a href=\"/blog/\">Blog</a></li>\n            </ul>\n        </div>\n\n        <div id=\"content\">\n            <h2>Entry one</h2>\n            <p>This is my first entry.</p>\n\n            <h2>Entry two</h2>\n            <p>This is my second entry.</p>\n        </div>\n    </body>\n    </html>\n\nNote that since the child template didn't define the ``sidebar`` block, the\nvalue from the parent template is used instead. Content within a ``{% block %}``\ntag in a parent template is always used as a fallback.\n\nYou can use as many levels of inheritance as needed. One common way of using\ninheritance is the following three-level approach:\n\n* Create a ``base.html`` template that holds the main look-and-feel of your\n  site.\n* Create a ``base_SECTIONNAME.html`` template for each \"section\" of your\n  site. For example, ``base_news.html``, ``base_sports.html``. These\n  templates all extend ``base.html`` and include section-specific\n  styles/design.\n* Create individual templates for each type of page, such as a news\n  article or blog entry. These templates extend the appropriate section\n  template.\n\nThis approach maximizes code reuse and helps to add items to shared content\nareas, such as section-wide navigation.\n\nHere are some tips for working with inheritance:\n\n* If you use :ttag:`{% extends %}<extends>` in a template, it must be the first template\n  tag in that template. Template inheritance won't work, otherwise.\n\n* More :ttag:`{% block %}<block>` tags in your base templates are better. Remember,\n  child templates don't have to define all parent blocks, so you can fill\n  in reasonable defaults in a number of blocks, then only define the ones\n  you need later. It's better to have more hooks than fewer hooks.\n\n* If you find yourself duplicating content in a number of templates, it\n  probably means you should move that content to a ``{% block %}`` in a\n  parent template.\n\n* If you need to get the content of the block from the parent template,\n  the ``{{ block.super }}`` variable will do the trick. This is useful\n  if you want to add to the contents of a parent block instead of\n  completely overriding it. Data inserted using ``{{ block.super }}`` will\n  not be automatically escaped (see the `next section`_), since it was\n  already escaped, if necessary, in the parent template.\n\n* Variables created outside of a :ttag:`{% block %}<block>` using the template\n  tag ``as`` syntax can't be used inside the block. For example, this template\n  doesn't render anything::\n\n      {% translate \"Title\" as title %}\n      {% block content %}{{ title }}{% endblock %}\n\n* For extra readability, you can optionally give a *name* to your\n  ``{% endblock %}`` tag. For example::\n\n      {% block content %}\n      ...\n      {% endblock content %}\n\n  In larger templates, this technique helps you see which ``{% block %}``\n  tags are being closed.\n\nFinally, note that you can't define multiple :ttag:`block` tags with the same\nname in the same template. This limitation exists because a block tag works in\n\"both\" directions. That is, a block tag doesn't just provide a hole to fill --\nit also defines the content that fills the hole in the *parent*. If there were\ntwo similarly-named :ttag:`block` tags in a template, that template's parent\nwouldn't know which one of the blocks' content to use.\n\n.. _next section: #automatic-html-escaping\n.. _automatic-html-escaping:\n\nAutomatic HTML escaping\n=======================\n\nWhen generating HTML from templates, there's always a risk that a variable will\ninclude characters that affect the resulting HTML. For example, consider this\ntemplate fragment::\n\n    Hello, {{ name }}\n\nAt first, this seems like a harmless way to display a user's name, but consider\nwhat would happen if the user entered their name as this::\n\n    <script>alert('hello')</script>\n\nWith this name value, the template would be rendered as::\n\n    Hello, <script>alert('hello')</script>\n\n...which means the browser would pop-up a JavaScript alert box!\n\nSimilarly, what if the name contained a ``'<'`` symbol, like this?\n\n.. code-block:: html\n\n    <b>username\n\nThat would result in a rendered template like this::\n\n    Hello, <b>username\n\n...which, in turn, would result in the remainder of the Web page being bolded!\n\nClearly, user-submitted data shouldn't be trusted blindly and inserted directly\ninto your Web pages, because a malicious user could use this kind of hole to\ndo potentially bad things. This type of security exploit is called a\n`Cross Site Scripting`_ (XSS) attack.\n\nTo avoid this problem, you have two options:\n\n* One, you can make sure to run each untrusted variable through the\n  :tfilter:`escape` filter (documented below), which converts potentially\n  harmful HTML characters to unharmful ones. This was the default solution\n  in Django for its first few years, but the problem is that it puts the\n  onus on *you*, the developer / template author, to ensure you're escaping\n  everything. It's easy to forget to escape data.\n\n* Two, you can take advantage of Django's automatic HTML escaping. The\n  remainder of this section describes how auto-escaping works.\n\nBy default in Django, every template automatically escapes the output\nof every variable tag. Specifically, these five characters are\nescaped:\n\n* ``<`` is converted to ``&lt;``\n* ``>`` is converted to ``&gt;``\n* ``'`` (single quote) is converted to ``&#x27;``\n* ``\"`` (double quote) is converted to ``&quot;``\n* ``&`` is converted to ``&amp;``\n\nAgain, we stress that this behavior is on by default. If you're using Django's\ntemplate system, you're protected.\n\n.. _Cross Site Scripting: https://en.wikipedia.org/wiki/Cross-site_scripting\n\nHow to turn it off\n------------------\n\nIf you don't want data to be auto-escaped, on a per-site, per-template level or\nper-variable level, you can turn it off in several ways.\n\nWhy would you want to turn it off? Because sometimes, template variables\ncontain data that you *intend* to be rendered as raw HTML, in which case you\ndon't want their contents to be escaped. For example, you might store a blob of\nHTML in your database and want to embed that directly into your template. Or,\nyou might be using Django's template system to produce text that is *not* HTML\n-- like an email message, for instance.\n\nFor individual variables\n~~~~~~~~~~~~~~~~~~~~~~~~\n\nTo disable auto-escaping for an individual variable, use the :tfilter:`safe`\nfilter::\n\n    This will be escaped: {{ data }}\n    This will not be escaped: {{ data|safe }}\n\nThink of *safe* as shorthand for *safe from further escaping* or *can be\nsafely interpreted as HTML*. In this example, if ``data`` contains ``'<b>'``,\nthe output will be::\n\n    This will be escaped: &lt;b&gt;\n    This will not be escaped: <b>\n\nFor template blocks\n~~~~~~~~~~~~~~~~~~~\n\nTo control auto-escaping for a template, wrap the template (or a particular\nsection of the template) in the :ttag:`autoescape` tag, like so::\n\n    {% autoescape off %}\n        Hello {{ name }}\n    {% endautoescape %}\n\nThe :ttag:`autoescape` tag takes either ``on`` or ``off`` as its argument. At\ntimes, you might want to force auto-escaping when it would otherwise be\ndisabled. Here is an example template::\n\n    Auto-escaping is on by default. Hello {{ name }}\n\n    {% autoescape off %}\n        This will not be auto-escaped: {{ data }}.\n\n        Nor this: {{ other_data }}\n        {% autoescape on %}\n            Auto-escaping applies again: {{ name }}\n        {% endautoescape %}\n    {% endautoescape %}\n\nThe auto-escaping tag passes its effect onto templates that extend the\ncurrent one as well as templates included via the :ttag:`include` tag,\njust like all block tags. For example:\n\n.. code-block:: html+django\n    :caption: base.html\n\n    {% autoescape off %}\n    <h1>{% block title %}{% endblock %}</h1>\n    {% block content %}\n    {% endblock %}\n    {% endautoescape %}\n\n.. code-block:: html+django\n    :caption: child.html\n\n    {% extends \"base.html\" %}\n    {% block title %}This &amp; that{% endblock %}\n    {% block content %}{{ greeting }}{% endblock %}\n\nBecause auto-escaping is turned off in the base template, it will also be\nturned off in the child template, resulting in the following rendered\nHTML when the ``greeting`` variable contains the string ``<b>Hello!</b>``::\n\n    <h1>This &amp; that</h1>\n    <b>Hello!</b>\n\nNotes\n-----\n\nGenerally, template authors don't need to worry about auto-escaping very much.\nDevelopers on the Python side (people writing views and custom filters) need to\nthink about the cases in which data shouldn't be escaped, and mark data\nappropriately, so things Just Work in the template.\n\nIf you're creating a template that might be used in situations where you're\nnot sure whether auto-escaping is enabled, then add an :tfilter:`escape` filter\nto any variable that needs escaping. When auto-escaping is on, there's no\ndanger of the :tfilter:`escape` filter *double-escaping* data -- the\n:tfilter:`escape` filter does not affect auto-escaped variables.\n\n.. _string-literals-and-automatic-escaping:\n\nString literals and automatic escaping\n--------------------------------------\n\nAs we mentioned earlier, filter arguments can be strings::\n\n    {{ data|default:\"This is a string literal.\" }}\n\nAll string literals are inserted **without** any automatic escaping into the\ntemplate -- they act as if they were all passed through the :tfilter:`safe`\nfilter. The reasoning behind this is that the template author is in control of\nwhat goes into the string literal, so they can make sure the text is correctly\nescaped when the template is written.\n\nThis means you would write ::\n\n    {{ data|default:\"3 &lt; 2\" }}\n\n...rather than::\n\n    {{ data|default:\"3 < 2\" }}  {# Bad! Don't do this. #}\n\nThis doesn't affect what happens to data coming from the variable itself.\nThe variable's contents are still automatically escaped, if necessary, because\nthey're beyond the control of the template author.\n\n.. _template-accessing-methods:\n\nAccessing method calls\n======================\n\nMost method calls attached to objects are also available from within templates.\nThis means that templates have access to much more than just class attributes\n(like field names) and variables passed in from views. For example, the Django\nORM provides the :ref:`\"entry_set\"<topics-db-queries-related>` syntax for\nfinding a collection of objects related on a foreign key. Therefore, given\na model called \"comment\" with a foreign key relationship to a model called\n\"task\" you can loop through all comments attached to a given task like this::\n\n    {% for comment in task.comment_set.all %}\n        {{ comment }}\n    {% endfor %}\n\nSimilarly, :doc:`QuerySets</ref/models/querysets>` provide a ``count()`` method\nto count the number of objects they contain. Therefore, you can obtain a count\nof all comments related to the current task with::\n\n    {{ task.comment_set.all.count }}\n\nYou can also access methods you've explicitly defined on your own models:\n\n.. code-block:: python\n    :caption: models.py\n\n    class Task(models.Model):\n        def foo(self):\n            return \"bar\"\n\n.. code-block:: html+django\n    :caption: template.html\n\n    {{ task.foo }}\n\nBecause Django intentionally limits the amount of logic processing available\nin the template language, it is not possible to pass arguments to method calls\naccessed from within templates. Data should be calculated in views, then passed\nto templates for display.\n\n.. _loading-custom-template-libraries:\n\nCustom tag and filter libraries\n===============================\n\nCertain applications provide custom tag and filter libraries. To access them in\na template, ensure the application is in :setting:`INSTALLED_APPS` (we'd add\n``'django.contrib.humanize'`` for this example), and then use the :ttag:`load`\ntag in a template::\n\n    {% load humanize %}\n\n    {{ 45000|intcomma }}\n\nIn the above, the :ttag:`load` tag loads the ``humanize`` tag library, which then\nmakes the ``intcomma`` filter available for use. If you've enabled\n:mod:`django.contrib.admindocs`, you can consult the documentation area in your\nadmin to find the list of custom libraries in your installation.\n\nThe :ttag:`load` tag can take multiple library names, separated by spaces.\nExample::\n\n    {% load humanize i18n %}\n\nSee :doc:`/howto/custom-template-tags` for information on writing your own custom\ntemplate libraries.\n\nCustom libraries and template inheritance\n-----------------------------------------\n\nWhen you load a custom tag or filter library, the tags/filters are only made\navailable to the current template -- not any parent or child templates along\nthe template-inheritance path.\n\nFor example, if a template ``foo.html`` has ``{% load humanize %}``, a child\ntemplate (e.g., one that has ``{% extends \"foo.html\" %}``) will *not* have\naccess to the humanize template tags and filters. The child template is\nresponsible for its own ``{% load humanize %}``.\n\nThis is a feature for the sake of maintainability and sanity.\n\n.. seealso::\n\n    :doc:`The Templates Reference </ref/templates/index>`\n        Covers built-in tags, built-in filters, using an alternative template,\n        language, and more.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":165,"nodeType":"Package","repoName":null,"name":"docs/howto","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":166,"nodeType":"TextFile","repoName":null,"name":"custom-template-backend.txt","path":"docs/howto","text":"=======================\nCustom template backend\n=======================\n\nCustom backends\n---------------\n\nHere's how to implement a custom template backend in order to use another\ntemplate system. A template backend is a class that inherits\n``django.template.backends.base.BaseEngine``. It must implement\n``get_template()`` and optionally ``from_string()``. Here's an example for a\nfictional ``foobar`` template library::\n\n    from django.template import TemplateDoesNotExist, TemplateSyntaxError\n    from django.template.backends.base import BaseEngine\n    from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy\n\n    import foobar\n\n\n    class FooBar(BaseEngine):\n\n        # Name of the subdirectory containing the templates for this engine\n        # inside an installed application.\n        app_dirname = 'foobar'\n\n        def __init__(self, params):\n            params = params.copy()\n            options = params.pop('OPTIONS').copy()\n            super().__init__(params)\n\n            self.engine = foobar.Engine(**options)\n\n        def from_string(self, template_code):\n            try:\n                return Template(self.engine.from_string(template_code))\n            except foobar.TemplateCompilationFailed as exc:\n                raise TemplateSyntaxError(exc.args)\n\n        def get_template(self, template_name):\n            try:\n                return Template(self.engine.get_template(template_name))\n            except foobar.TemplateNotFound as exc:\n                raise TemplateDoesNotExist(exc.args, backend=self)\n            except foobar.TemplateCompilationFailed as exc:\n                raise TemplateSyntaxError(exc.args)\n\n\n    class Template:\n\n        def __init__(self, template):\n            self.template = template\n\n        def render(self, context=None, request=None):\n            if context is None:\n                context = {}\n            if request is not None:\n                context['request'] = request\n                context['csrf_input'] = csrf_input_lazy(request)\n                context['csrf_token'] = csrf_token_lazy(request)\n            return self.template.render(context)\n\nSee `DEP 182`_ for more information.\n\n.. _template-debug-integration:\n\nDebug integration for custom engines\n------------------------------------\n\nThe Django debug page has hooks to provide detailed information when a template\nerror arises. Custom template engines can use these hooks to enhance the\ntraceback information that appears to users. The following hooks are available:\n\n.. _template-postmortem:\n\nTemplate postmortem\n~~~~~~~~~~~~~~~~~~~\n\nThe postmortem appears when :exc:`~django.template.TemplateDoesNotExist` is\nraised. It lists the template engines and loaders that were used when trying to\nfind a given template. For example, if two Django engines are configured, the\npostmortem will appear like:\n\n.. image:: _images/postmortem.png\n\nCustom engines can populate the postmortem by passing the ``backend`` and\n``tried`` arguments when raising :exc:`~django.template.TemplateDoesNotExist`.\nBackends that use the postmortem :ref:`should specify an origin\n<template-origin-api>` on the template object.\n\nContextual line information\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf an error happens during template parsing or rendering, Django can display\nthe line the error happened on. For example:\n\n.. image:: _images/template-lines.png\n\nCustom engines can populate this information by setting a ``template_debug``\nattribute on exceptions raised during parsing and rendering. This attribute is\na :class:`dict` with the following values:\n\n* ``'name'``: The name of the template in which the exception occurred.\n\n* ``'message'``: The exception message.\n\n* ``'source_lines'``: The lines before, after, and including the line the\n  exception occurred on. This is for context, so it shouldn't contain more than\n  20 lines or so.\n\n* ``'line'``: The line number on which the exception occurred.\n\n* ``'before'``: The content on the error line before the token that raised the\n  error.\n\n* ``'during'``: The token that raised the error.\n\n* ``'after'``: The content on the error line after the token that raised the\n  error.\n\n* ``'total'``: The number of lines in ``source_lines``.\n\n* ``'top'``: The line number where ``source_lines`` starts.\n\n* ``'bottom'``: The line number where ``source_lines`` ends.\n\nGiven the above template error, ``template_debug`` would look like::\n\n    {\n        'name': '/path/to/template.html',\n        'message': \"Invalid block tag: 'syntax'\",\n        'source_lines': [\n            (1, 'some\\n'),\n            (2, 'lines\\n'),\n            (3, 'before\\n'),\n            (4, 'Hello {% syntax error %} {{ world }}\\n'),\n            (5, 'some\\n'),\n            (6, 'lines\\n'),\n            (7, 'after\\n'),\n            (8, ''),\n        ],\n        'line': 4,\n        'before': 'Hello ',\n        'during': '{% syntax error %}',\n        'after': ' {{ world }}\\n',\n        'total': 9,\n        'bottom': 9,\n        'top': 1,\n    }\n\n.. _template-origin-api:\n\nOrigin API and 3rd-party integration\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nDjango templates have an :class:`~django.template.base.Origin` object available\nthrough the ``template.origin`` attribute. This enables debug information to be\ndisplayed in the :ref:`template postmortem <template-postmortem>`, as well as\nin 3rd-party libraries, like the `Django Debug Toolbar`_.\n\nCustom engines can provide their own ``template.origin`` information by\ncreating an object that specifies the following attributes:\n\n* ``'name'``: The full path to the template.\n\n* ``'template_name'``: The relative path to the template as passed into the\n  template loading methods.\n\n* ``'loader_name'``: An optional string identifying the function or class used\n  to load the template, e.g. ``django.template.loaders.filesystem.Loader``.\n\n.. _DEP 182: https://github.com/django/deps/blob/master/final/0182-multiple-template-engines.rst\n.. _Django Debug Toolbar: https://github.com/jazzband/django-debug-toolbar\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":167,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/ref/class-based-views","text":"==============================\nBuilt-in class-based views API\n==============================\n\nClass-based views API reference. For introductory material, see the\n:doc:`/topics/class-based-views/index` topic guide.\n\n.. toctree::\n   :maxdepth: 3\n\n   base\n   generic-display\n   generic-editing\n   generic-date-based\n   mixins\n   flattened-index\n\nSpecification\n=============\n\nEach request served by a class-based view has an independent state; therefore,\nit is safe to store state variables on the instance (i.e., ``self.foo = 3`` is\na thread-safe operation).\n\nA class-based view is deployed into a URL pattern using the\n:meth:`~django.views.generic.base.View.as_view()` classmethod::\n\n    urlpatterns = [\n        path('view/', MyView.as_view(size=42)),\n    ]\n\n.. admonition:: Thread safety with view arguments\n\n    Arguments passed to a view are shared between every instance of a view.\n    This means that you shouldn't use a list, dictionary, or any other\n    mutable object as an argument to a view. If you do and the shared object\n    is modified, the actions of one user visiting your view could have an\n    effect on subsequent users visiting the same view.\n\nArguments passed into :meth:`~django.views.generic.base.View.as_view()` will\nbe assigned onto the instance that is used to service a request. Using the\nprevious example, this means that every request on ``MyView`` is able to use\n``self.size``. Arguments must correspond to attributes that already exist on\nthe class (return ``True`` on a ``hasattr`` check).\n\nBase vs Generic views\n=====================\n\nBase class-based views can be thought of as *parent* views, which can be\nused by themselves or inherited from. They may not provide all the\ncapabilities required for projects, in which case there are Mixins which\nextend what base views can do.\n\nDjango's generic views are built off of those base views, and were developed\nas a shortcut for common usage patterns such as displaying the details of an\nobject. They take certain common idioms and patterns found in view\ndevelopment and abstract them so that you can quickly write common views of\ndata without having to repeat yourself.\n\nMost generic views require the ``queryset`` key, which is a ``QuerySet``\ninstance; see :doc:`/topics/db/queries` for more information about ``QuerySet``\nobjects.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":168,"nodeType":"TextFile","repoName":null,"name":"mixins-simple.txt","path":"docs/ref/class-based-views","text":"=============\nSimple mixins\n=============\n\n``ContextMixin``\n================\n\n.. class:: django.views.generic.base.ContextMixin\n\n    **Attributes**\n\n    .. attribute:: extra_context\n\n        A dictionary to include in the context. This is a convenient way of\n        specifying some context in\n        :meth:`~django.views.generic.base.View.as_view`. Example usage::\n\n            from django.views.generic import TemplateView\n            TemplateView.as_view(extra_context={'title': 'Custom Title'})\n\n    **Methods**\n\n    .. method:: get_context_data(**kwargs)\n\n        Returns a dictionary representing the template context. The keyword\n        arguments provided will make up the returned context. Example usage::\n\n            def get_context_data(self, **kwargs):\n                context = super().get_context_data(**kwargs)\n                context['number'] = random.randrange(1, 100)\n                return context\n\n        The template context of all class-based generic views include a\n        ``view`` variable that points to the ``View`` instance.\n\n        .. admonition:: Use ``alters_data`` where appropriate\n\n            Note that having the view instance in the template context may\n            expose potentially hazardous methods to template authors.  To\n            prevent methods like this from being called in the template, set\n            ``alters_data=True`` on those methods.  For more information, read\n            the documentation on :ref:`rendering a template context\n            <alters-data-description>`.\n\n``TemplateResponseMixin``\n=========================\n\n.. class:: django.views.generic.base.TemplateResponseMixin\n\n    Provides a mechanism to construct a\n    :class:`~django.template.response.TemplateResponse`, given\n    suitable context. The template to use is configurable and can be\n    further customized by subclasses.\n\n    **Attributes**\n\n    .. attribute:: template_name\n\n        The full name of a template to use as defined by a string. Not defining\n        a ``template_name`` will raise a\n        :class:`django.core.exceptions.ImproperlyConfigured` exception.\n\n    .. attribute:: template_engine\n\n        The :setting:`NAME <TEMPLATES-NAME>` of a template engine to use for\n        loading the template. ``template_engine`` is passed as the ``using``\n        keyword argument to ``response_class``. Default is ``None``, which\n        tells Django to search for the template in all configured engines.\n\n    .. attribute:: response_class\n\n        The response class to be returned by ``render_to_response`` method.\n        Default is :class:`TemplateResponse\n        <django.template.response.TemplateResponse>`. The template and context\n        of ``TemplateResponse`` instances can be altered later (e.g. in\n        :ref:`template response middleware <template-response-middleware>`).\n\n        If you need custom template loading or custom context object\n        instantiation, create a ``TemplateResponse`` subclass and assign it to\n        ``response_class``.\n\n    .. attribute:: content_type\n\n        The content type to use for the response. ``content_type`` is passed\n        as a keyword argument to ``response_class``. Default is ``None`` --\n        meaning that Django uses ``'text/html'``.\n\n    **Methods**\n\n    .. method:: render_to_response(context, **response_kwargs)\n\n        Returns a ``self.response_class`` instance.\n\n        If any keyword arguments are provided, they will be passed to the\n        constructor of the response class.\n\n        Calls :meth:`get_template_names()` to obtain the list of template names\n        that will be searched looking for an existent template.\n\n    .. method:: get_template_names()\n\n        Returns a list of template names to search for when rendering the\n        template. The first template that is found will be used.\n\n        If :attr:`template_name` is specified, the default implementation will\n        return a list containing :attr:`template_name` (if it is specified).\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":169,"nodeType":"TextFile","repoName":null,"name":"overriding-templates.txt","path":"docs/howto","text":"====================\nOverriding templates\n====================\n\nIn your project, you might want to override a template in another Django\napplication, whether it be a third-party application or a contrib application\nsuch as ``django.contrib.admin``. You can either put template overrides in your\nproject's templates directory or in an application's templates directory.\n\nIf you have app and project templates directories that both contain overrides,\nthe default Django template loader will try to load the template from the\nproject-level directory first. In other words, :setting:`DIRS <TEMPLATES-DIRS>`\nis searched before :setting:`APP_DIRS <TEMPLATES-APP_DIRS>`.\n\n.. seealso::\n\n   Read :ref:`overriding-built-in-widget-templates` if you're looking to\n   do that.\n\nOverriding from the project's templates directory\n=================================================\n\nFirst, we'll explore overriding templates by creating replacement templates in\nyour project's templates directory.\n\nLet's say you're trying to override the templates for a third-party application\ncalled ``blog``, which provides the templates ``blog/post.html`` and\n``blog/list.html``. The relevant settings for your project would look like::\n\n    from pathlib import Path\n\n    BASE_DIR = Path(__file__).resolve(strict=True).parent.parent\n\n    INSTALLED_APPS = [\n        ...,\n        'blog',\n        ...,\n    ]\n\n    TEMPLATES = [\n        {\n            'BACKEND': 'django.template.backends.django.DjangoTemplates',\n            'DIRS': [BASE_DIR / 'templates'],\n            'APP_DIRS': True,\n            ...\n        },\n    ]\n\nThe :setting:`TEMPLATES` setting and ``BASE_DIR`` will already exist if you\ncreated your project using the default project template. The setting that needs\nto be modified is :setting:`DIRS<TEMPLATES-DIRS>`.\n\nThese settings assume you have a ``templates`` directory in the root of your\nproject. To override the templates for the ``blog`` app, create a folder\nin the ``templates`` directory, and add the template files to that folder:\n\n.. code-block:: none\n\n    templates/\n        blog/\n            list.html\n            post.html\n\nThe template loader first looks for templates in the ``DIRS`` directory. When\nthe views in the ``blog`` app ask for the ``blog/post.html`` and\n``blog/list.html`` templates, the loader will return the files you just created.\n\nOverriding from an app's template directory\n===========================================\n\nSince you're overriding templates located outside of one of your project's\napps, it's more common to use the first method and put template overrides in a\nproject's templates folder. If you prefer, however, it's also possible to put\nthe overrides in an app's template directory.\n\nFirst, make sure your template settings are checking inside app directories::\n\n    TEMPLATES = [\n        {\n            ...,\n            'APP_DIRS': True,\n            ...\n        },\n    ]\n\nIf you want to put the template overrides in an app called ``myapp`` and the\ntemplates to override are named ``blog/list.html`` and ``blog/post.html``,\nthen your directory structure will look like:\n\n.. code-block:: none\n\n    myapp/\n        templates/\n            blog/\n                list.html\n                post.html\n\nWith :setting:`APP_DIRS<TEMPLATES-APP_DIRS>` set to ``True``, the template\nloader will look in the app's templates directory and find the templates.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":170,"nodeType":"Package","repoName":null,"name":"docs/misc","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":171,"nodeType":"TextFile","repoName":null,"name":"api-stability.txt","path":"docs/misc","text":"=============\nAPI stability\n=============\n\nDjango is committed to API stability and forwards-compatibility. In a nutshell,\nthis means that code you develop against a version of Django will continue to\nwork with future releases. You may need to make minor changes when upgrading\nthe version of Django your project uses: see the \"Backwards incompatible\nchanges\" section of the :doc:`release note </releases/index>` for the version\nor versions to which you are upgrading.\n\nAt the same time as making API stability a very high priority, Django is also\ncommitted to continual improvement, along with aiming for \"one way to do it\"\n(eventually) in the APIs we provide. This means that when we discover clearly\nsuperior ways to do things, we will deprecate and eventually remove the old\nways. Our aim is to provide a modern, dependable web framework of the highest\nquality that encourages best practices in all projects that use it. By using\nincremental improvements, we try to avoid both stagnation and large breaking\nupgrades.\n\nWhat \"stable\" means\n===================\n\nIn this context, stable means:\n\n- All the public APIs (everything in this documentation) will not be moved\n  or renamed without providing backwards-compatible aliases.\n\n- If new features are added to these APIs -- which is quite possible --\n  they will not break or change the meaning of existing methods. In other\n  words, \"stable\" does not (necessarily) mean \"complete.\"\n\n- If, for some reason, an API declared stable must be removed or replaced, it\n  will be declared deprecated but will remain in the API for at least two\n  feature releases. Warnings will be issued when the deprecated method is\n  called.\n\n  See :ref:`official-releases` for more details on how Django's version\n  numbering scheme works, and how features will be deprecated.\n\n- We'll only break backwards compatibility of these APIs without a deprecation\n  process if a bug or security hole makes it completely unavoidable.\n\nStable APIs\n===========\n\nIn general, everything covered in the documentation -- with the exception of\nanything in the :doc:`internals area </internals/index>` is considered stable.\n\nExceptions\n==========\n\nThere are a few exceptions to this stability and backwards-compatibility\npromise.\n\nSecurity fixes\n--------------\n\nIf we become aware of a security problem -- hopefully by someone following our\n:ref:`security reporting policy <reporting-security-issues>` -- we'll do\neverything necessary to fix it. This might mean breaking backwards\ncompatibility; security trumps the compatibility guarantee.\n\nAPIs marked as internal\n-----------------------\n\nCertain APIs are explicitly marked as \"internal\" in a couple of ways:\n\n- Some documentation refers to internals and mentions them as such. If the\n  documentation says that something is internal, we reserve the right to\n  change it.\n\n- Functions, methods, and other objects prefixed by a leading underscore\n  (``_``). This is the standard Python way of indicating that something is\n  private; if any method starts with a single ``_``, it's an internal API.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":172,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/misc","text":"=================================\nMeta-documentation and miscellany\n=================================\n\nDocumentation that we can't find a more organized place for. Like that drawer in\nyour kitchen with the scissors, batteries, duct tape, and other junk.\n\n.. toctree::\n   :maxdepth: 2\n\n   api-stability\n   design-philosophies\n   distributions\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":173,"nodeType":"TextFile","repoName":null,"name":"distributions.txt","path":"docs/misc","text":"===================================\nThird-party distributions of Django\n===================================\n\nMany third-party distributors are now providing versions of Django integrated\nwith their package-management systems. These can make installation and upgrading\nmuch easier for users of Django since the integration includes the ability to\nautomatically install dependencies (like database adapters) that Django\nrequires.\n\nTypically, these packages are based on the latest stable release of Django, so\nif you want to use the development version of Django you'll need to follow the\ninstructions for :ref:`installing the development version\n<installing-development-version>` from our Git repository.\n\nIf you're using Linux or a Unix installation, such as OpenSolaris,\ncheck with your distributor to see if they already package Django. If\nyou're using a Linux distro and don't know how to find out if a package\nis available, then now is a good time to learn.  The Django Wiki contains\na list of `Third Party Distributions`_ to help you out.\n\n.. _`Third Party Distributions`: https://code.djangoproject.com/wiki/Distributions\n\n\nFor distributors\n================\n\nIf you'd like to package Django for distribution, we'd be happy to help out!\nPlease join the |django-developers| mailing list and introduce yourself.\n\nWe also encourage all distributors to subscribe to the |django-announce| mailing\nlist, which is a (very) low-traffic list for announcing new releases of Django\nand important bugfixes.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":174,"nodeType":"TextFile","repoName":null,"name":"generic-display.txt","path":"docs/ref/class-based-views","text":"=====================\nGeneric display views\n=====================\n\nThe two following generic class-based views are designed to display data. On\nmany projects they are typically the most commonly used views.\n\n``DetailView``\n==============\n\n.. class:: django.views.generic.detail.DetailView\n\n    While this view is executing, ``self.object`` will contain the object that\n    the view is operating upon.\n\n    **Ancestors (MRO)**\n\n    This view inherits methods and attributes from the following views:\n\n    * :class:`django.views.generic.detail.SingleObjectTemplateResponseMixin`\n    * :class:`django.views.generic.base.TemplateResponseMixin`\n    * ``django.views.generic.detail.BaseDetailView``\n    * :class:`django.views.generic.detail.SingleObjectMixin`\n    * :class:`django.views.generic.base.View`\n\n    **Method Flowchart**\n\n    #. :meth:`~django.views.generic.base.View.setup()`\n    #. :meth:`~django.views.generic.base.View.dispatch()`\n    #. :meth:`~django.views.generic.base.View.http_method_not_allowed()`\n    #. :meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names()`\n    #. :meth:`~django.views.generic.detail.SingleObjectMixin.get_slug_field()`\n    #. :meth:`~django.views.generic.detail.SingleObjectMixin.get_queryset()`\n    #. :meth:`~django.views.generic.detail.SingleObjectMixin.get_object()`\n    #. :meth:`~django.views.generic.detail.SingleObjectMixin.get_context_object_name()`\n    #. :meth:`~django.views.generic.detail.SingleObjectMixin.get_context_data()`\n    #. ``get()``\n    #. :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response()`\n\n    **Example myapp/views.py**::\n\n        from django.utils import timezone\n        from django.views.generic.detail import DetailView\n\n        from articles.models import Article\n\n        class ArticleDetailView(DetailView):\n\n            model = Article\n\n            def get_context_data(self, **kwargs):\n                context = super().get_context_data(**kwargs)\n                context['now'] = timezone.now()\n                return context\n\n    **Example myapp/urls.py**::\n\n        from django.urls import path\n\n        from article.views import ArticleDetailView\n\n        urlpatterns = [\n            path('<slug:slug>/', ArticleDetailView.as_view(), name='article-detail'),\n        ]\n\n    **Example myapp/article_detail.html**:\n\n    .. code-block:: html+django\n\n        <h1>{{ object.headline }}</h1>\n        <p>{{ object.content }}</p>\n        <p>Reporter: {{ object.reporter }}</p>\n        <p>Published: {{ object.pub_date|date }}</p>\n        <p>Date: {{ now|date }}</p>\n\n``ListView``\n============\n\n.. class:: django.views.generic.list.ListView\n\n    A page representing a list of objects.\n\n    While this view is executing, ``self.object_list`` will contain the list of\n    objects (usually, but not necessarily a queryset) that the view is\n    operating upon.\n\n    **Ancestors (MRO)**\n\n    This view inherits methods and attributes from the following views:\n\n    * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`\n    * :class:`django.views.generic.base.TemplateResponseMixin`\n    * :class:`django.views.generic.list.BaseListView`\n    * :class:`django.views.generic.list.MultipleObjectMixin`\n    * :class:`django.views.generic.base.View`\n\n    **Method Flowchart**\n\n    #. :meth:`~django.views.generic.base.View.setup()`\n    #. :meth:`~django.views.generic.base.View.dispatch()`\n    #. :meth:`~django.views.generic.base.View.http_method_not_allowed()`\n    #. :meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names()`\n    #. :meth:`~django.views.generic.list.MultipleObjectMixin.get_queryset()`\n    #. :meth:`~django.views.generic.list.MultipleObjectMixin.get_context_object_name()`\n    #. :meth:`~django.views.generic.list.MultipleObjectMixin.get_context_data()`\n    #. ``get()``\n    #. :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response()`\n\n    **Example views.py**::\n\n        from django.utils import timezone\n        from django.views.generic.list import ListView\n\n        from articles.models import Article\n\n        class ArticleListView(ListView):\n\n            model = Article\n            paginate_by = 100  # if pagination is desired\n\n            def get_context_data(self, **kwargs):\n                context = super().get_context_data(**kwargs)\n                context['now'] = timezone.now()\n                return context\n\n    **Example myapp/urls.py**::\n\n        from django.urls import path\n\n        from article.views import ArticleListView\n\n        urlpatterns = [\n            path('', ArticleListView.as_view(), name='article-list'),\n        ]\n\n    **Example myapp/article_list.html**:\n\n    .. code-block:: html+django\n\n        <h1>Articles</h1>\n        <ul>\n        {% for article in object_list %}\n            <li>{{ article.pub_date|date }} - {{ article.headline }}</li>\n        {% empty %}\n            <li>No articles yet.</li>\n        {% endfor %}\n        </ul>\n\n    If you're using pagination, you can adapt the :ref:`example template from\n    the pagination docs <using-paginator-in-view>`. Change instances of\n    ``contacts`` in that example template to ``page_obj``.\n\n.. class:: django.views.generic.list.BaseListView\n\n    A base view for displaying a list of objects. It is not intended to be used\n    directly, but rather as a parent class of the\n    :class:`django.views.generic.list.ListView` or other views representing\n    lists of objects.\n\n    **Ancestors (MRO)**\n\n    This view inherits methods and attributes from the following views:\n\n    * :class:`django.views.generic.list.MultipleObjectMixin`\n    * :class:`django.views.generic.base.View`\n\n    **Methods**\n\n    .. method:: get(request, *args, **kwargs)\n\n        Adds ``object_list`` to the context. If\n        :attr:`~django.views.generic.list.MultipleObjectMixin.allow_empty`\n        is True then display an empty list. If\n        :attr:`~django.views.generic.list.MultipleObjectMixin.allow_empty` is\n        False then raise a 404 error.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":175,"nodeType":"TextFile","repoName":null,"name":"mixins-editing.txt","path":"docs/ref/class-based-views","text":"==============\nEditing mixins\n==============\n\nThe following mixins are used to construct Django's editing views:\n\n* :class:`django.views.generic.edit.FormMixin`\n* :class:`django.views.generic.edit.ModelFormMixin`\n* :class:`django.views.generic.edit.ProcessFormView`\n* :class:`django.views.generic.edit.DeletionMixin`\n\n.. note::\n\n    Examples of how these are combined into editing views can be found at\n    the documentation on :doc:`/ref/class-based-views/generic-editing`.\n\n``FormMixin``\n=============\n\n.. class:: django.views.generic.edit.FormMixin\n\n    A mixin class that provides facilities for creating and displaying forms.\n\n    **Mixins**\n\n    * :class:`django.views.generic.base.ContextMixin`\n\n    **Methods and Attributes**\n\n    .. attribute:: initial\n\n        A dictionary containing initial data for the form.\n\n    .. attribute:: form_class\n\n        The form class to instantiate.\n\n    .. attribute:: success_url\n\n        The URL to redirect to when the form is successfully processed.\n\n    .. attribute:: prefix\n\n        The :attr:`~django.forms.Form.prefix` for the generated form.\n\n    .. method:: get_initial()\n\n        Retrieve initial data for the form. By default, returns a copy of\n        :attr:`~django.views.generic.edit.FormMixin.initial`.\n\n    .. method:: get_form_class()\n\n        Retrieve the form class to instantiate. By default\n        :attr:`.form_class`.\n\n    .. method:: get_form(form_class=None)\n\n        Instantiate an instance of ``form_class`` using\n        :meth:`~django.views.generic.edit.FormMixin.get_form_kwargs`.\n        If ``form_class`` isn't provided :meth:`get_form_class` will be used.\n\n    .. method:: get_form_kwargs()\n\n        Build the keyword arguments required to instantiate the form.\n\n        The ``initial`` argument is set to :meth:`.get_initial`. If the\n        request is a ``POST`` or ``PUT``, the request data (``request.POST``\n        and ``request.FILES``) will also be provided.\n\n    .. method:: get_prefix()\n\n        Determine the :attr:`~django.forms.Form.prefix` for the generated form.\n        Returns :attr:`~django.views.generic.edit.FormMixin.prefix` by default.\n\n    .. method:: get_success_url()\n\n        Determine the URL to redirect to when the form is successfully\n        validated. Returns\n        :attr:`~django.views.generic.edit.FormMixin.success_url` by default.\n\n    .. method:: form_valid(form)\n\n        Redirects to\n        :meth:`~django.views.generic.edit.FormMixin.get_success_url`.\n\n    .. method:: form_invalid(form)\n\n        Renders a response, providing the invalid form as context.\n\n    .. method:: get_context_data(**kwargs)\n\n        Calls :meth:`get_form` and adds the result to the context data with the\n        name 'form'.\n\n``ModelFormMixin``\n==================\n\n.. class:: django.views.generic.edit.ModelFormMixin\n\n    A form mixin that works on ``ModelForms``, rather than a standalone form.\n\n    Since this is a subclass of\n    :class:`~django.views.generic.detail.SingleObjectMixin`, instances of this\n    mixin have access to the\n    :attr:`~django.views.generic.detail.SingleObjectMixin.model` and\n    :attr:`~django.views.generic.detail.SingleObjectMixin.queryset` attributes,\n    describing the type of object that the ``ModelForm`` is manipulating.\n\n    If you specify both the\n    :attr:`~django.views.generic.edit.ModelFormMixin.fields` and\n    :attr:`~django.views.generic.edit.FormMixin.form_class` attributes, an\n    :exc:`~django.core.exceptions.ImproperlyConfigured` exception will be\n    raised.\n\n    **Mixins**\n\n    * :class:`django.views.generic.edit.FormMixin`\n    * :class:`django.views.generic.detail.SingleObjectMixin`\n\n    **Methods and Attributes**\n\n    .. attribute:: model\n\n        A model class. Can be explicitly provided, otherwise will be determined\n        by examining ``self.object`` or\n        :attr:`~django.views.generic.detail.SingleObjectMixin.queryset`.\n\n    .. attribute:: fields\n\n        A list of names of fields. This is interpreted the same way as the\n        ``Meta.fields`` attribute of :class:`~django.forms.ModelForm`.\n\n        This is a required attribute if you are generating the form class\n        automatically (e.g. using ``model``). Omitting this attribute will\n        result in an :exc:`~django.core.exceptions.ImproperlyConfigured`\n        exception.\n\n    .. attribute:: success_url\n\n        The URL to redirect to when the form is successfully processed.\n\n        ``success_url`` may contain dictionary string formatting, which\n        will be interpolated against the object's field attributes. For\n        example, you could use ``success_url=\"/polls/{slug}/\"`` to\n        redirect to a URL composed out of the ``slug`` field on a model.\n\n    .. method:: get_form_class()\n\n        Retrieve the form class to instantiate. If\n        :attr:`~django.views.generic.edit.FormMixin.form_class` is provided,\n        that class will be used. Otherwise, a ``ModelForm`` will be\n        instantiated using the model associated with the\n        :attr:`~django.views.generic.detail.SingleObjectMixin.queryset`, or\n        with the :attr:`~django.views.generic.detail.SingleObjectMixin.model`,\n        depending on which attribute is provided.\n\n    .. method:: get_form_kwargs()\n\n        Add the current instance (``self.object``) to the standard\n        :meth:`~django.views.generic.edit.FormMixin.get_form_kwargs`.\n\n    .. method:: get_success_url()\n\n        Determine the URL to redirect to when the form is successfully\n        validated. Returns\n        :attr:`django.views.generic.edit.ModelFormMixin.success_url` if it is\n        provided; otherwise, attempts to use the ``get_absolute_url()`` of the\n        object.\n\n    .. method:: form_valid(form)\n\n        Saves the form instance, sets the current object for the view, and\n        redirects to\n        :meth:`~django.views.generic.edit.FormMixin.get_success_url`.\n\n    .. method:: form_invalid(form)\n\n        Renders a response, providing the invalid form as context.\n\n\n``ProcessFormView``\n===================\n\n.. class:: django.views.generic.edit.ProcessFormView\n\n    A mixin that provides basic HTTP GET and POST workflow.\n\n    .. note::\n\n        This is named 'ProcessFormView' and inherits directly from\n        :class:`django.views.generic.base.View`, but breaks if used\n        independently, so it is more of a mixin.\n\n    **Extends**\n\n    * :class:`django.views.generic.base.View`\n\n    **Methods and Attributes**\n\n    .. method:: get(request, *args, **kwargs)\n\n        Renders a response using a context created with\n        :meth:`~django.views.generic.edit.FormMixin.get_context_data`.\n\n    .. method:: post(request, *args, **kwargs)\n\n        Constructs a form, checks the form for validity, and handles it\n        accordingly.\n\n    .. method:: put(*args, **kwargs)\n\n        The ``PUT`` action is also handled and passes all parameters through to\n        :meth:`post`.\n\n\n``DeletionMixin``\n=================\n\n.. class:: django.views.generic.edit.DeletionMixin\n\n    Enables handling of the ``DELETE`` http action.\n\n    **Methods and Attributes**\n\n    .. attribute:: success_url\n\n        The url to redirect to when the nominated object has been\n        successfully deleted.\n\n        ``success_url`` may contain dictionary string formatting, which will be\n        interpolated against the object's field attributes. For example, you\n        could use ``success_url=\"/parent/{parent_id}/\"`` to redirect to a URL\n        composed out of the ``parent_id`` field on a model.\n\n    .. method:: delete(request, *args, **kwargs)\n\n        Retrieves the target object and calls its ``delete()`` method, then\n        redirects to the success URL.\n\n    .. method:: get_success_url()\n\n        Returns the url to redirect to when the nominated object has been\n        successfully deleted. Returns\n        :attr:`~django.views.generic.edit.DeletionMixin.success_url` by\n        default.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":176,"nodeType":"TextFile","repoName":null,"name":"legacy-databases.txt","path":"docs/howto","text":"=========================================\nIntegrating Django with a legacy database\n=========================================\n\nWhile Django is best suited for developing new applications, it's quite\npossible to integrate it into legacy databases. Django includes a couple of\nutilities to automate as much of this process as possible.\n\nThis document assumes you know the Django basics, as covered in the\n:doc:`tutorial </intro/tutorial01>`.\n\nOnce you've got Django set up, you'll follow this general process to integrate\nwith an existing database.\n\nGive Django your database parameters\n====================================\n\nYou'll need to tell Django what your database connection parameters are, and\nwhat the name of the database is. Do that by editing the :setting:`DATABASES`\nsetting and assigning values to the following keys for the ``'default'``\nconnection:\n\n* :setting:`NAME`\n* :setting:`ENGINE <DATABASE-ENGINE>`\n* :setting:`USER`\n* :setting:`PASSWORD`\n* :setting:`HOST`\n* :setting:`PORT`\n\nAuto-generate the models\n========================\n\n.. highlight:: bash\n\nDjango comes with a utility called :djadmin:`inspectdb` that can create models\nby introspecting an existing database. You can view the output by running this\ncommand::\n\n    $ python manage.py inspectdb\n\nSave this as a file by using standard Unix output redirection::\n\n    $ python manage.py inspectdb > models.py\n\nThis feature is meant as a shortcut, not as definitive model generation. See the\n:djadmin:`documentation of inspectdb <inspectdb>` for more information.\n\nOnce you've cleaned up your models, name the file ``models.py`` and put it in\nthe Python package that holds your app. Then add the app to your\n:setting:`INSTALLED_APPS` setting.\n\nBy default, :djadmin:`inspectdb` creates unmanaged models. That is,\n``managed = False`` in the model's ``Meta`` class tells Django not to manage\neach table's creation, modification, and deletion::\n\n    class Person(models.Model):\n        id = models.IntegerField(primary_key=True)\n        first_name = models.CharField(max_length=70)\n        class Meta:\n           managed = False\n           db_table = 'CENSUS_PERSONS'\n\nIf you do want to allow Django to manage the table's lifecycle, you'll need to\nchange the :attr:`~django.db.models.Options.managed` option above to ``True``\n(or remove it because ``True`` is its default value).\n\nInstall the core Django tables\n==============================\n\nNext, run the :djadmin:`migrate` command to install any extra needed database\nrecords such as admin permissions and content types::\n\n    $ python manage.py migrate\n\nTest and tweak\n==============\n\nThose are the basic steps -- from here you'll want to tweak the models Django\ngenerated until they work the way you'd like. Try accessing your data via the\nDjango database API, and try editing objects via Django's admin site, and edit\nthe models file accordingly.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":177,"nodeType":"TextFile","repoName":null,"name":"api.txt","path":"docs/ref/templates","text":"====================================================\nThe Django template language: for Python programmers\n====================================================\n\n.. currentmodule:: django.template\n\nThis document explains the Django template system from a technical\nperspective -- how it works and how to extend it. If you're looking for\nreference on the language syntax, see :doc:`/ref/templates/language`.\n\nIt assumes an understanding of templates, contexts, variables, tags, and\nrendering. Start with the :ref:`introduction to the Django template language\n<template-language-intro>` if you aren't familiar with these concepts.\n\nOverview\n========\n\nUsing the template system in Python is a three-step process:\n\n1. You configure an :class:`Engine`.\n2. You compile template code into a :class:`Template`.\n3. You render the template with a :class:`Context`.\n\nDjango projects generally rely on the :ref:`high level, backend agnostic APIs\n<template-engines>` for each of these steps instead of the template system's\nlower level APIs:\n\n1. For each :class:`~django.template.backends.django.DjangoTemplates` backend\n   in the :setting:`TEMPLATES` setting, Django instantiates an\n   :class:`Engine`. :class:`~django.template.backends.django.DjangoTemplates`\n   wraps :class:`Engine` and adapts it to the common template backend API.\n2. The :mod:`django.template.loader` module provides functions such as\n   :func:`~django.template.loader.get_template` for loading templates. They\n   return a ``django.template.backends.django.Template`` which wraps the\n   actual :class:`django.template.Template`.\n3. The ``Template`` obtained in the previous step has a\n   :meth:`~django.template.backends.base.Template.render` method which\n   marshals a context and possibly a request into a :class:`Context` and\n   delegates the rendering to the underlying :class:`Template`.\n\nConfiguring an engine\n=====================\n\nIf you are using the :class:`~django.template.backends.django.DjangoTemplates`\nbackend, this probably isn't the documentation you're looking for. An instance\nof the ``Engine`` class described below is accessible using the ``engine``\nattribute of that backend and any attribute defaults mentioned below are\noverridden by what's passed by\n:class:`~django.template.backends.django.DjangoTemplates`.\n\n.. class:: Engine(dirs=None, app_dirs=False, context_processors=None, debug=False, loaders=None, string_if_invalid='', file_charset='utf-8', libraries=None, builtins=None, autoescape=True)\n\n    When instantiating an ``Engine`` all arguments must be passed as keyword\n    arguments:\n\n    * ``dirs`` is a list of directories where the engine should look for\n      template source files. It is used to configure\n      :class:`filesystem.Loader <django.template.loaders.filesystem.Loader>`.\n\n      It defaults to an empty list.\n\n    * ``app_dirs`` only affects the default value of ``loaders``. See below.\n\n      It defaults to ``False``.\n\n    * ``autoescape`` controls whether HTML autoescaping is enabled.\n\n      It defaults to ``True``.\n\n      .. warning::\n\n          Only set it to ``False`` if you're rendering non-HTML templates!\n\n    * ``context_processors`` is a list of dotted Python paths to callables\n      that are used to populate the context when a template is rendered with a\n      request. These callables take a request object as their argument and\n      return a :class:`dict` of items to be merged into the context.\n\n      It defaults to an empty list.\n\n      See :class:`~django.template.RequestContext` for more information.\n\n    * ``debug`` is a boolean that turns on/off template debug mode. If it is\n      ``True``, the template engine will store additional debug information\n      which can be used to display a detailed report for any exception raised\n      during template rendering.\n\n      It defaults to ``False``.\n\n    * ``loaders`` is a list of template loader classes, specified as strings.\n      Each ``Loader`` class knows how to import templates from a particular\n      source. Optionally, a tuple can be used instead of a string. The first\n      item in the tuple should be the ``Loader`` class name, subsequent items\n      are passed to the ``Loader`` during initialization.\n\n      It defaults to a list containing:\n\n      * ``'django.template.loaders.filesystem.Loader'``\n      * ``'django.template.loaders.app_directories.Loader'`` if and only if\n        ``app_dirs`` is ``True``.\n\n      If ``debug`` is ``False``, these loaders are wrapped in\n      :class:`django.template.loaders.cached.Loader`.\n\n      See :ref:`template-loaders` for details.\n\n    * ``string_if_invalid`` is the output, as a string, that the template\n      system should use for invalid (e.g. misspelled) variables.\n\n      It defaults to the empty string.\n\n      See :ref:`invalid-template-variables` for details.\n\n    * ``file_charset`` is the charset used to read template files on disk.\n\n      It defaults to ``'utf-8'``.\n\n    * ``'libraries'``: A dictionary of labels and dotted Python paths of template\n      tag modules to register with the template engine. This is used to add new\n      libraries or provide alternate labels for existing ones. For example::\n\n          Engine(\n              libraries={\n                  'myapp_tags': 'path.to.myapp.tags',\n                  'admin.urls': 'django.contrib.admin.templatetags.admin_urls',\n              },\n          )\n\n      Libraries can be loaded by passing the corresponding dictionary key to\n      the :ttag:`{% load %}<load>` tag.\n\n    * ``'builtins'``: A list of dotted Python paths of template tag modules to\n      add to :doc:`built-ins </ref/templates/builtins>`. For example::\n\n          Engine(\n              builtins=['myapp.builtins'],\n          )\n\n      Tags and filters from built-in libraries can be used without first calling\n      the :ttag:`{% load %}<load>` tag.\n\n.. staticmethod:: Engine.get_default()\n\n    Returns the underlying :class:`Engine` from the first configured\n    :class:`~django.template.backends.django.DjangoTemplates` engine. Raises\n    :exc:`~django.core.exceptions.ImproperlyConfigured` if no engines are\n    configured.\n\n    It's required for preserving APIs that rely on a globally available,\n    implicitly configured engine. Any other use is strongly discouraged.\n\n.. method:: Engine.from_string(template_code)\n\n    Compiles the given template code and returns a :class:`Template` object.\n\n.. method:: Engine.get_template(template_name)\n\n    Loads a template with the given name, compiles it and returns a\n    :class:`Template` object.\n\n.. method:: Engine.select_template(template_name_list)\n\n    Like :meth:`~Engine.get_template`, except it takes a list of names\n    and returns the first template that was found.\n\nLoading a template\n==================\n\nThe recommended way to create a :class:`Template` is by calling the factory\nmethods of the :class:`Engine`: :meth:`~Engine.get_template`,\n:meth:`~Engine.select_template` and :meth:`~Engine.from_string`.\n\nIn a Django project where the :setting:`TEMPLATES` setting defines a\n:class:`~django.template.backends.django.DjangoTemplates` engine, it's\npossible to instantiate a :class:`Template` directly. If more than one\n:class:`~django.template.backends.django.DjangoTemplates` engine is defined,\nthe first one will be used.\n\n.. class:: Template\n\n    This class lives at ``django.template.Template``. The constructor takes\n    one argument — the raw template code::\n\n        from django.template import Template\n\n        template = Template(\"My name is {{ my_name }}.\")\n\n.. admonition:: Behind the scenes\n\n    The system only parses your raw template code once -- when you create the\n    ``Template`` object. From then on, it's stored internally as a tree\n    structure for performance.\n\n    Even the parsing itself is quite fast. Most of the parsing happens via a\n    single call to a single, short, regular expression.\n\nRendering a context\n===================\n\nOnce you have a compiled :class:`Template` object, you can render a context\nwith it. You can reuse the same template to render it several times with\ndifferent contexts.\n\n.. class:: Context(dict_=None)\n\n    The constructor of ``django.template.Context`` takes an optional argument —\n    a dictionary mapping variable names to variable values.\n\n    For details, see :ref:`playing-with-context` below.\n\n.. method:: Template.render(context)\n\n    Call the :class:`Template` object's ``render()`` method with a\n    :class:`Context` to \"fill\" the template::\n\n        >>> from django.template import Context, Template\n        >>> template = Template(\"My name is {{ my_name }}.\")\n\n        >>> context = Context({\"my_name\": \"Adrian\"})\n        >>> template.render(context)\n        \"My name is Adrian.\"\n\n        >>> context = Context({\"my_name\": \"Dolores\"})\n        >>> template.render(context)\n        \"My name is Dolores.\"\n\nVariables and lookups\n---------------------\n\nVariable names must consist of any letter (A-Z), any digit (0-9), an underscore\n(but they must not start with an underscore) or a dot.\n\nDots have a special meaning in template rendering. A dot in a variable name\nsignifies a **lookup**. Specifically, when the template system encounters a\ndot in a variable name, it tries the following lookups, in this order:\n\n* Dictionary lookup. Example: ``foo[\"bar\"]``\n* Attribute lookup. Example: ``foo.bar``\n* List-index lookup. Example: ``foo[bar]``\n\nNote that \"bar\" in a template expression like ``{{ foo.bar }}`` will be\ninterpreted as a literal string and not using the value of the variable \"bar\",\nif one exists in the template context.\n\nThe template system uses the first lookup type that works. It's short-circuit\nlogic. Here are a few examples::\n\n    >>> from django.template import Context, Template\n    >>> t = Template(\"My name is {{ person.first_name }}.\")\n    >>> d = {\"person\": {\"first_name\": \"Joe\", \"last_name\": \"Johnson\"}}\n    >>> t.render(Context(d))\n    \"My name is Joe.\"\n\n    >>> class PersonClass: pass\n    >>> p = PersonClass()\n    >>> p.first_name = \"Ron\"\n    >>> p.last_name = \"Nasty\"\n    >>> t.render(Context({\"person\": p}))\n    \"My name is Ron.\"\n\n    >>> t = Template(\"The first stooge in the list is {{ stooges.0 }}.\")\n    >>> c = Context({\"stooges\": [\"Larry\", \"Curly\", \"Moe\"]})\n    >>> t.render(c)\n    \"The first stooge in the list is Larry.\"\n\nIf any part of the variable is callable, the template system will try calling\nit. Example::\n\n    >>> class PersonClass2:\n    ...     def name(self):\n    ...         return \"Samantha\"\n    >>> t = Template(\"My name is {{ person.name }}.\")\n    >>> t.render(Context({\"person\": PersonClass2}))\n    \"My name is Samantha.\"\n\nCallable variables are slightly more complex than variables which only require\nstraight lookups. Here are some things to keep in mind:\n\n* If the variable raises an exception when called, the exception will be\n  propagated, unless the exception has an attribute\n  ``silent_variable_failure`` whose value is ``True``. If the exception\n  *does* have a ``silent_variable_failure`` attribute whose value is\n  ``True``, the variable will render as the value of the engine's\n  ``string_if_invalid`` configuration option (an empty string, by default).\n  Example::\n\n    >>> t = Template(\"My name is {{ person.first_name }}.\")\n    >>> class PersonClass3:\n    ...     def first_name(self):\n    ...         raise AssertionError(\"foo\")\n    >>> p = PersonClass3()\n    >>> t.render(Context({\"person\": p}))\n    Traceback (most recent call last):\n    ...\n    AssertionError: foo\n\n    >>> class SilentAssertionError(Exception):\n    ...     silent_variable_failure = True\n    >>> class PersonClass4:\n    ...     def first_name(self):\n    ...         raise SilentAssertionError\n    >>> p = PersonClass4()\n    >>> t.render(Context({\"person\": p}))\n    \"My name is .\"\n\n  Note that :exc:`django.core.exceptions.ObjectDoesNotExist`, which is the\n  base class for all Django database API ``DoesNotExist`` exceptions, has\n  ``silent_variable_failure = True``. So if you're using Django templates\n  with Django model objects, any ``DoesNotExist`` exception will fail\n  silently.\n\n* A variable can only be called if it has no required arguments. Otherwise,\n  the system will return the value of the engine's ``string_if_invalid``\n  option.\n\n.. _alters-data-description:\n\n* There can be side effects when calling some variables, and it'd be either\n  foolish or a security hole to allow the template system to access them.\n\n  A good example is the :meth:`~django.db.models.Model.delete` method on\n  each Django model object. The template system shouldn't be allowed to do\n  something like this::\n\n    I will now delete this valuable data. {{ data.delete }}\n\n  To prevent this, set an ``alters_data`` attribute on the callable\n  variable. The template system won't call a variable if it has\n  ``alters_data=True`` set, and will instead replace the variable with\n  ``string_if_invalid``, unconditionally.  The\n  dynamically-generated :meth:`~django.db.models.Model.delete` and\n  :meth:`~django.db.models.Model.save` methods on Django model objects get\n  ``alters_data=True`` automatically. Example::\n\n    def sensitive_function(self):\n        self.database_record.delete()\n    sensitive_function.alters_data = True\n\n* Occasionally you may want to turn off this feature for other reasons,\n  and tell the template system to leave a variable uncalled no matter\n  what.  To do so, set a ``do_not_call_in_templates`` attribute on the\n  callable with the value ``True``.  The template system then will act as\n  if your variable is not callable (allowing you to access attributes of\n  the callable, for example).\n\n.. _invalid-template-variables:\n\nHow invalid variables are handled\n---------------------------------\n\nGenerally, if a variable doesn't exist, the template system inserts the value\nof the engine's ``string_if_invalid`` configuration option, which is set to\n``''`` (the empty string) by default.\n\nFilters that are applied to an invalid variable will only be applied if\n``string_if_invalid`` is set to ``''`` (the empty string). If\n``string_if_invalid`` is set to any other value, variable filters will be\nignored.\n\nThis behavior is slightly different for the ``if``, ``for`` and ``regroup``\ntemplate tags. If an invalid variable is provided to one of these template\ntags, the variable will be interpreted as ``None``. Filters are always\napplied to invalid variables within these template tags.\n\nIf ``string_if_invalid`` contains a ``'%s'``, the format marker will be\nreplaced with the name of the invalid variable.\n\n.. admonition:: For debug purposes only!\n\n    While ``string_if_invalid`` can be a useful debugging tool, it is a bad\n    idea to turn it on as a 'development default'.\n\n    Many templates, including some of Django's, rely upon the silence of the\n    template system when a nonexistent variable is encountered. If you assign a\n    value other than ``''`` to ``string_if_invalid``, you will experience\n    rendering problems with these templates and sites.\n\n    Generally, ``string_if_invalid`` should only be enabled in order to debug\n    a specific template problem, then cleared once debugging is complete.\n\nBuilt-in variables\n------------------\n\nEvery context contains ``True``, ``False`` and ``None``. As you would expect,\nthese variables resolve to the corresponding Python objects.\n\nLimitations with string literals\n--------------------------------\n\nDjango's template language has no way to escape the characters used for its own\nsyntax. For example, the :ttag:`templatetag` tag is required if you need to\noutput character sequences like ``{%`` and ``%}``.\n\nA similar issue exists if you want to include these sequences in template filter\nor tag arguments. For example, when parsing a block tag, Django's template\nparser looks for the first occurrence of ``%}`` after a ``{%``. This prevents\nthe use of ``\"%}\"`` as a string literal. For example, a ``TemplateSyntaxError``\nwill be raised for the following expressions::\n\n  {% include \"template.html\" tvar=\"Some string literal with %} in it.\" %}\n\n  {% with tvar=\"Some string literal with %} in it.\" %}{% endwith %}\n\nThe same issue can be triggered by using a reserved sequence in filter\narguments::\n\n  {{ some.variable|default:\"}}\" }}\n\nIf you need to use strings with these sequences, store them in template\nvariables or use a custom template tag or filter to workaround the limitation.\n\n.. _playing-with-context:\n\nPlaying with ``Context`` objects\n================================\n\nMost of the time, you'll instantiate :class:`Context` objects by passing in a\nfully-populated dictionary to ``Context()``. But you can add and delete items\nfrom a ``Context`` object once it's been instantiated, too, using standard\ndictionary syntax::\n\n    >>> from django.template import Context\n    >>> c = Context({\"foo\": \"bar\"})\n    >>> c['foo']\n    'bar'\n    >>> del c['foo']\n    >>> c['foo']\n    Traceback (most recent call last):\n    ...\n    KeyError: 'foo'\n    >>> c['newvariable'] = 'hello'\n    >>> c['newvariable']\n    'hello'\n\n.. method:: Context.get(key, otherwise=None)\n\n    Returns the value for ``key`` if ``key`` is in the context, else returns\n    ``otherwise``.\n\n.. method:: Context.setdefault(key, default=None)\n\n    If ``key`` is in the context, returns its value. Otherwise inserts ``key``\n    with a value of ``default`` and returns ``default``.\n\n.. method:: Context.pop()\n.. method:: Context.push()\n.. exception:: ContextPopException\n\nA ``Context`` object is a stack. That is, you can ``push()`` and ``pop()`` it.\nIf you ``pop()`` too much, it'll raise\n``django.template.ContextPopException``::\n\n    >>> c = Context()\n    >>> c['foo'] = 'first level'\n    >>> c.push()\n    {}\n    >>> c['foo'] = 'second level'\n    >>> c['foo']\n    'second level'\n    >>> c.pop()\n    {'foo': 'second level'}\n    >>> c['foo']\n    'first level'\n    >>> c['foo'] = 'overwritten'\n    >>> c['foo']\n    'overwritten'\n    >>> c.pop()\n    Traceback (most recent call last):\n    ...\n    ContextPopException\n\nYou can also use ``push()`` as a context manager to ensure a matching ``pop()``\nis called.\n\n    >>> c = Context()\n    >>> c['foo'] = 'first level'\n    >>> with c.push():\n    ...     c['foo'] = 'second level'\n    ...     c['foo']\n    'second level'\n    >>> c['foo']\n    'first level'\n\nAll arguments passed to ``push()`` will be passed to the ``dict`` constructor\nused to build the new context level.\n\n    >>> c = Context()\n    >>> c['foo'] = 'first level'\n    >>> with c.push(foo='second level'):\n    ...     c['foo']\n    'second level'\n    >>> c['foo']\n    'first level'\n\n.. method:: Context.update(other_dict)\n\nIn addition to ``push()`` and ``pop()``, the ``Context``\nobject also defines an ``update()`` method. This works like ``push()``\nbut takes a dictionary as an argument and pushes that dictionary onto\nthe stack instead of an empty one.\n\n    >>> c = Context()\n    >>> c['foo'] = 'first level'\n    >>> c.update({'foo': 'updated'})\n    {'foo': 'updated'}\n    >>> c['foo']\n    'updated'\n    >>> c.pop()\n    {'foo': 'updated'}\n    >>> c['foo']\n    'first level'\n\nLike ``push()``, you can use ``update()`` as a context manager to ensure a\nmatching ``pop()`` is called.\n\n    >>> c = Context()\n    >>> c['foo'] = 'first level'\n    >>> with c.update({'foo': 'second level'}):\n    ...     c['foo']\n    'second level'\n    >>> c['foo']\n    'first level'\n\nUsing a ``Context`` as a stack comes in handy in :ref:`some custom template\ntags <howto-writing-custom-template-tags>`.\n\n.. method:: Context.flatten()\n\nUsing ``flatten()`` method you can get whole ``Context`` stack as one dictionary\nincluding builtin variables.\n\n    >>> c = Context()\n    >>> c['foo'] = 'first level'\n    >>> c.update({'bar': 'second level'})\n    {'bar': 'second level'}\n    >>> c.flatten()\n    {'True': True, 'None': None, 'foo': 'first level', 'False': False, 'bar': 'second level'}\n\nA ``flatten()`` method is also internally used to make ``Context`` objects comparable.\n\n    >>> c1 = Context()\n    >>> c1['foo'] = 'first level'\n    >>> c1['bar'] = 'second level'\n    >>> c2 = Context()\n    >>> c2.update({'bar': 'second level', 'foo': 'first level'})\n    {'foo': 'first level', 'bar': 'second level'}\n    >>> c1 == c2\n    True\n\nResult from ``flatten()`` can be useful in unit tests to compare ``Context``\nagainst ``dict``::\n\n    class ContextTest(unittest.TestCase):\n        def test_against_dictionary(self):\n            c1 = Context()\n            c1['update'] = 'value'\n            self.assertEqual(c1.flatten(), {\n                'True': True,\n                'None': None,\n                'False': False,\n                'update': 'value',\n            })\n\n.. _subclassing-context-requestcontext:\n\nUsing ``RequestContext``\n------------------------\n\n.. class:: RequestContext(request, dict_=None, processors=None)\n\nDjango comes with a special ``Context`` class,\n``django.template.RequestContext``, that acts slightly differently from the\nnormal ``django.template.Context``. The first difference is that it takes an\n:class:`~django.http.HttpRequest` as its first argument. For example::\n\n    c = RequestContext(request, {\n        'foo': 'bar',\n    })\n\nThe second difference is that it automatically populates the context with a\nfew variables, according to the engine's ``context_processors`` configuration\noption.\n\nThe ``context_processors`` option is a list of callables -- called **context\nprocessors** -- that take a request object as their argument and return a\ndictionary of items to be merged into the context. In the default generated\nsettings file, the default template engine contains the following context\nprocessors::\n\n    [\n        'django.template.context_processors.debug',\n        'django.template.context_processors.request',\n        'django.contrib.auth.context_processors.auth',\n        'django.contrib.messages.context_processors.messages',\n    ]\n\nIn addition to these, :class:`RequestContext` always enables\n``'django.template.context_processors.csrf'``.  This is a security related\ncontext processor required by the admin and other contrib apps, and, in case\nof accidental misconfiguration, it is deliberately hardcoded in and cannot be\nturned off in the ``context_processors`` option.\n\nEach processor is applied in order. That means, if one processor adds a\nvariable to the context and a second processor adds a variable with the same\nname, the second will override the first. The default processors are explained\nbelow.\n\n.. admonition:: When context processors are applied\n\n    Context processors are applied on top of context data. This means that a\n    context processor may overwrite variables you've supplied to your\n    :class:`Context` or :class:`RequestContext`, so take care to avoid\n    variable names that overlap with those supplied by your context\n    processors.\n\n    If you want context data to take priority over context processors, use the\n    following pattern::\n\n        from django.template import RequestContext\n\n        request_context = RequestContext(request)\n        request_context.push({\"my_name\": \"Adrian\"})\n\n    Django does this to allow context data to override context processors in\n    APIs such as :func:`~django.shortcuts.render` and\n    :class:`~django.template.response.TemplateResponse`.\n\nAlso, you can give :class:`RequestContext` a list of additional processors,\nusing the optional, third positional argument, ``processors``. In this\nexample, the :class:`RequestContext` instance gets an ``ip_address`` variable::\n\n    from django.http import HttpResponse\n    from django.template import RequestContext, Template\n\n    def ip_address_processor(request):\n        return {'ip_address': request.META['REMOTE_ADDR']}\n\n    def client_ip_view(request):\n        template = Template('{{ title }}: {{ ip_address }}')\n        context = RequestContext(request, {\n            'title': 'Your IP Address',\n        }, [ip_address_processor])\n        return HttpResponse(template.render(context))\n\n.. _context-processors:\n\nBuilt-in template context processors\n------------------------------------\n\nHere's what each of the built-in processors does:\n\n.. currentmodule:: django.contrib.auth.context_processors\n\n``django.contrib.auth.context_processors.auth``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. function:: auth\n\nIf this processor is enabled, every ``RequestContext`` will contain these\nvariables:\n\n* ``user`` -- An ``auth.User`` instance representing the currently\n  logged-in user (or an ``AnonymousUser`` instance, if the client isn't\n  logged in).\n\n* ``perms`` -- An instance of\n  ``django.contrib.auth.context_processors.PermWrapper``, representing the\n  permissions that the currently logged-in user has.\n\n.. currentmodule:: django.template.context_processors\n\n``django.template.context_processors.debug``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. function:: debug\n\nIf this processor is enabled, every ``RequestContext`` will contain these two\nvariables -- but only if your :setting:`DEBUG` setting is set to ``True`` and\nthe request's IP address (``request.META['REMOTE_ADDR']``) is in the\n:setting:`INTERNAL_IPS` setting:\n\n* ``debug`` -- ``True``. You can use this in templates to test whether\n  you're in :setting:`DEBUG` mode.\n* ``sql_queries`` -- A list of ``{'sql': ..., 'time': ...}`` dictionaries,\n  representing every SQL query that has happened so far during the request\n  and how long it took. The list is in order by database alias and then by\n  query. It's lazily generated on access.\n\n``django.template.context_processors.i18n``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. function:: i18n\n\nIf this processor is enabled, every ``RequestContext`` will contain these\nvariables:\n\n* ``LANGUAGES`` -- The value of the :setting:`LANGUAGES` setting.\n* ``LANGUAGE_BIDI`` -- ``True`` if the current language is a right-to-left\n  language, e.g. Hebrew, Arabic. ``False`` if it's a left-to-right language,\n  e.g. English, French, German.\n* ``LANGUAGE_CODE`` -- ``request.LANGUAGE_CODE``, if it exists. Otherwise,\n  the value of the :setting:`LANGUAGE_CODE` setting.\n\nSee :ref:`i18n template tags <i18n-template-tags>` for template tags that\ngenerate the same values.\n\n``django.template.context_processors.media``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf this processor is enabled, every ``RequestContext`` will contain a variable\n``MEDIA_URL``, providing the value of the :setting:`MEDIA_URL` setting.\n\n``django.template.context_processors.static``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. function:: static\n\nIf this processor is enabled, every ``RequestContext`` will contain a variable\n``STATIC_URL``, providing the value of the :setting:`STATIC_URL` setting.\n\n``django.template.context_processors.csrf``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThis processor adds a token that is needed by the :ttag:`csrf_token` template\ntag for protection against :doc:`Cross Site Request Forgeries\n</ref/csrf>`.\n\n``django.template.context_processors.request``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf this processor is enabled, every ``RequestContext`` will contain a variable\n``request``, which is the current :class:`~django.http.HttpRequest`.\n\n``django.template.context_processors.tz``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. function:: tz\n\nIf this processor is enabled, every ``RequestContext`` will contain a variable\n``TIME_ZONE``, providing the name of the currently active time zone.\n\n``django.contrib.messages.context_processors.messages``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf this processor is enabled, every ``RequestContext`` will contain these two\nvariables:\n\n* ``messages`` -- A list of messages (as strings) that have been set\n  via the :doc:`messages framework </ref/contrib/messages>`.\n* ``DEFAULT_MESSAGE_LEVELS`` -- A mapping of the message level names to\n  :ref:`their numeric value <message-level-constants>`.\n\nWriting your own context processors\n-----------------------------------\n\nA context processor has a simple interface: It's a Python function that takes\none argument, an :class:`~django.http.HttpRequest` object, and returns a\ndictionary that gets added to the template context. Each context processor\n*must* return a dictionary.\n\nCustom context processors can live anywhere in your code base. All Django\ncares about is that your custom context processors are pointed to by the\n``'context_processors'`` option in your :setting:`TEMPLATES` setting — or the\n``context_processors`` argument of :class:`~django.template.Engine` if you're\nusing it directly.\n\nLoading templates\n=================\n\nGenerally, you'll store templates in files on your filesystem rather than\nusing the low-level :class:`~django.template.Template` API yourself. Save\ntemplates in a directory specified as a **template directory**.\n\nDjango searches for template directories in a number of places, depending on\nyour template loading settings (see \"Loader types\" below), but the most basic\nway of specifying template directories is by using the :setting:`DIRS\n<TEMPLATES-DIRS>` option.\n\nThe :setting:`DIRS <TEMPLATES-DIRS>` option\n-------------------------------------------\n\nTell Django what your template directories are by using the :setting:`DIRS\n<TEMPLATES-DIRS>` option in the :setting:`TEMPLATES` setting in your settings\nfile — or the ``dirs`` argument of :class:`~django.template.Engine`. This\nshould be set to a list of strings that contain full paths to your template\ndirectories::\n\n    TEMPLATES = [\n        {\n            'BACKEND': 'django.template.backends.django.DjangoTemplates',\n            'DIRS': [\n                '/home/html/templates/lawrence.com',\n                '/home/html/templates/default',\n            ],\n        },\n    ]\n\nYour templates can go anywhere you want, as long as the directories and\ntemplates are readable by the Web server. They can have any extension you want,\nsuch as ``.html`` or ``.txt``, or they can have no extension at all.\n\nNote that these paths should use Unix-style forward slashes, even on Windows.\n\n.. _template-loaders:\n\nLoader types\n------------\n\nBy default, Django uses a filesystem-based template loader, but Django comes\nwith a few other template loaders, which know how to load templates from other\nsources.\n\nSome of these other loaders are disabled by default, but you can activate them\nby adding a ``'loaders'`` option to your ``DjangoTemplates`` backend in the\n:setting:`TEMPLATES` setting or passing a ``loaders`` argument to\n:class:`~django.template.Engine`. ``loaders`` should be a list of strings or\ntuples, where each represents a template loader class. Here are the template\nloaders that come with Django:\n\n.. currentmodule:: django.template.loaders\n\n``django.template.loaders.filesystem.Loader``\n\n.. class:: filesystem.Loader\n\n    Loads templates from the filesystem, according to\n    :setting:`DIRS <TEMPLATES-DIRS>`.\n\n    This loader is enabled by default. However it won't find any templates\n    until you set :setting:`DIRS <TEMPLATES-DIRS>` to a non-empty list::\n\n        TEMPLATES = [{\n            'BACKEND': 'django.template.backends.django.DjangoTemplates',\n            'DIRS': [BASE_DIR / 'templates'],\n        }]\n\n    You can also override ``'DIRS'`` and specify specific directories for a\n    particular filesystem loader::\n\n        TEMPLATES = [{\n            'BACKEND': 'django.template.backends.django.DjangoTemplates',\n            'OPTIONS': {\n                'loaders': [\n                    (\n                        'django.template.loaders.filesystem.Loader',\n                        [BASE_DIR / 'templates'],\n                    ),\n                ],\n            },\n        }]\n\n``django.template.loaders.app_directories.Loader``\n\n.. class:: app_directories.Loader\n\n    Loads templates from Django apps on the filesystem. For each app in\n    :setting:`INSTALLED_APPS`, the loader looks for a ``templates``\n    subdirectory. If the directory exists, Django looks for templates in there.\n\n    This means you can store templates with your individual apps. This also\n    helps to distribute Django apps with default templates.\n\n    For example, for this setting::\n\n        INSTALLED_APPS = ['myproject.polls', 'myproject.music']\n\n    ...then ``get_template('foo.html')`` will look for ``foo.html`` in these\n    directories, in this order:\n\n    * ``/path/to/myproject/polls/templates/``\n    * ``/path/to/myproject/music/templates/``\n\n    ... and will use the one it finds first.\n\n    The order of :setting:`INSTALLED_APPS` is significant! For example, if you\n    want to customize the Django admin, you might choose to override the\n    standard ``admin/base_site.html`` template, from ``django.contrib.admin``,\n    with your own ``admin/base_site.html`` in ``myproject.polls``. You must\n    then make sure that your ``myproject.polls`` comes *before*\n    ``django.contrib.admin`` in :setting:`INSTALLED_APPS`, otherwise\n    ``django.contrib.admin``’s will be loaded first and yours will be ignored.\n\n    Note that the loader performs an optimization when it first runs:\n    it caches a list of which :setting:`INSTALLED_APPS` packages have a\n    ``templates`` subdirectory.\n\n    You can enable this loader by setting :setting:`APP_DIRS\n    <TEMPLATES-APP_DIRS>` to ``True``::\n\n        TEMPLATES = [{\n            'BACKEND': 'django.template.backends.django.DjangoTemplates',\n            'APP_DIRS': True,\n        }]\n\n``django.template.loaders.cached.Loader``\n\n.. class:: cached.Loader\n\n    By default (when :setting:`DEBUG` is ``True``), the template system reads\n    and compiles your templates every time they're rendered. While the Django\n    template system is quite fast, the overhead from reading and compiling\n    templates can add up.\n\n    You configure the cached template loader with a list of other loaders that\n    it should wrap. The wrapped loaders are used to locate unknown templates\n    when they're first encountered. The cached loader then stores the compiled\n    ``Template`` in memory. The cached ``Template`` instance is returned for\n    subsequent requests to load the same template.\n\n    This loader is automatically enabled if :setting:`OPTIONS['loaders']\n    <TEMPLATES-OPTIONS>` isn't specified and :setting:`OPTIONS['debug']\n    <TEMPLATES-OPTIONS>` is ``False`` (the latter option defaults to the value\n    of :setting:`DEBUG`).\n\n    You can also enable template caching with some custom template loaders\n    using settings like this::\n\n        TEMPLATES = [{\n            'BACKEND': 'django.template.backends.django.DjangoTemplates',\n            'DIRS': [BASE_DIR / 'templates'],\n            'OPTIONS': {\n                'loaders': [\n                    ('django.template.loaders.cached.Loader', [\n                        'django.template.loaders.filesystem.Loader',\n                        'django.template.loaders.app_directories.Loader',\n                        'path.to.custom.Loader',\n                    ]),\n                ],\n            },\n        }]\n\n    .. note::\n\n        All of the built-in Django template tags are safe to use with the\n        cached loader, but if you're using custom template tags that come from\n        third party packages, or that you wrote yourself, you should ensure\n        that the ``Node`` implementation for each tag is thread-safe. For more\n        information, see :ref:`template tag thread safety considerations\n        <template_tag_thread_safety>`.\n\n``django.template.loaders.locmem.Loader``\n\n.. class:: locmem.Loader\n\n    Loads templates from a Python dictionary. This is useful for testing.\n\n    This loader takes a dictionary of templates as its first argument::\n\n        TEMPLATES = [{\n            'BACKEND': 'django.template.backends.django.DjangoTemplates',\n            'OPTIONS': {\n                'loaders': [\n                    ('django.template.loaders.locmem.Loader', {\n                        'index.html': 'content here',\n                    }),\n                ],\n            },\n        }]\n\n    This loader is disabled by default.\n\nDjango uses the template loaders in order according to the ``'loaders'``\noption. It uses each loader until a loader finds a match.\n\n.. _custom-template-loaders:\n\n.. currentmodule:: django.template.loaders.base\n\nCustom loaders\n==============\n\nIt's possible to load templates from additional sources using custom template\nloaders. Custom ``Loader`` classes should inherit from\n``django.template.loaders.base.Loader`` and define the ``get_contents()`` and\n``get_template_sources()`` methods.\n\nLoader methods\n--------------\n\n.. class:: Loader\n\n    Loads templates from a given source, such as the filesystem or a database.\n\n    .. method:: get_template_sources(template_name)\n\n        A method that takes a ``template_name`` and yields\n        :class:`~django.template.base.Origin` instances for each possible\n        source.\n\n        For example, the filesystem loader may receive ``'index.html'`` as a\n        ``template_name`` argument.  This method would yield origins for the\n        full path of ``index.html`` as it appears in each template directory\n        the loader looks at.\n\n        The method doesn't need to verify that the template exists at a given\n        path, but it should ensure the path is valid. For instance, the\n        filesystem loader makes sure the path lies under a valid template\n        directory.\n\n    .. method:: get_contents(origin)\n\n        Returns the contents for a template given a\n        :class:`~django.template.base.Origin` instance.\n\n        This is where a filesystem loader would read contents from the\n        filesystem, or a database loader would read from the database. If a\n        matching template doesn't exist, this should raise a\n        :exc:`~django.template.TemplateDoesNotExist` error.\n\n    .. method:: get_template(template_name, skip=None)\n\n        Returns a ``Template`` object for a given ``template_name`` by looping\n        through results from :meth:`get_template_sources` and calling\n        :meth:`get_contents`. This returns the first matching template. If no\n        template is found, :exc:`~django.template.TemplateDoesNotExist` is\n        raised.\n\n        The optional ``skip`` argument is a list of origins to ignore when\n        extending templates. This allow templates to extend other templates of\n        the same name. It also used to avoid recursion errors.\n\n        In general, it is enough to define :meth:`get_template_sources` and\n        :meth:`get_contents` for custom template loaders. ``get_template()``\n        will usually not need to be overridden.\n\n.. admonition:: Building your own\n\n    For examples, read the :source:`source code for Django's built-in loaders\n    <django/template/loaders>`.\n\n.. currentmodule:: django.template.base\n\nTemplate origin\n===============\n\nTemplates have an ``origin`` containing attributes depending on the source\nthey are loaded from.\n\n.. class:: Origin(name, template_name=None, loader=None)\n\n    .. attribute:: name\n\n        The path to the template as returned by the template loader.\n        For loaders that read from the file system, this is the full\n        path to the template.\n\n        If the template is instantiated directly rather than through a\n        template loader, this is a string value of ``<unknown_source>``.\n\n    .. attribute:: template_name\n\n        The relative path to the template as passed into the\n        template loader.\n\n        If the template is instantiated directly rather than through a\n        template loader, this is ``None``.\n\n    .. attribute:: loader\n\n        The template loader instance that constructed this ``Origin``.\n\n        If the template is instantiated directly rather than through a\n        template loader, this is ``None``.\n\n        :class:`django.template.loaders.cached.Loader` requires all of its\n        wrapped loaders to set this attribute, typically by instantiating\n        the ``Origin`` with ``loader=self``.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":178,"nodeType":"TextFile","repoName":null,"name":"mixins-single-object.txt","path":"docs/ref/class-based-views","text":"====================\nSingle object mixins\n====================\n\n``SingleObjectMixin``\n=====================\n\n.. class:: django.views.generic.detail.SingleObjectMixin\n\n    Provides a mechanism for looking up an object associated with the\n    current HTTP request.\n\n    **Methods and Attributes**\n\n    .. attribute:: model\n\n        The model that this view will display data for. Specifying ``model\n        = Foo`` is effectively the same as specifying ``queryset =\n        Foo.objects.all()``, where ``objects`` stands for ``Foo``’s\n        :ref:`default manager <default-managers>`.\n\n    .. attribute:: queryset\n\n        A ``QuerySet`` that represents the objects. If provided, the value of\n        ``queryset`` supersedes the value provided for :attr:`model`.\n\n        .. warning::\n\n            ``queryset`` is a class attribute with a *mutable* value so care\n            must be taken when using it directly. Before using it, either call\n            its :meth:`~django.db.models.query.QuerySet.all` method or\n            retrieve it with :meth:`get_queryset` which takes care of the\n            cloning behind the scenes.\n\n    .. attribute:: slug_field\n\n        The name of the field on the model that contains the slug. By default,\n        ``slug_field`` is ``'slug'``.\n\n    .. attribute:: slug_url_kwarg\n\n        The name of the URLConf keyword argument that contains the slug. By\n        default, ``slug_url_kwarg`` is ``'slug'``.\n\n    .. attribute:: pk_url_kwarg\n\n        The name of the URLConf keyword argument that contains the primary key.\n        By default, ``pk_url_kwarg`` is ``'pk'``.\n\n    .. attribute:: context_object_name\n\n        Designates the name of the variable to use in the context.\n\n    .. attribute:: query_pk_and_slug\n\n        If ``True``, causes :meth:`get_object()` to perform its lookup using\n        both the primary key and the slug. Defaults to ``False``.\n\n        This attribute can help mitigate `insecure direct object reference`_\n        attacks. When applications allow access to individual objects by a\n        sequential primary key, an attacker could brute-force guess all URLs;\n        thereby obtaining a list of all objects in the application. If users\n        with access to individual objects should be prevented from obtaining\n        this list, setting ``query_pk_and_slug`` to ``True`` will help prevent\n        the guessing of URLs as each URL will require two correct,\n        non-sequential arguments. Using a unique slug may serve the same\n        purpose, but this scheme allows you to have non-unique slugs.\n\n        .. _insecure direct object reference: https://www.owasp.org/index.php/Top_10_2013-A4-Insecure_Direct_Object_References\n\n    .. method:: get_object(queryset=None)\n\n        Returns the single object that this view will display. If ``queryset``\n        is provided, that queryset will be used as the source of objects;\n        otherwise, :meth:`get_queryset` will be used. ``get_object()`` looks\n        for a :attr:`pk_url_kwarg` argument in the arguments to the view; if\n        this argument is found, this method performs a primary-key based lookup\n        using that value. If this argument is not found, it looks for a\n        :attr:`slug_url_kwarg` argument, and performs a slug lookup using the\n        :attr:`slug_field`.\n\n        When :attr:`query_pk_and_slug` is ``True``, ``get_object()`` will\n        perform its lookup using both the primary key and the slug.\n\n    .. method:: get_queryset()\n\n        Returns the queryset that will be used to retrieve the object that\n        this view will display. By default, :meth:`get_queryset` returns the\n        value of the :attr:`queryset` attribute if it is set, otherwise\n        it constructs a :class:`~django.db.models.query.QuerySet` by calling\n        the ``all()`` method on the :attr:`model` attribute's default manager.\n\n    .. method:: get_context_object_name(obj)\n\n        Return the context variable name that will be used to contain the\n        data that this view is manipulating. If :attr:`context_object_name` is\n        not set, the context name will be constructed from the ``model_name``\n        of the model that the queryset is composed from. For example, the model\n        ``Article`` would have context object named ``'article'``.\n\n    .. method:: get_context_data(**kwargs)\n\n        Returns context data for displaying the object.\n\n        The base implementation of this method requires that the ``self.object``\n        attribute be set by the view (even if ``None``). Be sure to do this if\n        you are using this mixin without one of the built-in views that does so.\n\n        It returns a dictionary with these contents:\n\n        * ``object``: The object that this view is displaying\n          (``self.object``).\n        * ``context_object_name``: ``self.object`` will also be stored under\n          the name returned by :meth:`get_context_object_name`, which defaults\n          to the lowercased version of the model name.\n\n        .. admonition:: Context variables override values from template context processors\n\n            Any variables from :meth:`get_context_data` take precedence over\n            context variables from :ref:`context processors\n            <subclassing-context-requestcontext>`. For example, if your view\n            sets the :attr:`model` attribute to\n            :class:`~django.contrib.auth.models.User`, the default context\n            object name of ``user`` would override the ``user`` variable from\n            the :func:`django.contrib.auth.context_processors.auth` context\n            processor. Use :meth:`get_context_object_name` to avoid a clash.\n\n    .. method:: get_slug_field()\n\n        Returns the name of a slug field to be used to look up by slug. By\n        default this returns the value of :attr:`slug_field`.\n\n\n``SingleObjectTemplateResponseMixin``\n=====================================\n\n.. class:: django.views.generic.detail.SingleObjectTemplateResponseMixin\n\n    A mixin class that performs template-based response rendering for views\n    that operate upon a single object instance. Requires that the view it is\n    mixed with provides ``self.object``, the object instance that the view is\n    operating on. ``self.object`` will usually be, but is not required to be,\n    an instance of a Django model. It may be ``None`` if the view is in the\n    process of constructing a new instance.\n\n    **Extends**\n\n    * :class:`~django.views.generic.base.TemplateResponseMixin`\n\n    **Methods and Attributes**\n\n    .. attribute:: template_name_field\n\n        The field on the current object instance that can be used to determine\n        the name of a candidate template. If either ``template_name_field``\n        itself or the value of the ``template_name_field`` on the current\n        object instance is ``None``, the object will not be used for a\n        candidate template name.\n\n    .. attribute:: template_name_suffix\n\n        The suffix to append to the auto-generated candidate template name.\n        Default suffix is ``_detail``.\n\n    .. method:: get_template_names()\n\n        Returns a list of candidate template names. Returns the following list:\n\n        * the value of ``template_name`` on the view (if provided)\n        * the contents of the ``template_name_field`` field on the\n          object instance that the view is operating upon (if available)\n        * ``<app_label>/<model_name><template_name_suffix>.html``\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":179,"nodeType":"TextFile","repoName":null,"name":"outputting-csv.txt","path":"docs/howto","text":"==========================\nOutputting CSV with Django\n==========================\n\nThis document explains how to output CSV (Comma Separated Values) dynamically\nusing Django views. To do this, you can either use the Python CSV library or the\nDjango template system.\n\nUsing the Python CSV library\n============================\n\nPython comes with a CSV library, :mod:`csv`. The key to using it with Django is\nthat the :mod:`csv` module's CSV-creation capability acts on file-like objects,\nand Django's :class:`~django.http.HttpResponse` objects are file-like objects.\n\nHere's an example::\n\n    import csv\n    from django.http import HttpResponse\n\n    def some_view(request):\n        # Create the HttpResponse object with the appropriate CSV header.\n        response = HttpResponse(content_type='text/csv')\n        response['Content-Disposition'] = 'attachment; filename=\"somefilename.csv\"'\n\n        writer = csv.writer(response)\n        writer.writerow(['First row', 'Foo', 'Bar', 'Baz'])\n        writer.writerow(['Second row', 'A', 'B', 'C', '\"Testing\"', \"Here's a quote\"])\n\n        return response\n\nThe code and comments should be self-explanatory, but a few things deserve a\nmention:\n\n* The response gets a special MIME type, :mimetype:`text/csv`. This tells\n  browsers that the document is a CSV file, rather than an HTML file. If\n  you leave this off, browsers will probably interpret the output as HTML,\n  which will result in ugly, scary gobbledygook in the browser window.\n\n* The response gets an additional ``Content-Disposition`` header, which\n  contains the name of the CSV file. This filename is arbitrary; call it\n  whatever you want. It'll be used by browsers in the \"Save as...\" dialog, etc.\n\n* You can hook into the CSV-generation API by passing ``response`` as the first\n  argument to ``csv.writer``. The ``csv.writer`` function expects a file-like\n  object, and :class:`~django.http.HttpResponse` objects fit the bill.\n\n* For each row in your CSV file, call ``writer.writerow``, passing it an\n  :term:`iterable`.\n\n* The CSV module takes care of quoting for you, so you don't have to worry\n  about escaping strings with quotes or commas in them. Pass ``writerow()``\n  your raw strings, and it'll do the right thing.\n\n.. _streaming-csv-files:\n\nStreaming large CSV files\n-------------------------\n\nWhen dealing with views that generate very large responses, you might want to\nconsider using Django's :class:`~django.http.StreamingHttpResponse` instead.\nFor example, by streaming a file that takes a long time to generate you can\navoid a load balancer dropping a connection that might have otherwise timed out\nwhile the server was generating the response.\n\nIn this example, we make full use of Python generators to efficiently handle\nthe assembly and transmission of a large CSV file::\n\n    import csv\n\n    from django.http import StreamingHttpResponse\n\n    class Echo:\n        \"\"\"An object that implements just the write method of the file-like\n        interface.\n        \"\"\"\n        def write(self, value):\n            \"\"\"Write the value by returning it, instead of storing in a buffer.\"\"\"\n            return value\n\n    def some_streaming_csv_view(request):\n        \"\"\"A view that streams a large CSV file.\"\"\"\n        # Generate a sequence of rows. The range is based on the maximum number of\n        # rows that can be handled by a single sheet in most spreadsheet\n        # applications.\n        rows = ([\"Row {}\".format(idx), str(idx)] for idx in range(65536))\n        pseudo_buffer = Echo()\n        writer = csv.writer(pseudo_buffer)\n        response = StreamingHttpResponse((writer.writerow(row) for row in rows),\n                                         content_type=\"text/csv\")\n        response['Content-Disposition'] = 'attachment; filename=\"somefilename.csv\"'\n        return response\n\nUsing the template system\n=========================\n\nAlternatively, you can use the :doc:`Django template system </topics/templates>`\nto generate CSV. This is lower-level than using the convenient Python :mod:`csv`\nmodule, but the solution is presented here for completeness.\n\nThe idea here is to pass a list of items to your template, and have the\ntemplate output the commas in a :ttag:`for` loop.\n\nHere's an example, which generates the same CSV file as above::\n\n    from django.http import HttpResponse\n    from django.template import loader\n\n    def some_view(request):\n        # Create the HttpResponse object with the appropriate CSV header.\n        response = HttpResponse(content_type='text/csv')\n        response['Content-Disposition'] = 'attachment; filename=\"somefilename.csv\"'\n\n        # The data is hard-coded here, but you could load it from a database or\n        # some other source.\n        csv_data = (\n            ('First row', 'Foo', 'Bar', 'Baz'),\n            ('Second row', 'A', 'B', 'C', '\"Testing\"', \"Here's a quote\"),\n        )\n\n        t = loader.get_template('my_template_name.txt')\n        c = {'data': csv_data}\n        response.write(t.render(c))\n        return response\n\nThe only difference between this example and the previous example is that this\none uses template loading instead of the CSV module. The rest of the code --\nsuch as the ``content_type='text/csv'`` -- is the same.\n\nThen, create the template ``my_template_name.txt``, with this template code:\n\n.. code-block:: html+django\n\n    {% for row in data %}\"{{ row.0|addslashes }}\", \"{{ row.1|addslashes }}\", \"{{ row.2|addslashes }}\", \"{{ row.3|addslashes }}\", \"{{ row.4|addslashes }}\"\n    {% endfor %}\n\nThis short template iterates over the given data and displays a line of CSV for\neach row. It uses the :tfilter:`addslashes` template filter to ensure there\naren't any problems with quotes.\n\nOther text-based formats\n========================\n\nNotice that there isn't very much specific to CSV here -- just the specific\noutput format. You can use either of these techniques to output any text-based\nformat you can dream of. You can also use a similar technique to generate\narbitrary binary data; see :doc:`/howto/outputting-pdf` for an example.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":180,"nodeType":"TextFile","repoName":null,"name":"auth-remote-user.txt","path":"docs/howto","text":"====================================\nAuthentication using ``REMOTE_USER``\n====================================\n\nThis document describes how to make use of external authentication sources\n(where the Web server sets the ``REMOTE_USER`` environment variable) in your\nDjango applications.  This type of authentication solution is typically seen on\nintranet sites, with single sign-on solutions such as IIS and Integrated\nWindows Authentication or Apache and `mod_authnz_ldap`_, `CAS`_, `Cosign`_,\n`WebAuth`_, `mod_auth_sspi`_, etc.\n\n.. _mod_authnz_ldap: https://httpd.apache.org/docs/2.2/mod/mod_authnz_ldap.html\n.. _CAS: https://www.apereo.org/projects/cas\n.. _Cosign: http://weblogin.org\n.. _WebAuth: https://www.stanford.edu/services/webauth/\n.. _mod_auth_sspi: https://sourceforge.net/projects/mod-auth-sspi\n\nWhen the Web server takes care of authentication it typically sets the\n``REMOTE_USER`` environment variable for use in the underlying application.  In\nDjango, ``REMOTE_USER`` is made available in the :attr:`request.META\n<django.http.HttpRequest.META>` attribute.  Django can be configured to make\nuse of the ``REMOTE_USER`` value using the ``RemoteUserMiddleware``\nor ``PersistentRemoteUserMiddleware``, and\n:class:`~django.contrib.auth.backends.RemoteUserBackend` classes found in\n:mod:`django.contrib.auth`.\n\nConfiguration\n=============\n\nFirst, you must add the\n:class:`django.contrib.auth.middleware.RemoteUserMiddleware` to the\n:setting:`MIDDLEWARE` setting **after** the\n:class:`django.contrib.auth.middleware.AuthenticationMiddleware`::\n\n    MIDDLEWARE = [\n        '...',\n        'django.contrib.auth.middleware.AuthenticationMiddleware',\n        'django.contrib.auth.middleware.RemoteUserMiddleware',\n        '...',\n    ]\n\nNext, you must replace the :class:`~django.contrib.auth.backends.ModelBackend`\nwith :class:`~django.contrib.auth.backends.RemoteUserBackend` in the\n:setting:`AUTHENTICATION_BACKENDS` setting::\n\n    AUTHENTICATION_BACKENDS = [\n        'django.contrib.auth.backends.RemoteUserBackend',\n    ]\n\nWith this setup, ``RemoteUserMiddleware`` will detect the username in\n``request.META['REMOTE_USER']`` and will authenticate and auto-login that user\nusing the :class:`~django.contrib.auth.backends.RemoteUserBackend`.\n\nBe aware that this particular setup disables authentication with the default\n``ModelBackend``. This means that if the ``REMOTE_USER`` value is not set\nthen the user is unable to log in, even using Django's admin interface.\nAdding ``'django.contrib.auth.backends.ModelBackend'`` to the\n``AUTHENTICATION_BACKENDS`` list will use ``ModelBackend`` as a fallback\nif ``REMOTE_USER`` is absent, which will solve these issues.\n\nDjango's user management, such as the views in ``contrib.admin`` and\nthe :djadmin:`createsuperuser` management command, doesn't integrate with\nremote users. These interfaces work with users stored in the database\nregardless of ``AUTHENTICATION_BACKENDS``.\n\n.. note::\n\n    Since the ``RemoteUserBackend`` inherits from ``ModelBackend``, you will\n    still have all of the same permissions checking that is implemented in\n    ``ModelBackend``.\n\n    Users with :attr:`is_active=False\n    <django.contrib.auth.models.User.is_active>` won't be allowed to\n    authenticate. Use\n    :class:`~django.contrib.auth.backends.AllowAllUsersRemoteUserBackend` if\n    you want to allow them to.\n\nIf your authentication mechanism uses a custom HTTP header and not\n``REMOTE_USER``, you can subclass ``RemoteUserMiddleware`` and set the\n``header`` attribute to the desired ``request.META`` key.  For example::\n\n    from django.contrib.auth.middleware import RemoteUserMiddleware\n\n    class CustomHeaderMiddleware(RemoteUserMiddleware):\n        header = 'HTTP_AUTHUSER'\n\n.. warning::\n\n    Be very careful if using a ``RemoteUserMiddleware`` subclass with a custom\n    HTTP header. You must be sure that your front-end web server always sets or\n    strips that header based on the appropriate authentication checks, never\n    permitting an end-user to submit a fake (or \"spoofed\") header value. Since\n    the HTTP headers ``X-Auth-User`` and ``X-Auth_User`` (for example) both\n    normalize to the ``HTTP_X_AUTH_USER`` key in ``request.META``, you must\n    also check that your web server doesn't allow a spoofed header using\n    underscores in place of dashes.\n\n    This warning doesn't apply to ``RemoteUserMiddleware`` in its default\n    configuration with ``header = 'REMOTE_USER'``, since a key that doesn't\n    start with ``HTTP_`` in ``request.META`` can only be set by your WSGI\n    server, not directly from an HTTP request header.\n\nIf you need more control, you can create your own authentication backend\nthat inherits from :class:`~django.contrib.auth.backends.RemoteUserBackend` and\noverride one or more of its attributes and methods.\n\n.. _persistent-remote-user-middleware-howto:\n\nUsing ``REMOTE_USER`` on login pages only\n=========================================\n\nThe ``RemoteUserMiddleware`` authentication middleware assumes that the HTTP\nrequest header ``REMOTE_USER`` is present with all authenticated requests. That\nmight be expected and practical when Basic HTTP Auth with ``htpasswd`` or\nsimilar mechanisms are used, but with Negotiate (GSSAPI/Kerberos) or other\nresource intensive authentication methods, the authentication in the front-end\nHTTP server is usually only set up for one or a few login URLs, and after\nsuccessful authentication, the application is supposed to maintain the\nauthenticated session itself.\n\n:class:`~django.contrib.auth.middleware.PersistentRemoteUserMiddleware`\nprovides support for this use case. It will maintain the authenticated session\nuntil explicit logout by the user. The class can be used as a drop-in\nreplacement of :class:`~django.contrib.auth.middleware.RemoteUserMiddleware`\nin the documentation above.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":181,"nodeType":"TextFile","repoName":null,"name":"generic-date-based.txt","path":"docs/ref/class-based-views","text":"==================\nGeneric date views\n==================\n\n.. module:: django.views.generic.dates\n\nDate-based generic views, provided in :mod:`django.views.generic.dates`, are\nviews for displaying drilldown pages for date-based data.\n\n.. note::\n\n    Some of the examples on this page assume that an ``Article`` model has been\n    defined as follows in ``myapp/models.py``::\n\n        from django.db import models\n        from django.urls import reverse\n\n        class Article(models.Model):\n            title = models.CharField(max_length=200)\n            pub_date = models.DateField()\n\n            def get_absolute_url(self):\n                return reverse('article-detail', kwargs={'pk': self.pk})\n\n``ArchiveIndexView``\n====================\n\n.. class:: ArchiveIndexView\n\n    A top-level index page showing the \"latest\" objects, by date. Objects with\n    a date in the *future* are not included unless you set ``allow_future`` to\n    ``True``.\n\n    **Ancestors (MRO)**\n\n    * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`\n    * :class:`django.views.generic.base.TemplateResponseMixin`\n    * :class:`django.views.generic.dates.BaseArchiveIndexView`\n    * :class:`django.views.generic.dates.BaseDateListView`\n    * :class:`django.views.generic.list.MultipleObjectMixin`\n    * :class:`django.views.generic.dates.DateMixin`\n    * :class:`django.views.generic.base.View`\n\n    **Context**\n\n    In addition to the context provided by\n    :class:`django.views.generic.list.MultipleObjectMixin` (via\n    :class:`django.views.generic.dates.BaseDateListView`), the template's\n    context will be:\n\n    * ``date_list``: A :meth:`QuerySet <django.db.models.query.QuerySet.dates>`\n      object containing all years that have objects available according to\n      ``queryset``, represented as :class:`datetime.datetime` objects, in\n      descending order.\n\n    **Notes**\n\n    * Uses a default ``context_object_name`` of ``latest``.\n    * Uses a default ``template_name_suffix`` of ``_archive``.\n    * Defaults to providing ``date_list`` by year, but this can be altered to\n      month or day using the attribute ``date_list_period``. This also applies\n      to all subclass views.\n\n    **Example myapp/urls.py**::\n\n        from django.urls import path\n        from django.views.generic.dates import ArchiveIndexView\n\n        from myapp.models import Article\n\n        urlpatterns = [\n            path('archive/',\n                 ArchiveIndexView.as_view(model=Article, date_field=\"pub_date\"),\n                 name=\"article_archive\"),\n        ]\n\n    **Example myapp/article_archive.html**:\n\n    .. code-block:: html+django\n\n        <ul>\n            {% for article in latest %}\n                <li>{{ article.pub_date }}: {{ article.title }}</li>\n            {% endfor %}\n        </ul>\n\n    This will output all articles.\n\n``YearArchiveView``\n===================\n\n.. class:: YearArchiveView\n\n    A yearly archive page showing all available months in a given year. Objects\n    with a date in the *future* are not displayed unless you set\n    ``allow_future`` to ``True``.\n\n    **Ancestors (MRO)**\n\n    * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`\n    * :class:`django.views.generic.base.TemplateResponseMixin`\n    * :class:`django.views.generic.dates.BaseYearArchiveView`\n    * :class:`django.views.generic.dates.YearMixin`\n    * :class:`django.views.generic.dates.BaseDateListView`\n    * :class:`django.views.generic.list.MultipleObjectMixin`\n    * :class:`django.views.generic.dates.DateMixin`\n    * :class:`django.views.generic.base.View`\n\n    .. attribute:: make_object_list\n\n        A boolean specifying whether to retrieve the full list of objects for\n        this year and pass those to the template. If ``True``, the list of\n        objects will be made available to the context. If ``False``, the\n        ``None`` queryset will be used as the object list. By default, this is\n        ``False``.\n\n    .. method:: get_make_object_list()\n\n        Determine if an object list will be returned as part of the context.\n        Returns :attr:`~YearArchiveView.make_object_list` by default.\n\n    **Context**\n\n    In addition to the context provided by\n    :class:`django.views.generic.list.MultipleObjectMixin` (via\n    :class:`django.views.generic.dates.BaseDateListView`), the template's\n    context will be:\n\n    * ``date_list``: A :meth:`QuerySet <django.db.models.query.QuerySet.dates>`\n      object containing all months that have objects available according to\n      ``queryset``, represented as :class:`datetime.datetime` objects, in\n      ascending order.\n\n    * ``year``: A :class:`~datetime.date` object\n      representing the given year.\n\n    * ``next_year``: A :class:`~datetime.date` object\n      representing the first day of the next year, according to\n      :attr:`~BaseDateListView.allow_empty` and\n      :attr:`~DateMixin.allow_future`.\n\n    * ``previous_year``: A :class:`~datetime.date` object\n      representing the first day of the previous year, according to\n      :attr:`~BaseDateListView.allow_empty` and\n      :attr:`~DateMixin.allow_future`.\n\n    **Notes**\n\n    * Uses a default ``template_name_suffix`` of ``_archive_year``.\n\n    **Example myapp/views.py**::\n\n        from django.views.generic.dates import YearArchiveView\n\n        from myapp.models import Article\n\n        class ArticleYearArchiveView(YearArchiveView):\n            queryset = Article.objects.all()\n            date_field = \"pub_date\"\n            make_object_list = True\n            allow_future = True\n\n    **Example myapp/urls.py**::\n\n        from django.urls import path\n\n        from myapp.views import ArticleYearArchiveView\n\n        urlpatterns = [\n            path('<int:year>/',\n                 ArticleYearArchiveView.as_view(),\n                 name=\"article_year_archive\"),\n        ]\n\n    **Example myapp/article_archive_year.html**:\n\n    .. code-block:: html+django\n\n        <ul>\n            {% for date in date_list %}\n                <li>{{ date|date }}</li>\n            {% endfor %}\n        </ul>\n\n        <div>\n            <h1>All Articles for {{ year|date:\"Y\" }}</h1>\n            {% for obj in object_list %}\n                <p>\n                    {{ obj.title }} - {{ obj.pub_date|date:\"F j, Y\" }}\n                </p>\n            {% endfor %}\n        </div>\n\n``MonthArchiveView``\n====================\n\n.. class:: MonthArchiveView\n\n    A monthly archive page showing all objects in a given month. Objects with a\n    date in the *future* are not displayed unless you set ``allow_future`` to\n    ``True``.\n\n    **Ancestors (MRO)**\n\n    * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`\n    * :class:`django.views.generic.base.TemplateResponseMixin`\n    * :class:`django.views.generic.dates.BaseMonthArchiveView`\n    * :class:`django.views.generic.dates.YearMixin`\n    * :class:`django.views.generic.dates.MonthMixin`\n    * :class:`django.views.generic.dates.BaseDateListView`\n    * :class:`django.views.generic.list.MultipleObjectMixin`\n    * :class:`django.views.generic.dates.DateMixin`\n    * :class:`django.views.generic.base.View`\n\n    **Context**\n\n    In addition to the context provided by\n    :class:`~django.views.generic.list.MultipleObjectMixin` (via\n    :class:`~django.views.generic.dates.BaseDateListView`), the template's\n    context will be:\n\n    * ``date_list``: A :meth:`QuerySet <django.db.models.query.QuerySet.dates>`\n      object containing all days that have objects available in the given month,\n      according to ``queryset``, represented as :class:`datetime.datetime`\n      objects, in ascending order.\n\n    * ``month``: A :class:`~datetime.date` object\n      representing the given month.\n\n    * ``next_month``: A :class:`~datetime.date` object\n      representing the first day of the next month, according to\n      :attr:`~BaseDateListView.allow_empty` and\n      :attr:`~DateMixin.allow_future`.\n\n    * ``previous_month``: A :class:`~datetime.date` object\n      representing the first day of the previous month, according to\n      :attr:`~BaseDateListView.allow_empty` and\n      :attr:`~DateMixin.allow_future`.\n\n    **Notes**\n\n    * Uses a default ``template_name_suffix`` of ``_archive_month``.\n\n    **Example myapp/views.py**::\n\n        from django.views.generic.dates import MonthArchiveView\n\n        from myapp.models import Article\n\n        class ArticleMonthArchiveView(MonthArchiveView):\n            queryset = Article.objects.all()\n            date_field = \"pub_date\"\n            allow_future = True\n\n    **Example myapp/urls.py**::\n\n        from django.urls import path\n\n        from myapp.views import ArticleMonthArchiveView\n\n        urlpatterns = [\n            # Example: /2012/08/\n            path('<int:year>/<int:month>/',\n                 ArticleMonthArchiveView.as_view(month_format='%m'),\n                 name=\"archive_month_numeric\"),\n            # Example: /2012/aug/\n            path('<int:year>/<str:month>/',\n                 ArticleMonthArchiveView.as_view(),\n                 name=\"archive_month\"),\n        ]\n\n    **Example myapp/article_archive_month.html**:\n\n    .. code-block:: html+django\n\n        <ul>\n            {% for article in object_list %}\n                <li>{{ article.pub_date|date:\"F j, Y\" }}: {{ article.title }}</li>\n            {% endfor %}\n        </ul>\n\n        <p>\n            {% if previous_month %}\n                Previous Month: {{ previous_month|date:\"F Y\" }}\n            {% endif %}\n            {% if next_month %}\n                Next Month: {{ next_month|date:\"F Y\" }}\n            {% endif %}\n        </p>\n\n``WeekArchiveView``\n===================\n\n.. class:: WeekArchiveView\n\n    A weekly archive page showing all objects in a given week. Objects with a\n    date in the *future* are not displayed unless you set ``allow_future`` to\n    ``True``.\n\n    **Ancestors (MRO)**\n\n    * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`\n    * :class:`django.views.generic.base.TemplateResponseMixin`\n    * :class:`django.views.generic.dates.BaseWeekArchiveView`\n    * :class:`django.views.generic.dates.YearMixin`\n    * :class:`django.views.generic.dates.WeekMixin`\n    * :class:`django.views.generic.dates.BaseDateListView`\n    * :class:`django.views.generic.list.MultipleObjectMixin`\n    * :class:`django.views.generic.dates.DateMixin`\n    * :class:`django.views.generic.base.View`\n\n    **Context**\n\n    In addition to the context provided by\n    :class:`~django.views.generic.list.MultipleObjectMixin` (via\n    :class:`~django.views.generic.dates.BaseDateListView`), the template's\n    context will be:\n\n    * ``week``: A :class:`~datetime.date` object\n      representing the first day of the given week.\n\n    * ``next_week``: A :class:`~datetime.date` object\n      representing the first day of the next week, according to\n      :attr:`~BaseDateListView.allow_empty` and\n      :attr:`~DateMixin.allow_future`.\n\n    * ``previous_week``: A :class:`~datetime.date` object\n      representing the first day of the previous week, according to\n      :attr:`~BaseDateListView.allow_empty` and\n      :attr:`~DateMixin.allow_future`.\n\n    **Notes**\n\n    * Uses a default ``template_name_suffix`` of ``_archive_week``.\n\n    * The ``week_format`` attribute is a :func:`~time.strptime` format string\n      used to parse the week number. The following values are supported:\n\n      * ``'%U'``: Based on the United States week system where the week\n        begins on Sunday. This is the default value.\n\n      * ``'%W'``: Similar to ``'%U'``, except it assumes that the week\n        begins on Monday. This is not the same as the ISO 8601 week number.\n\n    **Example myapp/views.py**::\n\n        from django.views.generic.dates import WeekArchiveView\n\n        from myapp.models import Article\n\n        class ArticleWeekArchiveView(WeekArchiveView):\n            queryset = Article.objects.all()\n            date_field = \"pub_date\"\n            week_format = \"%W\"\n            allow_future = True\n\n    **Example myapp/urls.py**::\n\n        from django.urls import path\n\n        from myapp.views import ArticleWeekArchiveView\n\n        urlpatterns = [\n            # Example: /2012/week/23/\n            path('<int:year>/week/<int:week>/',\n                 ArticleWeekArchiveView.as_view(),\n                 name=\"archive_week\"),\n        ]\n\n    **Example myapp/article_archive_week.html**:\n\n    .. code-block:: html+django\n\n        <h1>Week {{ week|date:'W' }}</h1>\n\n        <ul>\n            {% for article in object_list %}\n                <li>{{ article.pub_date|date:\"F j, Y\" }}: {{ article.title }}</li>\n            {% endfor %}\n        </ul>\n\n        <p>\n            {% if previous_week %}\n                Previous Week: {{ previous_week|date:\"W\" }} of year {{ previous_week|date:\"Y\" }}\n            {% endif %}\n            {% if previous_week and next_week %}--{% endif %}\n            {% if next_week %}\n                Next week: {{ next_week|date:\"W\" }} of year {{ next_week|date:\"Y\" }}\n            {% endif %}\n        </p>\n\n    In this example, you are outputting the week number. Keep in mind that week\n    numbers computed by the :tfilter:`date` template filter with the ``'W'``\n    format character are not always the same as those computed by\n    :func:`~time.strftime` and :func:`~time.strptime` with the ``'%W'`` format\n    string. For year 2015, for example, week numbers output by :tfilter:`date`\n    are higher by one compared to those output by :func:`~time.strftime`. There\n    isn't an equivalent for the ``'%U'`` :func:`~time.strftime` format string\n    in :tfilter:`date`. Therefore, you should avoid using :tfilter:`date` to\n    generate URLs for ``WeekArchiveView``.\n\n``DayArchiveView``\n==================\n\n.. class:: DayArchiveView\n\n    A day archive page showing all objects in a given day. Days in the future\n    throw a 404 error, regardless of whether any objects exist for future days,\n    unless you set ``allow_future`` to ``True``.\n\n    **Ancestors (MRO)**\n\n    * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`\n    * :class:`django.views.generic.base.TemplateResponseMixin`\n    * :class:`django.views.generic.dates.BaseDayArchiveView`\n    * :class:`django.views.generic.dates.YearMixin`\n    * :class:`django.views.generic.dates.MonthMixin`\n    * :class:`django.views.generic.dates.DayMixin`\n    * :class:`django.views.generic.dates.BaseDateListView`\n    * :class:`django.views.generic.list.MultipleObjectMixin`\n    * :class:`django.views.generic.dates.DateMixin`\n    * :class:`django.views.generic.base.View`\n\n    **Context**\n\n    In addition to the context provided by\n    :class:`~django.views.generic.list.MultipleObjectMixin` (via\n    :class:`~django.views.generic.dates.BaseDateListView`), the template's\n    context will be:\n\n    * ``day``: A :class:`~datetime.date` object\n      representing the given day.\n\n    * ``next_day``: A :class:`~datetime.date` object\n      representing the next day, according to\n      :attr:`~BaseDateListView.allow_empty` and\n      :attr:`~DateMixin.allow_future`.\n\n    * ``previous_day``: A :class:`~datetime.date` object\n      representing the previous day, according to\n      :attr:`~BaseDateListView.allow_empty` and\n      :attr:`~DateMixin.allow_future`.\n\n    * ``next_month``: A :class:`~datetime.date` object\n      representing the first day of the next month, according to\n      :attr:`~BaseDateListView.allow_empty` and\n      :attr:`~DateMixin.allow_future`.\n\n    * ``previous_month``: A :class:`~datetime.date` object\n      representing the first day of the previous month, according to\n      :attr:`~BaseDateListView.allow_empty` and\n      :attr:`~DateMixin.allow_future`.\n\n    **Notes**\n\n    * Uses a default ``template_name_suffix`` of ``_archive_day``.\n\n    **Example myapp/views.py**::\n\n        from django.views.generic.dates import DayArchiveView\n\n        from myapp.models import Article\n\n        class ArticleDayArchiveView(DayArchiveView):\n            queryset = Article.objects.all()\n            date_field = \"pub_date\"\n            allow_future = True\n\n    **Example myapp/urls.py**::\n\n        from django.urls import path\n\n        from myapp.views import ArticleDayArchiveView\n\n        urlpatterns = [\n            # Example: /2012/nov/10/\n            path('<int:year>/<str:month>/<int:day>/',\n                 ArticleDayArchiveView.as_view(),\n                 name=\"archive_day\"),\n        ]\n\n    **Example myapp/article_archive_day.html**:\n\n    .. code-block:: html+django\n\n        <h1>{{ day }}</h1>\n\n        <ul>\n            {% for article in object_list %}\n                <li>{{ article.pub_date|date:\"F j, Y\" }}: {{ article.title }}</li>\n            {% endfor %}\n        </ul>\n\n        <p>\n            {% if previous_day %}\n                Previous Day: {{ previous_day }}\n            {% endif %}\n            {% if previous_day and next_day %}--{% endif %}\n            {% if next_day %}\n                Next Day: {{ next_day }}\n            {% endif %}\n        </p>\n\n``TodayArchiveView``\n====================\n\n.. class:: TodayArchiveView\n\n    A day archive page showing all objects for *today*. This is exactly the\n    same as :class:`django.views.generic.dates.DayArchiveView`, except today's\n    date is used instead of the ``year``/``month``/``day`` arguments.\n\n    **Ancestors (MRO)**\n\n    * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`\n    * :class:`django.views.generic.base.TemplateResponseMixin`\n    * :class:`django.views.generic.dates.BaseTodayArchiveView`\n    * :class:`django.views.generic.dates.BaseDayArchiveView`\n    * :class:`django.views.generic.dates.YearMixin`\n    * :class:`django.views.generic.dates.MonthMixin`\n    * :class:`django.views.generic.dates.DayMixin`\n    * :class:`django.views.generic.dates.BaseDateListView`\n    * :class:`django.views.generic.list.MultipleObjectMixin`\n    * :class:`django.views.generic.dates.DateMixin`\n    * :class:`django.views.generic.base.View`\n\n    **Notes**\n\n    * Uses a default ``template_name_suffix`` of ``_archive_today``.\n\n    **Example myapp/views.py**::\n\n        from django.views.generic.dates import TodayArchiveView\n\n        from myapp.models import Article\n\n        class ArticleTodayArchiveView(TodayArchiveView):\n            queryset = Article.objects.all()\n            date_field = \"pub_date\"\n            allow_future = True\n\n    **Example myapp/urls.py**::\n\n        from django.urls import path\n\n        from myapp.views import ArticleTodayArchiveView\n\n        urlpatterns = [\n            path('today/',\n                 ArticleTodayArchiveView.as_view(),\n                 name=\"archive_today\"),\n        ]\n\n    .. admonition:: Where is the example template for ``TodayArchiveView``?\n\n        This view uses by default the same template as the\n        :class:`~DayArchiveView`, which is in the previous example. If you need\n        a different template, set the ``template_name`` attribute to be the\n        name of the new template.\n\n``DateDetailView``\n==================\n\n.. class:: DateDetailView\n\n    A page representing an individual object. If the object has a date value in\n    the future, the view will throw a 404 error by default, unless you set\n    ``allow_future`` to ``True``.\n\n    **Ancestors (MRO)**\n\n    * :class:`django.views.generic.detail.SingleObjectTemplateResponseMixin`\n    * :class:`django.views.generic.base.TemplateResponseMixin`\n    * :class:`django.views.generic.dates.BaseDateDetailView`\n    * :class:`django.views.generic.dates.YearMixin`\n    * :class:`django.views.generic.dates.MonthMixin`\n    * :class:`django.views.generic.dates.DayMixin`\n    * :class:`django.views.generic.dates.DateMixin`\n    * ``django.views.generic.detail.BaseDetailView``\n    * :class:`django.views.generic.detail.SingleObjectMixin`\n    * :class:`django.views.generic.base.View`\n\n    **Context**\n\n    * Includes the single object associated with the ``model`` specified in\n      the ``DateDetailView``.\n\n    **Notes**\n\n    * Uses a default ``template_name_suffix`` of ``_detail``.\n\n    **Example myapp/urls.py**::\n\n        from django.urls import path\n        from django.views.generic.dates import DateDetailView\n\n        urlpatterns = [\n            path('<int:year>/<str:month>/<int:day>/<int:pk>/',\n                 DateDetailView.as_view(model=Article, date_field=\"pub_date\"),\n                 name=\"archive_date_detail\"),\n        ]\n\n    **Example myapp/article_detail.html**:\n\n    .. code-block:: html+django\n\n        <h1>{{ object.title }}</h1>\n\n.. note::\n\n    All of the generic views listed above have matching ``Base`` views that\n    only differ in that they do not include the\n    :class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`\n    (for the archive views) or\n    :class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`\n    (for the :class:`DateDetailView`):\n\n    .. class:: BaseArchiveIndexView\n\n    .. class:: BaseYearArchiveView\n\n    .. class:: BaseMonthArchiveView\n\n    .. class:: BaseWeekArchiveView\n\n    .. class:: BaseDayArchiveView\n\n    .. class:: BaseTodayArchiveView\n\n    .. class:: BaseDateDetailView\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":182,"nodeType":"TextFile","repoName":null,"name":"design-philosophies.txt","path":"docs/misc","text":"===================\nDesign philosophies\n===================\n\nThis document explains some of the fundamental philosophies Django's developers\nhave used in creating the framework. Its goal is to explain the past and guide\nthe future.\n\nOverall\n=======\n\n.. _loose-coupling:\n\nLoose coupling\n--------------\n\n.. index:: coupling; loose\n\nA fundamental goal of Django's stack is `loose coupling and tight cohesion`_.\nThe various layers of the framework shouldn't \"know\" about each other unless\nabsolutely necessary.\n\nFor example, the template system knows nothing about Web requests, the database\nlayer knows nothing about data display and the view system doesn't care which\ntemplate system a programmer uses.\n\nAlthough Django comes with a full stack for convenience, the pieces of the\nstack are independent of another wherever possible.\n\n.. _`loose coupling and tight cohesion`: http://wiki.c2.com/?CouplingAndCohesion\n\n.. _less-code:\n\nLess code\n---------\n\nDjango apps should use as little code as possible; they should lack boilerplate.\nDjango should take full advantage of Python's dynamic capabilities, such as\nintrospection.\n\n.. _quick-development:\n\nQuick development\n-----------------\n\nThe point of a Web framework in the 21st century is to make the tedious aspects\nof Web development fast. Django should allow for incredibly quick Web\ndevelopment.\n\n.. _dry:\n\nDon't repeat yourself (DRY)\n---------------------------\n\n.. index::\n   single: DRY\n   single: Don't repeat yourself\n\nEvery distinct concept and/or piece of data should live in one, and only one,\nplace. Redundancy is bad. Normalization is good.\n\nThe framework, within reason, should deduce as much as possible from as little\nas possible.\n\n.. seealso::\n\n    The `discussion of DRY on the Portland Pattern Repository`__\n\n    __ http://wiki.c2.com/?DontRepeatYourself\n\n.. _explicit-is-better-than-implicit:\n\nExplicit is better than implicit\n--------------------------------\n\nThis is a core Python principle listed in :pep:`20`, and it means Django\nshouldn't do too much \"magic.\" Magic shouldn't happen unless there's a really\ngood reason for it. Magic is worth using only if it creates a huge convenience\nunattainable in other ways, and it isn't implemented in a way that confuses\ndevelopers who are trying to learn how to use the feature.\n\n.. _consistency:\n\nConsistency\n-----------\n\nThe framework should be consistent at all levels. Consistency applies to\neverything from low-level (the Python coding style used) to high-level (the\n\"experience\" of using Django).\n\nModels\n======\n\nExplicit is better than implicit\n--------------------------------\n\nFields shouldn't assume certain behaviors based solely on the name of the\nfield. This requires too much knowledge of the system and is prone to errors.\nInstead, behaviors should be based on keyword arguments and, in some cases, on\nthe type of the field.\n\nInclude all relevant domain logic\n---------------------------------\n\nModels should encapsulate every aspect of an \"object,\" following Martin\nFowler's `Active Record`_ design pattern.\n\nThis is why both the data represented by a model and information about\nit (its human-readable name, options like default ordering, etc.) are\ndefined in the model class; all the information needed to understand a\ngiven model should be stored *in* the model.\n\n.. _`Active Record`: https://www.martinfowler.com/eaaCatalog/activeRecord.html\n\nDatabase API\n============\n\nThe core goals of the database API are:\n\nSQL efficiency\n--------------\n\nIt should execute SQL statements as few times as possible, and it should\noptimize statements internally.\n\nThis is why developers need to call ``save()`` explicitly, rather than the\nframework saving things behind the scenes silently.\n\nThis is also why the ``select_related()`` ``QuerySet`` method exists. It's an\noptional performance booster for the common case of selecting \"every related\nobject.\"\n\nTerse, powerful syntax\n----------------------\n\nThe database API should allow rich, expressive statements in as little syntax\nas possible. It should not rely on importing other modules or helper objects.\n\nJoins should be performed automatically, behind the scenes, when necessary.\n\nEvery object should be able to access every related object, systemwide. This\naccess should work both ways.\n\nOption to drop into raw SQL easily, when needed\n-----------------------------------------------\n\nThe database API should realize it's a shortcut but not necessarily an\nend-all-be-all. The framework should make it easy to write custom SQL -- entire\nstatements, or just custom ``WHERE`` clauses as custom parameters to API calls.\n\nURL design\n==========\n\nLoose coupling\n--------------\n\nURLs in a Django app should not be coupled to the underlying Python code. Tying\nURLs to Python function names is a Bad And Ugly Thing.\n\nAlong these lines, the Django URL system should allow URLs for the same app to\nbe different in different contexts. For example, one site may put stories at\n``/stories/``, while another may use ``/news/``.\n\nInfinite flexibility\n--------------------\n\nURLs should be as flexible as possible. Any conceivable URL design should be\nallowed.\n\nEncourage best practices\n------------------------\n\nThe framework should make it just as easy (or even easier) for a developer to\ndesign pretty URLs than ugly ones.\n\nFile extensions in Web-page URLs should be avoided.\n\nVignette-style commas in URLs deserve severe punishment.\n\n.. _definitive-urls:\n\nDefinitive URLs\n---------------\n\n.. index:: urls; definitive\n\nTechnically, ``foo.com/bar`` and ``foo.com/bar/`` are two different URLs, and\nsearch-engine robots (and some Web traffic-analyzing tools) would treat them as\nseparate pages. Django should make an effort to \"normalize\" URLs so that\nsearch-engine robots don't get confused.\n\nThis is the reasoning behind the :setting:`APPEND_SLASH` setting.\n\nTemplate system\n===============\n\n.. _separation-of-logic-and-presentation:\n\nSeparate logic from presentation\n--------------------------------\n\nWe see a template system as a tool that controls presentation and\npresentation-related logic -- and that's it. The template system shouldn't\nsupport functionality that goes beyond this basic goal.\n\nDiscourage redundancy\n---------------------\n\nThe majority of dynamic websites use some sort of common sitewide design --\na common header, footer, navigation bar, etc. The Django template system should\nmake it easy to store those elements in a single place, eliminating duplicate\ncode.\n\nThis is the philosophy behind :ref:`template inheritance\n<template-inheritance>`.\n\nBe decoupled from HTML\n----------------------\n\nThe template system shouldn't be designed so that it only outputs HTML. It\nshould be equally good at generating other text-based formats, or just plain\ntext.\n\nXML should not be used for template languages\n---------------------------------------------\n\n.. index:: xml; suckiness of\n\nUsing an XML engine to parse templates introduces a whole new world of human\nerror in editing templates -- and incurs an unacceptable level of overhead in\ntemplate processing.\n\nAssume designer competence\n--------------------------\n\nThe template system shouldn't be designed so that templates necessarily are\ndisplayed nicely in WYSIWYG editors such as Dreamweaver. That is too severe of\na limitation and wouldn't allow the syntax to be as nice as it is. Django\nexpects template authors are comfortable editing HTML directly.\n\nTreat whitespace obviously\n--------------------------\n\nThe template system shouldn't do magic things with whitespace. If a template\nincludes whitespace, the system should treat the whitespace as it treats text\n-- just display it. Any whitespace that's not in a template tag should be\ndisplayed.\n\nDon't invent a programming language\n-----------------------------------\n\nThe goal is not to invent a programming language. The goal is to offer just\nenough programming-esque functionality, such as branching and looping, that is\nessential for making presentation-related decisions. The :ref:`Django Template\nLanguage (DTL) <template-language-intro>` aims to avoid advanced logic.\n\nThe Django template system recognizes that templates are most often written by\n*designers*, not *programmers*, and therefore should not assume Python\nknowledge.\n\nSafety and security\n-------------------\n\nThe template system, out of the box, should forbid the inclusion of malicious\ncode -- such as commands that delete database records.\n\nThis is another reason the template system doesn't allow arbitrary Python code.\n\nExtensibility\n-------------\n\nThe template system should recognize that advanced template authors may want\nto extend its technology.\n\nThis is the philosophy behind custom template tags and filters.\n\nViews\n=====\n\nSimplicity\n----------\n\nWriting a view should be as simple as writing a Python function. Developers\nshouldn't have to instantiate a class when a function will do.\n\nUse request objects\n-------------------\n\nViews should have access to a request object -- an object that stores metadata\nabout the current request. The object should be passed directly to a view\nfunction, rather than the view function having to access the request data from\na global variable. This makes it light, clean and easy to test views by passing\nin \"fake\" request objects.\n\nLoose coupling\n--------------\n\nA view shouldn't care about which template system the developer uses -- or even\nwhether a template system is used at all.\n\nDifferentiate between GET and POST\n----------------------------------\n\nGET and POST are distinct; developers should explicitly use one or the other.\nThe framework should make it easy to distinguish between GET and POST data.\n\n.. _cache-design-philosophy:\n\nCache Framework\n===============\n\nThe core goals of Django's :doc:`cache framework </topics/cache>` are:\n\nLess code\n---------\n\nA cache should be as fast as possible.  Hence, all framework code surrounding\nthe cache backend should be kept to the absolute minimum, especially for\n``get()`` operations.\n\nConsistency\n-----------\n\nThe cache API should provide a consistent interface across the different\ncache backends.\n\nExtensibility\n-------------\n\nThe cache API should be extensible at the application level based on the\ndeveloper's needs (for example, see :ref:`cache_key_transformation`).\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":183,"nodeType":"TextFile","repoName":null,"name":"builtins.txt","path":"docs/ref/templates","text":"==================================\nBuilt-in template tags and filters\n==================================\n\nThis document describes Django's built-in template tags and filters. It is\nrecommended that you use the :doc:`automatic documentation\n</ref/contrib/admin/admindocs>`, if available, as this will also include\ndocumentation for any custom tags or filters installed.\n\n.. _ref-templates-builtins-tags:\n\nBuilt-in tag reference\n======================\n\n.. highlight:: html+django\n\n.. templatetag:: autoescape\n\n``autoescape``\n--------------\n\nControls the current auto-escaping behavior. This tag takes either ``on`` or\n``off`` as an argument and that determines whether auto-escaping is in effect\ninside the block. The block is closed with an ``endautoescape`` ending tag.\n\nWhen auto-escaping is in effect, all variable content has HTML escaping applied\nto it before placing the result into the output (but after any filters have\nbeen applied). This is equivalent to manually applying the :tfilter:`escape`\nfilter to each variable.\n\nThe only exceptions are variables that are already marked as \"safe\" from\nescaping, either by the code that populated the variable, or because it has had\nthe :tfilter:`safe` or :tfilter:`escape` filters applied.\n\nSample usage::\n\n    {% autoescape on %}\n        {{ body }}\n    {% endautoescape %}\n\n.. templatetag:: block\n\n``block``\n---------\n\nDefines a block that can be overridden by child templates. See\n:ref:`Template inheritance <template-inheritance>` for more information.\n\n.. templatetag:: comment\n\n``comment``\n-----------\n\nIgnores everything between ``{% comment %}`` and ``{% endcomment %}``.\nAn optional note may be inserted in the first tag. For example, this is\nuseful when commenting out code for documenting why the code was disabled.\n\nSample usage::\n\n    <p>Rendered text with {{ pub_date|date:\"c\" }}</p>\n    {% comment \"Optional note\" %}\n        <p>Commented out text with {{ create_date|date:\"c\" }}</p>\n    {% endcomment %}\n\n``comment`` tags cannot be nested.\n\n.. templatetag:: csrf_token\n\n``csrf_token``\n--------------\n\nThis tag is used for CSRF protection, as described in the documentation for\n:doc:`Cross Site Request Forgeries </ref/csrf>`.\n\n.. templatetag:: cycle\n\n``cycle``\n---------\n\nProduces one of its arguments each time this tag is encountered. The first\nargument is produced on the first encounter, the second argument on the second\nencounter, and so forth. Once all arguments are exhausted, the tag cycles to\nthe first argument and produces it again.\n\nThis tag is particularly useful in a loop::\n\n    {% for o in some_list %}\n        <tr class=\"{% cycle 'row1' 'row2' %}\">\n            ...\n        </tr>\n    {% endfor %}\n\nThe first iteration produces HTML that refers to class ``row1``, the second to\n``row2``, the third to ``row1`` again, and so on for each iteration of the\nloop.\n\nYou can use variables, too. For example, if you have two template variables,\n``rowvalue1`` and ``rowvalue2``, you can alternate between their values like\nthis::\n\n    {% for o in some_list %}\n        <tr class=\"{% cycle rowvalue1 rowvalue2 %}\">\n            ...\n        </tr>\n    {% endfor %}\n\nVariables included in the cycle will be escaped.  You can disable auto-escaping\nwith::\n\n    {% for o in some_list %}\n        <tr class=\"{% autoescape off %}{% cycle rowvalue1 rowvalue2 %}{% endautoescape %}\">\n            ...\n        </tr>\n    {% endfor %}\n\nYou can mix variables and strings::\n\n    {% for o in some_list %}\n        <tr class=\"{% cycle 'row1' rowvalue2 'row3' %}\">\n            ...\n        </tr>\n    {% endfor %}\n\nIn some cases you might want to refer to the current value of a cycle\nwithout advancing to the next value. To do this,\ngive the ``{% cycle %}`` tag a name, using \"as\", like this::\n\n    {% cycle 'row1' 'row2' as rowcolors %}\n\nFrom then on, you can insert the current value of the cycle wherever you'd like\nin your template by referencing the cycle name as a context variable. If you\nwant to move the cycle to the next value independently of the original\n``cycle`` tag, you can use another ``cycle`` tag and specify the name of the\nvariable. So, the following template::\n\n    <tr>\n        <td class=\"{% cycle 'row1' 'row2' as rowcolors %}\">...</td>\n        <td class=\"{{ rowcolors }}\">...</td>\n    </tr>\n    <tr>\n        <td class=\"{% cycle rowcolors %}\">...</td>\n        <td class=\"{{ rowcolors }}\">...</td>\n    </tr>\n\nwould output::\n\n    <tr>\n        <td class=\"row1\">...</td>\n        <td class=\"row1\">...</td>\n    </tr>\n    <tr>\n        <td class=\"row2\">...</td>\n        <td class=\"row2\">...</td>\n    </tr>\n\nYou can use any number of values in a ``cycle`` tag, separated by spaces.\nValues enclosed in single quotes (``'``) or double quotes (``\"``) are treated\nas string literals, while values without quotes are treated as template\nvariables.\n\nBy default, when you use the ``as`` keyword with the cycle tag, the\nusage of ``{% cycle %}`` that initiates the cycle will itself produce\nthe first value in the cycle. This could be a problem if you want to\nuse the value in a nested loop or an included template. If you only want\nto declare the cycle but not produce the first value, you can add a\n``silent`` keyword as the last keyword in the tag. For example::\n\n    {% for obj in some_list %}\n        {% cycle 'row1' 'row2' as rowcolors silent %}\n        <tr class=\"{{ rowcolors }}\">{% include \"subtemplate.html\" %}</tr>\n    {% endfor %}\n\nThis will output a list of ``<tr>`` elements with ``class``\nalternating between ``row1`` and ``row2``. The subtemplate will have\naccess to ``rowcolors`` in its context and the value will match the class\nof the ``<tr>`` that encloses it. If the ``silent`` keyword were to be\nomitted, ``row1`` and ``row2`` would be emitted as normal text, outside the\n``<tr>`` element.\n\nWhen the silent keyword is used on a cycle definition, the silence\nautomatically applies to all subsequent uses of that specific cycle tag.\nThe following template would output *nothing*, even though the second\ncall to ``{% cycle %}`` doesn't specify ``silent``::\n\n    {% cycle 'row1' 'row2' as rowcolors silent %}\n    {% cycle rowcolors %}\n\nYou can use the :ttag:`resetcycle` tag to make a ``{% cycle %}`` tag restart\nfrom its first value when it's next encountered.\n\n.. templatetag:: debug\n\n``debug``\n---------\n\nOutputs a whole load of debugging information, including the current context\nand imported modules.\n\n.. templatetag:: extends\n\n``extends``\n-----------\n\nSignals that this template extends a parent template.\n\nThis tag can be used in two ways:\n\n* ``{% extends \"base.html\" %}`` (with quotes) uses the literal value\n  ``\"base.html\"`` as the name of the parent template to extend.\n\n* ``{% extends variable %}`` uses the value of ``variable``. If the variable\n  evaluates to a string, Django will use that string as the name of the\n  parent template. If the variable evaluates to a ``Template`` object,\n  Django will use that object as the parent template.\n\nSee :ref:`template-inheritance` for more information.\n\nNormally the template name is relative to the template loader's root directory.\nA string argument may also be a relative path starting with ``./`` or ``../``.\nFor example, assume the following directory structure::\n\n    dir1/\n        template.html\n        base2.html\n        my/\n            base3.html\n    base1.html\n\nIn ``template.html``, the following paths would be valid::\n\n    {% extends \"./base2.html\" %}\n    {% extends \"../base1.html\" %}\n    {% extends \"./my/base3.html\" %}\n\n.. templatetag:: filter\n\n``filter``\n----------\n\nFilters the contents of the block through one or more filters. Multiple\nfilters can be specified with pipes and filters can have arguments, just as\nin variable syntax.\n\nNote that the block includes *all* the text between the ``filter`` and\n``endfilter`` tags.\n\nSample usage::\n\n    {% filter force_escape|lower %}\n        This text will be HTML-escaped, and will appear in all lowercase.\n    {% endfilter %}\n\n.. note::\n\n    The :tfilter:`escape` and :tfilter:`safe` filters are not acceptable\n    arguments. Instead, use the :ttag:`autoescape` tag to manage autoescaping\n    for blocks of template code.\n\n.. templatetag:: firstof\n\n``firstof``\n-----------\n\nOutputs the first argument variable that is not \"false\" (i.e. exists, is not\nempty, is not a false boolean value, and is not a zero numeric value). Outputs\nnothing if all the passed variables are \"false\".\n\nSample usage::\n\n    {% firstof var1 var2 var3 %}\n\nThis is equivalent to::\n\n    {% if var1 %}\n        {{ var1 }}\n    {% elif var2 %}\n        {{ var2 }}\n    {% elif var3 %}\n        {{ var3 }}\n    {% endif %}\n\nYou can also use a literal string as a fallback value in case all\npassed variables are False::\n\n    {% firstof var1 var2 var3 \"fallback value\" %}\n\nThis tag auto-escapes variable values. You can disable auto-escaping with::\n\n    {% autoescape off %}\n        {% firstof var1 var2 var3 \"<strong>fallback value</strong>\" %}\n    {% endautoescape %}\n\nOr if only some variables should be escaped, you can use::\n\n    {% firstof var1 var2|safe var3 \"<strong>fallback value</strong>\"|safe %}\n\nYou can use the syntax ``{% firstof var1 var2 var3 as value %}`` to store the\noutput inside a variable.\n\n.. templatetag:: for\n\n``for``\n-------\n\nLoops over each item in an array, making the item available in a context\nvariable. For example, to display a list of athletes provided in\n``athlete_list``::\n\n    <ul>\n    {% for athlete in athlete_list %}\n        <li>{{ athlete.name }}</li>\n    {% endfor %}\n    </ul>\n\nYou can loop over a list in reverse by using\n``{% for obj in list reversed %}``.\n\nIf you need to loop over a list of lists, you can unpack the values\nin each sublist into individual variables. For example, if your context\ncontains a list of (x,y) coordinates called ``points``, you could use the\nfollowing to output the list of points::\n\n    {% for x, y in points %}\n        There is a point at {{ x }},{{ y }}\n    {% endfor %}\n\nThis can also be useful if you need to access the items in a dictionary.\nFor example, if your context contained a dictionary ``data``, the following\nwould display the keys and values of the dictionary::\n\n    {% for key, value in data.items %}\n        {{ key }}: {{ value }}\n    {% endfor %}\n\nKeep in mind that for the dot operator, dictionary key lookup takes precedence\nover method lookup. Therefore if the ``data`` dictionary contains a key named\n``'items'``, ``data.items`` will return ``data['items']`` instead of\n``data.items()``. Avoid adding keys that are named like dictionary methods if\nyou want to use those methods in a template (``items``, ``values``, ``keys``,\netc.). Read more about the lookup order of the dot operator in the\n:ref:`documentation of template variables <template-variables>`.\n\nThe for loop sets a number of variables available within the loop:\n\n==========================  ===============================================\nVariable                    Description\n==========================  ===============================================\n``forloop.counter``         The current iteration of the loop (1-indexed)\n``forloop.counter0``        The current iteration of the loop (0-indexed)\n``forloop.revcounter``      The number of iterations from the end of the\n                            loop (1-indexed)\n``forloop.revcounter0``     The number of iterations from the end of the\n                            loop (0-indexed)\n``forloop.first``           True if this is the first time through the loop\n``forloop.last``            True if this is the last time through the loop\n``forloop.parentloop``      For nested loops, this is the loop surrounding\n                            the current one\n==========================  ===============================================\n\n``for`` ... ``empty``\n---------------------\n\nThe ``for`` tag can take an optional ``{% empty %}`` clause whose text is\ndisplayed if the given array is empty or could not be found::\n\n    <ul>\n    {% for athlete in athlete_list %}\n        <li>{{ athlete.name }}</li>\n    {% empty %}\n        <li>Sorry, no athletes in this list.</li>\n    {% endfor %}\n    </ul>\n\nThe above is equivalent to -- but shorter, cleaner, and possibly faster\nthan -- the following::\n\n    <ul>\n      {% if athlete_list %}\n        {% for athlete in athlete_list %}\n          <li>{{ athlete.name }}</li>\n        {% endfor %}\n      {% else %}\n        <li>Sorry, no athletes in this list.</li>\n      {% endif %}\n    </ul>\n\n.. templatetag:: if\n\n``if``\n------\n\nThe ``{% if %}`` tag evaluates a variable, and if that variable is \"true\" (i.e.\nexists, is not empty, and is not a false boolean value) the contents of the\nblock are output::\n\n    {% if athlete_list %}\n        Number of athletes: {{ athlete_list|length }}\n    {% elif athlete_in_locker_room_list %}\n        Athletes should be out of the locker room soon!\n    {% else %}\n        No athletes.\n    {% endif %}\n\nIn the above, if ``athlete_list`` is not empty, the number of athletes will be\ndisplayed by the ``{{ athlete_list|length }}`` variable.\n\nAs you can see, the ``if`` tag may take one or several ``{% elif %}``\nclauses, as well as an ``{% else %}`` clause that will be displayed if all\nprevious conditions fail. These clauses are optional.\n\nBoolean operators\n~~~~~~~~~~~~~~~~~\n\n:ttag:`if` tags may use ``and``, ``or`` or ``not`` to test a number of\nvariables or to negate a given variable::\n\n    {% if athlete_list and coach_list %}\n        Both athletes and coaches are available.\n    {% endif %}\n\n    {% if not athlete_list %}\n        There are no athletes.\n    {% endif %}\n\n    {% if athlete_list or coach_list %}\n        There are some athletes or some coaches.\n    {% endif %}\n\n    {% if not athlete_list or coach_list %}\n        There are no athletes or there are some coaches.\n    {% endif %}\n\n    {% if athlete_list and not coach_list %}\n        There are some athletes and absolutely no coaches.\n    {% endif %}\n\nUse of both ``and`` and ``or`` clauses within the same tag is allowed, with\n``and`` having higher precedence than ``or`` e.g.::\n\n    {% if athlete_list and coach_list or cheerleader_list %}\n\nwill be interpreted like:\n\n.. code-block:: python\n\n    if (athlete_list and coach_list) or cheerleader_list\n\nUse of actual parentheses in the :ttag:`if` tag is invalid syntax. If you need\nthem to indicate precedence, you should use nested :ttag:`if` tags.\n\n:ttag:`if` tags may also use the operators ``==``, ``!=``, ``<``, ``>``,\n``<=``, ``>=``, ``in``, ``not in``, ``is``, and ``is not`` which work as\nfollows:\n\n``==`` operator\n^^^^^^^^^^^^^^^\n\nEquality. Example::\n\n    {% if somevar == \"x\" %}\n      This appears if variable somevar equals the string \"x\"\n    {% endif %}\n\n``!=`` operator\n^^^^^^^^^^^^^^^\n\nInequality. Example::\n\n    {% if somevar != \"x\" %}\n      This appears if variable somevar does not equal the string \"x\",\n      or if somevar is not found in the context\n    {% endif %}\n\n``<`` operator\n^^^^^^^^^^^^^^\n\nLess than. Example::\n\n    {% if somevar < 100 %}\n      This appears if variable somevar is less than 100.\n    {% endif %}\n\n``>`` operator\n^^^^^^^^^^^^^^\n\nGreater than. Example::\n\n    {% if somevar > 0 %}\n      This appears if variable somevar is greater than 0.\n    {% endif %}\n\n``<=`` operator\n^^^^^^^^^^^^^^^\n\nLess than or equal to. Example::\n\n    {% if somevar <= 100 %}\n      This appears if variable somevar is less than 100 or equal to 100.\n    {% endif %}\n\n``>=`` operator\n^^^^^^^^^^^^^^^\n\nGreater than or equal to. Example::\n\n    {% if somevar >= 1 %}\n      This appears if variable somevar is greater than 1 or equal to 1.\n    {% endif %}\n\n``in`` operator\n^^^^^^^^^^^^^^^\n\nContained within. This operator is supported by many Python containers to test\nwhether the given value is in the container. The following are some examples\nof how ``x in y`` will be interpreted::\n\n    {% if \"bc\" in \"abcdef\" %}\n      This appears since \"bc\" is a substring of \"abcdef\"\n    {% endif %}\n\n    {% if \"hello\" in greetings %}\n      If greetings is a list or set, one element of which is the string\n      \"hello\", this will appear.\n    {% endif %}\n\n    {% if user in users %}\n      If users is a QuerySet, this will appear if user is an\n      instance that belongs to the QuerySet.\n    {% endif %}\n\n``not in`` operator\n^^^^^^^^^^^^^^^^^^^\n\nNot contained within. This is the negation of the ``in`` operator.\n\n``is`` operator\n^^^^^^^^^^^^^^^\n\nObject identity. Tests if two values are the same object. Example::\n\n    {% if somevar is True %}\n      This appears if and only if somevar is True.\n    {% endif %}\n\n    {% if somevar is None %}\n      This appears if somevar is None, or if somevar is not found in the context.\n    {% endif %}\n\n``is not`` operator\n^^^^^^^^^^^^^^^^^^^\n\nNegated object identity. Tests if two values are not the same object. This is\nthe negation of the ``is`` operator. Example::\n\n    {% if somevar is not True %}\n      This appears if somevar is not True, or if somevar is not found in the\n      context.\n    {% endif %}\n\n    {% if somevar is not None %}\n      This appears if and only if somevar is not None.\n    {% endif %}\n\nFilters\n~~~~~~~\n\nYou can also use filters in the :ttag:`if` expression. For example::\n\n    {% if messages|length >= 100 %}\n       You have lots of messages today!\n    {% endif %}\n\nComplex expressions\n~~~~~~~~~~~~~~~~~~~\n\nAll of the above can be combined to form complex expressions. For such\nexpressions, it can be important to know how the operators are grouped when the\nexpression is evaluated - that is, the precedence rules. The precedence of the\noperators, from lowest to highest, is as follows:\n\n* ``or``\n* ``and``\n* ``not``\n* ``in``\n* ``==``, ``!=``, ``<``, ``>``, ``<=``, ``>=``\n\n(This follows Python exactly). So, for example, the following complex\n:ttag:`if` tag::\n\n    {% if a == b or c == d and e %}\n\n...will be interpreted as:\n\n.. code-block:: python\n\n    (a == b) or ((c == d) and e)\n\nIf you need different precedence, you will need to use nested :ttag:`if` tags.\nSometimes that is better for clarity anyway, for the sake of those who do not\nknow the precedence rules.\n\nThe comparison operators cannot be 'chained' like in Python or in mathematical\nnotation. For example, instead of using::\n\n    {% if a > b > c %}  (WRONG)\n\nyou should use::\n\n    {% if a > b and b > c %}\n\n``ifequal`` and ``ifnotequal``\n------------------------------\n\n.. deprecated:: 3.1\n\n``{% ifequal a b %} ... {% endifequal %}`` is an obsolete way to write\n``{% if a == b %} ... {% endif %}``. Likewise, ``{% ifnotequal a b %} ...\n{% endifnotequal %}`` is superseded by ``{% if a != b %} ... {% endif %}``.\n\n.. templatetag:: ifchanged\n\n``ifchanged``\n-------------\n\nCheck if a value has changed from the last iteration of a loop.\n\nThe ``{% ifchanged %}`` block tag is used within a loop. It has two possible\nuses.\n\n1. Checks its own rendered contents against its previous state and only\n   displays the content if it has changed. For example, this displays a list of\n   days, only displaying the month if it changes::\n\n        <h1>Archive for {{ year }}</h1>\n\n        {% for date in days %}\n            {% ifchanged %}<h3>{{ date|date:\"F\" }}</h3>{% endifchanged %}\n            <a href=\"{{ date|date:\"M/d\"|lower }}/\">{{ date|date:\"j\" }}</a>\n        {% endfor %}\n\n2. If given one or more variables, check whether any variable has changed.\n   For example, the following shows the date every time it changes, while\n   showing the hour if either the hour or the date has changed::\n\n        {% for date in days %}\n            {% ifchanged date.date %} {{ date.date }} {% endifchanged %}\n            {% ifchanged date.hour date.date %}\n                {{ date.hour }}\n            {% endifchanged %}\n        {% endfor %}\n\nThe ``ifchanged`` tag can also take an optional ``{% else %}`` clause that\nwill be displayed if the value has not changed::\n\n        {% for match in matches %}\n            <div style=\"background-color:\n                {% ifchanged match.ballot_id %}\n                    {% cycle \"red\" \"blue\" %}\n                {% else %}\n                    gray\n                {% endifchanged %}\n            \">{{ match }}</div>\n        {% endfor %}\n\n.. templatetag:: include\n\n``include``\n-----------\n\nLoads a template and renders it with the current context. This is a way of\n\"including\" other templates within a template.\n\nThe template name can either be a variable or a hard-coded (quoted) string,\nin either single or double quotes.\n\nThis example includes the contents of the template ``\"foo/bar.html\"``::\n\n    {% include \"foo/bar.html\" %}\n\nNormally the template name is relative to the template loader's root directory.\nA string argument may also be a relative path starting with ``./`` or ``../``\nas described in the :ttag:`extends` tag.\n\nThis example includes the contents of the template whose name is contained in\nthe variable ``template_name``::\n\n    {% include template_name %}\n\nThe variable may also be any object with a ``render()`` method that accepts a\ncontext. This allows you to reference a compiled ``Template`` in your context.\n\nAdditionally, the variable may be an iterable of template names, in which case\nthe first that can be loaded will be used, as per\n:func:`~django.template.loader.select_template`.\n\nAn included template is rendered within the context of the template that\nincludes it. This example produces the output ``\"Hello, John!\"``:\n\n* Context: variable ``person`` is set to ``\"John\"`` and variable ``greeting``\n  is set to ``\"Hello\"``.\n\n* Template::\n\n    {% include \"name_snippet.html\" %}\n\n* The ``name_snippet.html`` template::\n\n    {{ greeting }}, {{ person|default:\"friend\" }}!\n\nYou can pass additional context to the template using keyword arguments::\n\n    {% include \"name_snippet.html\" with person=\"Jane\" greeting=\"Hello\" %}\n\nIf you want to render the context only with the variables provided (or even\nno variables at all), use the ``only`` option. No other variables are\navailable to the included template::\n\n    {% include \"name_snippet.html\" with greeting=\"Hi\" only %}\n\n.. note::\n    The :ttag:`include` tag should be considered as an implementation of\n    \"render this subtemplate and include the HTML\", not as \"parse this\n    subtemplate and include its contents as if it were part of the parent\".\n    This means that there is no shared state between included templates --\n    each include is a completely independent rendering process.\n\n    Blocks are evaluated *before* they are included. This means that a template\n    that includes blocks from another will contain blocks that have *already\n    been evaluated and rendered* - not blocks that can be overridden by, for\n    example, an extending template.\n\n.. versionchanged:: 3.1\n\n    Support for iterables of template names was added.\n\n.. templatetag:: load\n\n``load``\n--------\n\nLoads a custom template tag set.\n\nFor example, the following template would load all the tags and filters\nregistered in ``somelibrary`` and ``otherlibrary`` located in package\n``package``::\n\n    {% load somelibrary package.otherlibrary %}\n\nYou can also selectively load individual filters or tags from a library, using\nthe ``from`` argument. In this example, the template tags/filters named ``foo``\nand ``bar`` will be loaded from ``somelibrary``::\n\n    {% load foo bar from somelibrary %}\n\nSee :doc:`Custom tag and filter libraries </howto/custom-template-tags>` for\nmore information.\n\n.. templatetag:: lorem\n\n``lorem``\n---------\n\nDisplays random \"lorem ipsum\" Latin text. This is useful for providing sample\ndata in templates.\n\nUsage::\n\n    {% lorem [count] [method] [random] %}\n\nThe ``{% lorem %}`` tag can be used with zero, one, two or three arguments.\nThe arguments are:\n\n===========  =============================================================\nArgument     Description\n===========  =============================================================\n``count``    A number (or variable) containing the number of paragraphs or\n             words to generate (default is 1).\n``method``   Either ``w`` for words, ``p`` for HTML paragraphs or ``b``\n             for plain-text paragraph blocks (default is ``b``).\n``random``   The word ``random``, which if given, does not use the common\n             paragraph (\"Lorem ipsum dolor sit amet...\") when generating\n             text.\n===========  =============================================================\n\nExamples:\n\n* ``{% lorem %}`` will output the common \"lorem ipsum\" paragraph.\n* ``{% lorem 3 p %}`` will output the common \"lorem ipsum\" paragraph\n  and two random paragraphs each wrapped in HTML ``<p>`` tags.\n* ``{% lorem 2 w random %}`` will output two random Latin words.\n\n.. templatetag:: now\n\n``now``\n-------\n\nDisplays the current date and/or time, using a format according to the given\nstring. Such string can contain format specifiers characters as described\nin the :tfilter:`date` filter section.\n\nExample::\n\n    It is {% now \"jS F Y H:i\" %}\n\nNote that you can backslash-escape a format string if you want to use the\n\"raw\" value. In this example, both \"o\" and \"f\" are backslash-escaped, because\notherwise each is a format string that displays the year and the time,\nrespectively::\n\n    It is the {% now \"jS \\o\\f F\" %}\n\nThis would display as \"It is the 4th of September\".\n\n.. note::\n\n    The format passed can also be one of the predefined ones\n    :setting:`DATE_FORMAT`, :setting:`DATETIME_FORMAT`,\n    :setting:`SHORT_DATE_FORMAT` or :setting:`SHORT_DATETIME_FORMAT`.\n    The predefined formats may vary depending on the current locale and\n    if :doc:`/topics/i18n/formatting` is enabled, e.g.::\n\n        It is {% now \"SHORT_DATETIME_FORMAT\" %}\n\nYou can also use the syntax ``{% now \"Y\" as current_year %}`` to store the\noutput (as a string) inside a variable. This is useful if you want to use\n``{% now %}`` inside a template tag like :ttag:`blocktranslate` for example::\n\n    {% now \"Y\" as current_year %}\n    {% blocktranslate %}Copyright {{ current_year }}{% endblocktranslate %}\n\n.. templatetag:: regroup\n\n``regroup``\n-----------\n\nRegroups a list of alike objects by a common attribute.\n\nThis complex tag is best illustrated by way of an example: say that ``cities``\nis a list of cities represented by dictionaries containing ``\"name\"``,\n``\"population\"``, and ``\"country\"`` keys:\n\n.. code-block:: python\n\n    cities = [\n        {'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'},\n        {'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'},\n        {'name': 'New York', 'population': '20,000,000', 'country': 'USA'},\n        {'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'},\n        {'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'},\n    ]\n\n...and you'd like to display a hierarchical list that is ordered by country,\nlike this:\n\n* India\n\n  * Mumbai: 19,000,000\n  * Calcutta: 15,000,000\n\n* USA\n\n  * New York: 20,000,000\n  * Chicago: 7,000,000\n\n* Japan\n\n  * Tokyo: 33,000,000\n\nYou can use the ``{% regroup %}`` tag to group the list of cities by country.\nThe following snippet of template code would accomplish this::\n\n    {% regroup cities by country as country_list %}\n\n    <ul>\n    {% for country in country_list %}\n        <li>{{ country.grouper }}\n        <ul>\n            {% for city in country.list %}\n              <li>{{ city.name }}: {{ city.population }}</li>\n            {% endfor %}\n        </ul>\n        </li>\n    {% endfor %}\n    </ul>\n\nLet's walk through this example. ``{% regroup %}`` takes three arguments: the\nlist you want to regroup, the attribute to group by, and the name of the\nresulting list. Here, we're regrouping the ``cities`` list by the ``country``\nattribute and calling the result ``country_list``.\n\n``{% regroup %}`` produces a list (in this case, ``country_list``) of\n**group objects**. Group objects are instances of\n:py:func:`~collections.namedtuple` with two fields:\n\n* ``grouper`` -- the item that was grouped by (e.g., the string \"India\" or\n  \"Japan\").\n* ``list`` -- a list of all items in this group (e.g., a list of all cities\n  with country='India').\n\nBecause ``{% regroup %}`` produces :py:func:`~collections.namedtuple` objects,\nyou can also write the previous example as::\n\n    {% regroup cities by country as country_list %}\n\n    <ul>\n    {% for country, local_cities in country_list %}\n        <li>{{ country }}\n        <ul>\n            {% for city in local_cities %}\n              <li>{{ city.name }}: {{ city.population }}</li>\n            {% endfor %}\n        </ul>\n        </li>\n    {% endfor %}\n    </ul>\n\nNote that ``{% regroup %}`` does not order its input! Our example relies on\nthe fact that the ``cities`` list was ordered by ``country`` in the first place.\nIf the ``cities`` list did *not* order its members by ``country``, the\nregrouping would naively display more than one group for a single country. For\nexample, say the ``cities`` list was set to this (note that the countries are not\ngrouped together):\n\n.. code-block:: python\n\n    cities = [\n        {'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'},\n        {'name': 'New York', 'population': '20,000,000', 'country': 'USA'},\n        {'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'},\n        {'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'},\n        {'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'},\n    ]\n\nWith this input for ``cities``, the example ``{% regroup %}`` template code\nabove would result in the following output:\n\n* India\n\n  * Mumbai: 19,000,000\n\n* USA\n\n  * New York: 20,000,000\n\n* India\n\n  * Calcutta: 15,000,000\n\n* USA\n\n  * Chicago: 7,000,000\n\n* Japan\n\n  * Tokyo: 33,000,000\n\nThe easiest solution to this gotcha is to make sure in your view code that the\ndata is ordered according to how you want to display it.\n\nAnother solution is to sort the data in the template using the\n:tfilter:`dictsort` filter, if your data is in a list of dictionaries::\n\n    {% regroup cities|dictsort:\"country\" by country as country_list %}\n\nGrouping on other properties\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nAny valid template lookup is a legal grouping attribute for the regroup\ntag, including methods, attributes, dictionary keys and list items. For\nexample, if the \"country\" field is a foreign key to a class with\nan attribute \"description,\" you could use::\n\n    {% regroup cities by country.description as country_list %}\n\nOr, if ``country`` is a field with ``choices``, it will have a\n:meth:`~django.db.models.Model.get_FOO_display` method available as an\nattribute, allowing  you to group on the display string rather than the\n``choices`` key::\n\n    {% regroup cities by get_country_display as country_list %}\n\n``{{ country.grouper }}`` will now display the value fields from the\n``choices`` set rather than the keys.\n\n.. templatetag:: resetcycle\n\n``resetcycle``\n--------------\n\nResets a previous `cycle`_ so that it restarts from its first item at its next\nencounter. Without arguments, ``{% resetcycle %}`` will reset the last\n``{% cycle %}`` defined in the template.\n\nExample usage::\n\n    {% for coach in coach_list %}\n        <h1>{{ coach.name }}</h1>\n        {% for athlete in coach.athlete_set.all %}\n            <p class=\"{% cycle 'odd' 'even' %}\">{{ athlete.name }}</p>\n        {% endfor %}\n        {% resetcycle %}\n    {% endfor %}\n\nThis example would return this HTML::\n\n    <h1>José Mourinho</h1>\n    <p class=\"odd\">Thibaut Courtois</p>\n    <p class=\"even\">John Terry</p>\n    <p class=\"odd\">Eden Hazard</p>\n\n    <h1>Carlo Ancelotti</h1>\n    <p class=\"odd\">Manuel Neuer</p>\n    <p class=\"even\">Thomas Müller</p>\n\nNotice how the first block ends with ``class=\"odd\"`` and the new one starts\nwith ``class=\"odd\"``. Without the ``{% resetcycle %}`` tag, the second block\nwould start with ``class=\"even\"``.\n\nYou can also reset named cycle tags::\n\n    {% for item in list %}\n        <p class=\"{% cycle 'odd' 'even' as stripe %} {% cycle 'major' 'minor' 'minor' 'minor' 'minor' as tick %}\">\n            {{ item.data }}\n        </p>\n        {% ifchanged item.category %}\n            <h1>{{ item.category }}</h1>\n            {% if not forloop.first %}{% resetcycle tick %}{% endif %}\n        {% endifchanged %}\n    {% endfor %}\n\nIn this example, we have both the alternating odd/even rows and a \"major\" row\nevery fifth row. Only the five-row cycle is reset when a category changes.\n\n.. templatetag:: spaceless\n\n``spaceless``\n-------------\n\nRemoves whitespace between HTML tags. This includes tab\ncharacters and newlines.\n\nExample usage::\n\n    {% spaceless %}\n        <p>\n            <a href=\"foo/\">Foo</a>\n        </p>\n    {% endspaceless %}\n\nThis example would return this HTML::\n\n    <p><a href=\"foo/\">Foo</a></p>\n\nOnly space between *tags* is removed -- not space between tags and text. In\nthis example, the space around ``Hello`` won't be stripped::\n\n    {% spaceless %}\n        <strong>\n            Hello\n        </strong>\n    {% endspaceless %}\n\n.. templatetag:: templatetag\n\n``templatetag``\n---------------\n\nOutputs one of the syntax characters used to compose template tags.\n\nSince the template system has no concept of \"escaping\", to display one of the\nbits used in template tags, you must use the ``{% templatetag %}`` tag.\n\nThe argument tells which template bit to output:\n\n==================  =======\nArgument            Outputs\n==================  =======\n``openblock``       ``{%``\n``closeblock``      ``%}``\n``openvariable``    ``{{``\n``closevariable``   ``}}``\n``openbrace``       ``{``\n``closebrace``      ``}``\n``opencomment``     ``{#``\n``closecomment``    ``#}``\n==================  =======\n\nSample usage::\n\n    {% templatetag openblock %} url 'entry_list' {% templatetag closeblock %}\n\n.. templatetag:: url\n\n``url``\n-------\n\nReturns an absolute path reference (a URL without the domain name) matching a\ngiven view and optional parameters. Any special characters in the resulting\npath will be encoded using :func:`~django.utils.encoding.iri_to_uri`.\n\nThis is a way to output links without violating the DRY principle by having to\nhard-code URLs in your templates::\n\n    {% url 'some-url-name' v1 v2 %}\n\nThe first argument is a :ref:`URL pattern name <naming-url-patterns>`. It can\nbe a quoted literal or any other context variable. Additional arguments are\noptional and should be space-separated values that will be used as arguments in\nthe URL. The example above shows passing positional arguments. Alternatively\nyou may use keyword syntax::\n\n    {% url 'some-url-name' arg1=v1 arg2=v2 %}\n\nDo not mix both positional and keyword syntax in a single call. All arguments\nrequired by the URLconf should be present.\n\nFor example, suppose you have a view, ``app_views.client``, whose URLconf\ntakes a client ID (here, ``client()`` is a method inside the views file\n``app_views.py``). The URLconf line might look like this:\n\n.. code-block:: python\n\n    path('client/<int:id>/', app_views.client, name='app-views-client')\n\nIf this app's URLconf is included into the project's URLconf under a path\nsuch as this:\n\n.. code-block:: python\n\n    path('clients/', include('project_name.app_name.urls'))\n\n...then, in a template, you can create a link to this view like this::\n\n    {% url 'app-views-client' client.id %}\n\nThe template tag will output the string ``/clients/client/123/``.\n\nNote that if the URL you're reversing doesn't exist, you'll get an\n:exc:`~django.urls.NoReverseMatch` exception raised, which will cause your\nsite to display an error page.\n\nIf you'd like to retrieve a URL without displaying it, you can use a slightly\ndifferent call::\n\n    {% url 'some-url-name' arg arg2 as the_url %}\n\n    <a href=\"{{ the_url }}\">I'm linking to {{ the_url }}</a>\n\nThe scope of the variable created by the  ``as var`` syntax is the\n``{% block %}`` in which the ``{% url %}`` tag appears.\n\nThis ``{% url ... as var %}`` syntax will *not* cause an error if the view is\nmissing. In practice you'll use this to link to views that are optional::\n\n    {% url 'some-url-name' as the_url %}\n    {% if the_url %}\n      <a href=\"{{ the_url }}\">Link to optional stuff</a>\n    {% endif %}\n\nIf you'd like to retrieve a namespaced URL, specify the fully qualified name::\n\n    {% url 'myapp:view-name' %}\n\nThis will follow the normal :ref:`namespaced URL resolution strategy\n<topics-http-reversing-url-namespaces>`, including using any hints provided\nby the context as to the current application.\n\n.. warning::\n\n    Don't forget to put quotes around the URL pattern ``name``, otherwise the\n    value will be interpreted as a context variable!\n\n.. templatetag:: verbatim\n\n``verbatim``\n------------\n\nStops the template engine from rendering the contents of this block tag.\n\nA common use is to allow a JavaScript template layer that collides with\nDjango's syntax. For example::\n\n    {% verbatim %}\n        {{if dying}}Still alive.{{/if}}\n    {% endverbatim %}\n\nYou can also designate a specific closing tag, allowing the use of\n``{% endverbatim %}`` as part of the unrendered contents::\n\n    {% verbatim myblock %}\n        Avoid template rendering via the {% verbatim %}{% endverbatim %} block.\n    {% endverbatim myblock %}\n\n.. templatetag:: widthratio\n\n``widthratio``\n--------------\n\nFor creating bar charts and such, this tag calculates the ratio of a given\nvalue to a maximum value, and then applies that ratio to a constant.\n\nFor example::\n\n    <img src=\"bar.png\" alt=\"Bar\"\n         height=\"10\" width=\"{% widthratio this_value max_value max_width %}\">\n\nIf ``this_value`` is 175, ``max_value`` is 200, and ``max_width`` is 100, the\nimage in the above example will be 88 pixels wide\n(because 175/200 = .875; .875 * 100 = 87.5 which is rounded up to 88).\n\nIn some cases you might want to capture the result of ``widthratio`` in a\nvariable. It can be useful, for instance, in a :ttag:`blocktranslate` like this::\n\n    {% widthratio this_value max_value max_width as width %}\n    {% blocktranslate %}The width is: {{ width }}{% endblocktranslate %}\n\n.. templatetag:: with\n\n``with``\n--------\n\nCaches a complex variable under a simpler name. This is useful when accessing\nan \"expensive\" method (e.g., one that hits the database) multiple times.\n\nFor example::\n\n    {% with total=business.employees.count %}\n        {{ total }} employee{{ total|pluralize }}\n    {% endwith %}\n\nThe populated variable (in the example above, ``total``) is only available\nbetween the ``{% with %}`` and ``{% endwith %}`` tags.\n\nYou can assign more than one context variable::\n\n    {% with alpha=1 beta=2 %}\n        ...\n    {% endwith %}\n\n.. note:: The previous more verbose format is still supported:\n   ``{% with business.employees.count as total %}``\n\n.. _ref-templates-builtins-filters:\n\nBuilt-in filter reference\n=========================\n\n.. templatefilter:: add\n\n``add``\n-------\n\nAdds the argument to the value.\n\nFor example::\n\n    {{ value|add:\"2\" }}\n\nIf ``value`` is ``4``, then the output will be ``6``.\n\nThis filter will first try to coerce both values to integers. If this fails,\nit'll attempt to add the values together anyway. This will work on some data\ntypes (strings, list, etc.) and fail on others. If it fails, the result will\nbe an empty string.\n\nFor example, if we have::\n\n    {{ first|add:second }}\n\nand ``first`` is ``[1, 2, 3]`` and ``second`` is ``[4, 5, 6]``, then the\noutput will be ``[1, 2, 3, 4, 5, 6]``.\n\n.. warning::\n\n    Strings that can be coerced to integers will be **summed**, not\n    concatenated, as in the first example above.\n\n.. templatefilter:: addslashes\n\n``addslashes``\n--------------\n\nAdds slashes before quotes. Useful for escaping strings in CSV, for example.\n\nFor example::\n\n    {{ value|addslashes }}\n\nIf ``value`` is ``\"I'm using Django\"``, the output will be\n``\"I\\'m using Django\"``.\n\n.. templatefilter:: capfirst\n\n``capfirst``\n------------\n\nCapitalizes the first character of the value. If the first character is not\na letter, this filter has no effect.\n\nFor example::\n\n    {{ value|capfirst }}\n\nIf ``value`` is ``\"django\"``, the output will be ``\"Django\"``.\n\n.. templatefilter:: center\n\n``center``\n----------\n\nCenters the value in a field of a given width.\n\nFor example::\n\n    \"{{ value|center:\"15\" }}\"\n\nIf ``value`` is ``\"Django\"``, the output will be ``\"     Django    \"``.\n\n.. templatefilter:: cut\n\n``cut``\n-------\n\nRemoves all values of arg from the given string.\n\nFor example::\n\n    {{ value|cut:\" \" }}\n\nIf ``value`` is ``\"String with spaces\"``, the output will be\n``\"Stringwithspaces\"``.\n\n.. templatefilter:: date\n\n``date``\n--------\n\nFormats a date according to the given format.\n\nUses a similar format as PHP's ``date()`` function (https://php.net/date)\nwith some differences.\n\n.. note::\n    These format characters are not used in Django outside of templates. They\n    were designed to be compatible with PHP to ease transitioning for designers.\n\n.. _date-and-time-formatting-specifiers:\n\nAvailable format strings:\n\n================  ========================================  =====================\nFormat character  Description                               Example output\n================  ========================================  =====================\n**Day**\n``d``             Day of the month, 2 digits with           ``'01'`` to ``'31'``\n                  leading zeros.\n``j``             Day of the month without leading          ``'1'`` to ``'31'``\n                  zeros.\n``D``             Day of the week, textual, 3 letters.      ``'Fri'``\n``l``             Day of the week, textual, long.           ``'Friday'``\n``S``             English ordinal suffix for day of the     ``'st'``, ``'nd'``, ``'rd'`` or ``'th'``\n                  month, 2 characters.\n``w``             Day of the week, digits without           ``'0'`` (Sunday) to ``'6'`` (Saturday)\n                  leading zeros.\n``z``             Day of the year.                          ``1`` to ``366``\n**Week**\n``W``             ISO-8601 week number of year, with        ``1``, ``53``\n                  weeks starting on Monday.\n**Month**\n``m``             Month, 2 digits with leading zeros.       ``'01'`` to ``'12'``\n``n``             Month without leading zeros.              ``'1'`` to ``'12'``\n``M``             Month, textual, 3 letters.                ``'Jan'``\n``b``             Month, textual, 3 letters, lowercase.     ``'jan'``\n``E``             Month, locale specific alternative\n                  representation usually used for long\n                  date representation.                      ``'listopada'`` (for Polish locale, as opposed to ``'Listopad'``)\n``F``             Month, textual, long.                     ``'January'``\n``N``             Month abbreviation in Associated Press    ``'Jan.'``, ``'Feb.'``, ``'March'``, ``'May'``\n                  style. Proprietary extension.\n``t``             Number of days in the given month.        ``28`` to ``31``\n**Year**\n``y``             Year, 2 digits.                           ``'99'``\n``Y``             Year, 4 digits.                           ``'1999'``\n``L``             Boolean for whether it's a leap year.     ``True`` or ``False``\n``o``             ISO-8601 week-numbering year,             ``'1999'``\n                  corresponding to the ISO-8601 week\n                  number (W) which uses leap weeks. See Y\n                  for the more common year format.\n**Time**\n``g``             Hour, 12-hour format without leading      ``'1'`` to ``'12'``\n                  zeros.\n``G``             Hour, 24-hour format without leading      ``'0'`` to ``'23'``\n                  zeros.\n``h``             Hour, 12-hour format.                     ``'01'`` to ``'12'``\n``H``             Hour, 24-hour format.                     ``'00'`` to ``'23'``\n``i``             Minutes.                                  ``'00'`` to ``'59'``\n``s``             Seconds, 2 digits with leading zeros.     ``'00'`` to ``'59'``\n``u``             Microseconds.                             ``000000`` to ``999999``\n``a``             ``'a.m.'`` or ``'p.m.'`` (Note that       ``'a.m.'``\n                  this is slightly different than PHP's\n                  output, because this includes periods\n                  to match Associated Press style.)\n``A``             ``'AM'`` or ``'PM'``.                     ``'AM'``\n``f``             Time, in 12-hour hours and minutes,       ``'1'``, ``'1:30'``\n                  with minutes left off if they're zero.\n                  Proprietary extension.\n``P``             Time, in 12-hour hours, minutes and       ``'1 a.m.'``, ``'1:30 p.m.'``, ``'midnight'``, ``'noon'``, ``'12:30 p.m.'``\n                  'a.m.'/'p.m.', with minutes left off\n                  if they're zero and the special-case\n                  strings 'midnight' and 'noon' if\n                  appropriate. Proprietary extension.\n**Timezone**\n``e``             Timezone name. Could be in any format,\n                  or might return an empty string,          ``''``, ``'GMT'``, ``'-500'``, ``'US/Eastern'``, etc.\n                  depending on the datetime.\n``I``             Daylight Savings Time, whether it's       ``'1'`` or ``'0'``\n                  in effect or not.\n``O``             Difference to Greenwich time in hours.    ``'+0200'``\n``T``             Time zone of this machine.                ``'EST'``, ``'MDT'``\n``Z``             Time zone offset in seconds. The          ``-43200`` to ``43200``\n                  offset for timezones west of UTC is\n                  always negative, and for those east of\n                  UTC is always positive.\n**Date/Time**\n``c``             ISO 8601 format. (Note: unlike others     ``2008-01-02T10:30:00.000123+02:00``,\n                  formatters, such as \"Z\", \"O\" or \"r\",      or ``2008-01-02T10:30:00.000123`` if the datetime is naive\n                  the \"c\" formatter will not add timezone\n                  offset if value is a naive datetime\n                  (see :class:`datetime.tzinfo`).\n``r``             :rfc:`RFC 5322 <5322#section-3.3>`        ``'Thu, 21 Dec 2000 16:01:07 +0200'``\n                  formatted date.\n``U``             Seconds since the Unix Epoch\n                  (January 1 1970 00:00:00 UTC).\n================  ========================================  =====================\n\nFor example::\n\n    {{ value|date:\"D d M Y\" }}\n\nIf ``value`` is a :py:class:`~datetime.datetime` object (e.g., the result of\n``datetime.datetime.now()``), the output will be the string\n``'Wed 09 Jan 2008'``.\n\nThe format passed can be one of the predefined ones :setting:`DATE_FORMAT`,\n:setting:`DATETIME_FORMAT`, :setting:`SHORT_DATE_FORMAT` or\n:setting:`SHORT_DATETIME_FORMAT`, or a custom format that uses the format\nspecifiers shown in the table above. Note that predefined formats may vary\ndepending on the current locale.\n\nAssuming that :setting:`USE_L10N` is ``True`` and :setting:`LANGUAGE_CODE` is,\nfor example, ``\"es\"``, then for::\n\n    {{ value|date:\"SHORT_DATE_FORMAT\" }}\n\nthe output would be the string ``\"09/01/2008\"`` (the ``\"SHORT_DATE_FORMAT\"``\nformat specifier for the ``es`` locale as shipped with Django is ``\"d/m/Y\"``).\n\nWhen used without a format string, the ``DATE_FORMAT`` format specifier is\nused. Assuming the same settings as the previous example::\n\n    {{ value|date }}\n\noutputs ``9 de Enero de 2008`` (the ``DATE_FORMAT`` format specifier for the\n``es`` locale is ``r'j \\d\\e F \\d\\e Y'``). Both \"d\" and \"e\" are\nbackslash-escaped, because otherwise each is a format string that displays the\nday and the timezone name, respectively.\n\nYou can combine ``date`` with the :tfilter:`time` filter to render a full\nrepresentation of a ``datetime`` value. E.g.::\n\n    {{ value|date:\"D d M Y\" }} {{ value|time:\"H:i\" }}\n\n.. templatefilter:: default\n\n``default``\n-----------\n\nIf value evaluates to ``False``, uses the given default. Otherwise, uses the\nvalue.\n\nFor example::\n\n    {{ value|default:\"nothing\" }}\n\nIf ``value`` is ``\"\"`` (the empty string), the output will be ``nothing``.\n\n.. templatefilter:: default_if_none\n\n``default_if_none``\n-------------------\n\nIf (and only if) value is ``None``, uses the given default. Otherwise, uses the\nvalue.\n\nNote that if an empty string is given, the default value will *not* be used.\nUse the :tfilter:`default` filter if you want to fallback for empty strings.\n\nFor example::\n\n    {{ value|default_if_none:\"nothing\" }}\n\nIf ``value`` is ``None``, the output will be ``nothing``.\n\n.. templatefilter:: dictsort\n\n``dictsort``\n------------\n\nTakes a list of dictionaries and returns that list sorted by the key given in\nthe argument.\n\nFor example::\n\n    {{ value|dictsort:\"name\" }}\n\nIf ``value`` is:\n\n.. code-block:: python\n\n    [\n        {'name': 'zed', 'age': 19},\n        {'name': 'amy', 'age': 22},\n        {'name': 'joe', 'age': 31},\n    ]\n\nthen the output would be:\n\n.. code-block:: python\n\n    [\n        {'name': 'amy', 'age': 22},\n        {'name': 'joe', 'age': 31},\n        {'name': 'zed', 'age': 19},\n    ]\n\nYou can also do more complicated things like::\n\n    {% for book in books|dictsort:\"author.age\" %}\n        * {{ book.title }} ({{ book.author.name }})\n    {% endfor %}\n\nIf ``books`` is:\n\n.. code-block:: python\n\n    [\n        {'title': '1984', 'author': {'name': 'George', 'age': 45}},\n        {'title': 'Timequake', 'author': {'name': 'Kurt', 'age': 75}},\n        {'title': 'Alice', 'author': {'name': 'Lewis', 'age': 33}},\n    ]\n\nthen the output would be::\n\n    * Alice (Lewis)\n    * 1984 (George)\n    * Timequake (Kurt)\n\n``dictsort`` can also order a list of lists (or any other object implementing\n``__getitem__()``) by elements at specified index. For example::\n\n    {{ value|dictsort:0 }}\n\nIf ``value`` is:\n\n.. code-block:: python\n\n    [\n        ('a', '42'),\n        ('c', 'string'),\n        ('b', 'foo'),\n    ]\n\nthen the output would be:\n\n.. code-block:: python\n\n    [\n        ('a', '42'),\n        ('b', 'foo'),\n        ('c', 'string'),\n    ]\n\nYou must pass the index as an integer rather than a string. The following\nproduce empty output::\n\n    {{ values|dictsort:\"0\" }}\n\n.. templatefilter:: dictsortreversed\n\n``dictsortreversed``\n--------------------\n\nTakes a list of dictionaries and returns that list sorted in reverse order by\nthe key given in the argument. This works exactly the same as the above filter,\nbut the returned value will be in reverse order.\n\n.. templatefilter:: divisibleby\n\n``divisibleby``\n---------------\n\nReturns ``True`` if the value is divisible by the argument.\n\nFor example::\n\n    {{ value|divisibleby:\"3\" }}\n\nIf ``value`` is ``21``, the output would be ``True``.\n\n.. templatefilter:: escape\n\n``escape``\n----------\n\nEscapes a string's HTML. Specifically, it makes these replacements:\n\n* ``<`` is converted to ``&lt;``\n* ``>`` is converted to ``&gt;``\n* ``'`` (single quote) is converted to ``&#x27;``\n* ``\"`` (double quote) is converted to ``&quot;``\n* ``&`` is converted to ``&amp;``\n\nApplying ``escape`` to a variable that would normally have auto-escaping\napplied to the result will only result in one round of escaping being done. So\nit is safe to use this function even in auto-escaping environments. If you want\nmultiple escaping passes to be applied, use the :tfilter:`force_escape` filter.\n\nFor example, you can apply ``escape`` to fields when :ttag:`autoescape` is off::\n\n    {% autoescape off %}\n        {{ title|escape }}\n    {% endautoescape %}\n\n.. templatefilter:: escapejs\n\n``escapejs``\n------------\n\nEscapes characters for use in JavaScript strings. This does *not* make the\nstring safe for use in HTML or JavaScript template literals, but does protect\nyou from syntax errors when using templates to generate JavaScript/JSON.\n\nFor example::\n\n    {{ value|escapejs }}\n\nIf ``value`` is ``\"testing\\r\\njavascript 'string\\\" <b>escaping</b>\"``,\nthe output will be ``\"testing\\\\u000D\\\\u000Ajavascript \\\\u0027string\\\\u0022 \\\\u003Cb\\\\u003Eescaping\\\\u003C/b\\\\u003E\"``.\n\n.. templatefilter:: filesizeformat\n\n``filesizeformat``\n------------------\n\nFormats the value like a 'human-readable' file size (i.e. ``'13 KB'``,\n``'4.1 MB'``, ``'102 bytes'``, etc.).\n\nFor example::\n\n    {{ value|filesizeformat }}\n\nIf ``value`` is 123456789, the output would be ``117.7 MB``.\n\n.. admonition:: File sizes and SI units\n\n    Strictly speaking, ``filesizeformat`` does not conform to the International\n    System of Units which recommends using KiB, MiB, GiB, etc. when byte sizes\n    are calculated in powers of 1024 (which is the case here). Instead, Django\n    uses traditional unit names (KB, MB, GB, etc.) corresponding to names that\n    are more commonly used.\n\n.. templatefilter:: first\n\n``first``\n---------\n\nReturns the first item in a list.\n\nFor example::\n\n    {{ value|first }}\n\nIf ``value`` is the list ``['a', 'b', 'c']``, the output will be ``'a'``.\n\n.. templatefilter:: floatformat\n\n``floatformat``\n---------------\n\nWhen used without an argument, rounds a floating-point number to one decimal\nplace -- but only if there's a decimal part to be displayed. For example:\n\n============  ===========================  ========\n``value``     Template                     Output\n============  ===========================  ========\n``34.23234``  ``{{ value|floatformat }}``  ``34.2``\n``34.00000``  ``{{ value|floatformat }}``  ``34``\n``34.26000``  ``{{ value|floatformat }}``  ``34.3``\n============  ===========================  ========\n\nIf used with a numeric integer argument, ``floatformat`` rounds a number to\nthat many decimal places. For example:\n\n============  =============================  ==========\n``value``     Template                       Output\n============  =============================  ==========\n``34.23234``  ``{{ value|floatformat:3 }}``  ``34.232``\n``34.00000``  ``{{ value|floatformat:3 }}``  ``34.000``\n``34.26000``  ``{{ value|floatformat:3 }}``  ``34.260``\n============  =============================  ==========\n\nParticularly useful is passing 0 (zero) as the argument which will round the\nfloat to the nearest integer.\n\n============  ================================  ==========\n``value``     Template                          Output\n============  ================================  ==========\n``34.23234``  ``{{ value|floatformat:\"0\" }}``   ``34``\n``34.00000``  ``{{ value|floatformat:\"0\" }}``   ``34``\n``39.56000``  ``{{ value|floatformat:\"0\" }}``   ``40``\n============  ================================  ==========\n\nIf the argument passed to ``floatformat`` is negative, it will round a number\nto that many decimal places -- but only if there's a decimal part to be\ndisplayed. For example:\n\n============  ================================  ==========\n``value``     Template                          Output\n============  ================================  ==========\n``34.23234``  ``{{ value|floatformat:\"-3\" }}``  ``34.232``\n``34.00000``  ``{{ value|floatformat:\"-3\" }}``  ``34``\n``34.26000``  ``{{ value|floatformat:\"-3\" }}``  ``34.260``\n============  ================================  ==========\n\nUsing ``floatformat`` with no argument is equivalent to using ``floatformat``\nwith an argument of ``-1``.\n\n.. versionchanged:: 3.1\n\n    In older versions, a negative zero ``-0`` was returned for negative numbers\n    which round to zero.\n\n.. templatefilter:: force_escape\n\n``force_escape``\n----------------\n\nApplies HTML escaping to a string (see the :tfilter:`escape` filter for\ndetails). This filter is applied *immediately* and returns a new, escaped\nstring. This is useful in the rare cases where you need multiple escaping or\nwant to apply other filters to the escaped results. Normally, you want to use\nthe :tfilter:`escape` filter.\n\nFor example, if you want to catch the ``<p>`` HTML elements created by\nthe :tfilter:`linebreaks` filter::\n\n    {% autoescape off %}\n        {{ body|linebreaks|force_escape }}\n    {% endautoescape %}\n\n.. templatefilter:: get_digit\n\n``get_digit``\n-------------\n\nGiven a whole number, returns the requested digit, where 1 is the right-most\ndigit, 2 is the second-right-most digit, etc. Returns the original value for\ninvalid input (if input or argument is not an integer, or if argument is less\nthan 1). Otherwise, output is always an integer.\n\nFor example::\n\n    {{ value|get_digit:\"2\" }}\n\nIf ``value`` is ``123456789``, the output will be ``8``.\n\n.. templatefilter:: iriencode\n\n``iriencode``\n-------------\n\nConverts an IRI (Internationalized Resource Identifier) to a string that is\nsuitable for including in a URL. This is necessary if you're trying to use\nstrings containing non-ASCII characters in a URL.\n\nIt's safe to use this filter on a string that has already gone through the\n:tfilter:`urlencode` filter.\n\nFor example::\n\n    {{ value|iriencode }}\n\nIf ``value`` is ``\"?test=1&me=2\"``, the output will be ``\"?test=1&amp;me=2\"``.\n\n.. templatefilter:: join\n\n``join``\n--------\n\nJoins a list with a string, like Python's ``str.join(list)``\n\nFor example::\n\n    {{ value|join:\" // \" }}\n\nIf ``value`` is the list ``['a', 'b', 'c']``, the output will be the string\n``\"a // b // c\"``.\n\n.. templatefilter:: json_script\n\n``json_script``\n---------------\n\nSafely outputs a Python object as JSON, wrapped in a ``<script>`` tag, ready\nfor use with JavaScript.\n\n**Argument:** HTML \"id\" of the ``<script>`` tag.\n\nFor example::\n\n    {{ value|json_script:\"hello-data\" }}\n\nIf ``value`` is the dictionary ``{'hello': 'world'}``, the output will be:\n\n.. code-block:: html\n\n    <script id=\"hello-data\" type=\"application/json\">{\"hello\": \"world\"}</script>\n\nThe resulting data can be accessed in JavaScript like this:\n\n.. code-block:: javascript\n\n    var value = JSON.parse(document.getElementById('hello-data').textContent);\n\nXSS attacks are mitigated by escaping the characters \"<\", \">\" and \"&\". For\nexample if ``value`` is ``{'hello': 'world</script>&amp;'}``, the output is:\n\n.. code-block:: html\n\n    <script id=\"hello-data\" type=\"application/json\">{\"hello\": \"world\\\\u003C/script\\\\u003E\\\\u0026amp;\"}</script>\n\nThis is compatible with a strict Content Security Policy that prohibits in-page\nscript execution. It also maintains a clean separation between passive data and\nexecutable code.\n\n.. templatefilter:: last\n\n``last``\n--------\n\nReturns the last item in a list.\n\nFor example::\n\n    {{ value|last }}\n\nIf ``value`` is the list ``['a', 'b', 'c', 'd']``, the output will be the\nstring ``\"d\"``.\n\n.. templatefilter:: length\n\n``length``\n----------\n\nReturns the length of the value. This works for both strings and lists.\n\nFor example::\n\n    {{ value|length }}\n\nIf ``value`` is ``['a', 'b', 'c', 'd']`` or ``\"abcd\"``, the output will be\n``4``.\n\nThe filter returns ``0`` for an undefined variable.\n\n.. templatefilter:: length_is\n\n``length_is``\n-------------\n\nReturns ``True`` if the value's length is the argument, or ``False`` otherwise.\n\nFor example::\n\n    {{ value|length_is:\"4\" }}\n\nIf ``value`` is ``['a', 'b', 'c', 'd']`` or ``\"abcd\"``, the output will be\n``True``.\n\n.. templatefilter:: linebreaks\n\n``linebreaks``\n--------------\n\nReplaces line breaks in plain text with appropriate HTML; a single\nnewline becomes an HTML line break (``<br>``) and a new line\nfollowed by a blank line becomes a paragraph break (``</p>``).\n\nFor example::\n\n    {{ value|linebreaks }}\n\nIf ``value`` is ``Joel\\nis a slug``, the output will be ``<p>Joel<br>is a\nslug</p>``.\n\n.. templatefilter:: linebreaksbr\n\n``linebreaksbr``\n----------------\n\nConverts all newlines in a piece of plain text to HTML line breaks\n(``<br>``).\n\nFor example::\n\n    {{ value|linebreaksbr }}\n\nIf ``value`` is ``Joel\\nis a slug``, the output will be ``Joel<br>is a\nslug``.\n\n.. templatefilter:: linenumbers\n\n``linenumbers``\n---------------\n\nDisplays text with line numbers.\n\nFor example::\n\n    {{ value|linenumbers }}\n\nIf ``value`` is::\n\n    one\n    two\n    three\n\nthe output will be::\n\n    1. one\n    2. two\n    3. three\n\n.. templatefilter:: ljust\n\n``ljust``\n---------\n\nLeft-aligns the value in a field of a given width.\n\n**Argument:** field size\n\nFor example::\n\n    \"{{ value|ljust:\"10\" }}\"\n\nIf ``value`` is ``Django``, the output will be ``\"Django    \"``.\n\n.. templatefilter:: lower\n\n``lower``\n---------\n\nConverts a string into all lowercase.\n\nFor example::\n\n    {{ value|lower }}\n\nIf ``value`` is ``Totally LOVING this Album!``, the output will be\n``totally loving this album!``.\n\n.. templatefilter:: make_list\n\n``make_list``\n-------------\n\nReturns the value turned into a list. For a string, it's a list of characters.\nFor an integer, the argument is cast to a string before creating a list.\n\nFor example::\n\n    {{ value|make_list }}\n\nIf ``value`` is the string ``\"Joel\"``, the output would be the list\n``['J', 'o', 'e', 'l']``. If ``value`` is ``123``, the output will be the\nlist ``['1', '2', '3']``.\n\n.. templatefilter:: phone2numeric\n\n``phone2numeric``\n-----------------\n\nConverts a phone number (possibly containing letters) to its numerical\nequivalent.\n\nThe input doesn't have to be a valid phone number. This will happily convert\nany string.\n\nFor example::\n\n    {{ value|phone2numeric }}\n\nIf ``value`` is ``800-COLLECT``, the output will be ``800-2655328``.\n\n.. templatefilter:: pluralize\n\n``pluralize``\n-------------\n\nReturns a plural suffix if the value is not ``1``, ``'1'``, or an object of\nlength 1. By default, this suffix is ``'s'``.\n\nExample::\n\n    You have {{ num_messages }} message{{ num_messages|pluralize }}.\n\nIf ``num_messages`` is ``1``, the output will be ``You have 1 message.``\nIf ``num_messages`` is ``2``  the output will be ``You have 2 messages.``\n\nFor words that require a suffix other than ``'s'``, you can provide an alternate\nsuffix as a parameter to the filter.\n\nExample::\n\n    You have {{ num_walruses }} walrus{{ num_walruses|pluralize:\"es\" }}.\n\nFor words that don't pluralize by simple suffix, you can specify both a\nsingular and plural suffix, separated by a comma.\n\nExample::\n\n    You have {{ num_cherries }} cherr{{ num_cherries|pluralize:\"y,ies\" }}.\n\n.. note:: Use :ttag:`blocktranslate` to pluralize translated strings.\n\n.. templatefilter:: pprint\n\n``pprint``\n----------\n\nA wrapper around :func:`pprint.pprint` -- for debugging, really.\n\n.. templatefilter:: random\n\n``random``\n----------\n\nReturns a random item from the given list.\n\nFor example::\n\n    {{ value|random }}\n\nIf ``value`` is the list ``['a', 'b', 'c', 'd']``, the output could be ``\"b\"``.\n\n.. templatefilter:: rjust\n\n``rjust``\n---------\n\nRight-aligns the value in a field of a given width.\n\n**Argument:** field size\n\nFor example::\n\n    \"{{ value|rjust:\"10\" }}\"\n\nIf ``value`` is ``Django``, the output will be ``\"    Django\"``.\n\n.. templatefilter:: safe\n\n``safe``\n--------\n\nMarks a string as not requiring further HTML escaping prior to output. When\nautoescaping is off, this filter has no effect.\n\n.. note::\n\n    If you are chaining filters, a filter applied after ``safe`` can\n    make the contents unsafe again. For example, the following code\n    prints the variable as is, unescaped::\n\n        {{ var|safe|escape }}\n\n.. templatefilter:: safeseq\n\n``safeseq``\n-----------\n\nApplies the :tfilter:`safe` filter to each element of a sequence. Useful in\nconjunction with other filters that operate on sequences, such as\n:tfilter:`join`. For example::\n\n    {{ some_list|safeseq|join:\", \" }}\n\nYou couldn't use the :tfilter:`safe` filter directly in this case, as it would\nfirst convert the variable into a string, rather than working with the\nindividual elements of the sequence.\n\n.. templatefilter:: slice\n\n``slice``\n---------\n\nReturns a slice of the list.\n\nUses the same syntax as Python's list slicing. See\nhttps://www.diveinto.org/python3/native-datatypes.html#slicinglists\nfor an introduction.\n\nExample::\n\n    {{ some_list|slice:\":2\" }}\n\nIf ``some_list`` is ``['a', 'b', 'c']``, the output will be ``['a', 'b']``.\n\n.. templatefilter:: slugify\n\n``slugify``\n-----------\n\nConverts to ASCII. Converts spaces to hyphens. Removes characters that aren't\nalphanumerics, underscores, or hyphens. Converts to lowercase. Also strips\nleading and trailing whitespace.\n\nFor example::\n\n    {{ value|slugify }}\n\nIf ``value`` is ``\"Joel is a slug\"``, the output will be ``\"joel-is-a-slug\"``.\n\n.. templatefilter:: stringformat\n\n``stringformat``\n----------------\n\nFormats the variable according to the argument, a string formatting specifier.\nThis specifier uses the :ref:`old-string-formatting` syntax, with the exception\nthat the leading \"%\" is dropped.\n\nFor example::\n\n    {{ value|stringformat:\"E\" }}\n\nIf ``value`` is ``10``, the output will be ``1.000000E+01``.\n\n.. templatefilter:: striptags\n\n``striptags``\n-------------\n\nMakes all possible efforts to strip all [X]HTML tags.\n\nFor example::\n\n    {{ value|striptags }}\n\nIf ``value`` is ``\"<b>Joel</b> <button>is</button> a <span>slug</span>\"``, the\noutput will be ``\"Joel is a slug\"``.\n\n.. admonition:: No safety guarantee\n\n    Note that ``striptags`` doesn't give any guarantee about its output being\n    HTML safe, particularly with non valid HTML input. So **NEVER** apply the\n    ``safe`` filter to a ``striptags`` output. If you are looking for something\n    more robust, you can use the ``bleach`` Python library, notably its\n    `clean`_ method.\n\n.. _clean: https://bleach.readthedocs.io/en/latest/clean.html\n\n.. templatefilter:: time\n\n``time``\n--------\n\nFormats a time according to the given format.\n\nGiven format can be the predefined one :setting:`TIME_FORMAT`, or a custom\nformat, same as the :tfilter:`date` filter. Note that the predefined format\nis locale-dependent.\n\nFor example::\n\n    {{ value|time:\"H:i\" }}\n\nIf ``value`` is equivalent to ``datetime.datetime.now()``, the output will be\nthe string ``\"01:23\"``.\n\nNote that you can backslash-escape a format string if you want to use the\n\"raw\" value. In this example, both \"h\" and \"m\" are backslash-escaped, because\notherwise each is a format string that displays the hour and the month,\nrespectively::\n\n    {% value|time:\"H\\h i\\m\" %}\n\nThis would display as \"01h 23m\".\n\nAnother example:\n\nAssuming that :setting:`USE_L10N` is ``True`` and :setting:`LANGUAGE_CODE` is,\nfor example, ``\"de\"``, then for::\n\n    {{ value|time:\"TIME_FORMAT\" }}\n\nthe output will be the string ``\"01:23\"`` (The ``\"TIME_FORMAT\"`` format\nspecifier for the ``de`` locale as shipped with Django is ``\"H:i\"``).\n\nThe ``time`` filter will only accept parameters in the format string that\nrelate to the time of day, not the date. If you need to format a ``date``\nvalue, use the :tfilter:`date` filter instead (or along with :tfilter:`time` if\nyou need to render a full :py:class:`~datetime.datetime` value).\n\nThere is one exception the above rule: When passed a ``datetime`` value with\nattached timezone information (a :ref:`time-zone-aware\n<naive_vs_aware_datetimes>` ``datetime`` instance) the ``time`` filter will\naccept the timezone-related :ref:`format specifiers\n<date-and-time-formatting-specifiers>` ``'e'``, ``'O'`` , ``'T'`` and ``'Z'``.\n\nWhen used without a format string, the ``TIME_FORMAT`` format specifier is\nused::\n\n    {{ value|time }}\n\nis the same as::\n\n    {{ value|time:\"TIME_FORMAT\" }}\n\n.. templatefilter:: timesince\n\n``timesince``\n-------------\n\nFormats a date as the time since that date (e.g., \"4 days, 6 hours\").\n\nTakes an optional argument that is a variable containing the date to use as\nthe comparison point (without the argument, the comparison point is *now*).\nFor example, if ``blog_date`` is a date instance representing midnight on 1\nJune 2006, and ``comment_date`` is a date instance for 08:00 on 1 June 2006,\nthen the following would return \"8 hours\"::\n\n    {{ blog_date|timesince:comment_date }}\n\nComparing offset-naive and offset-aware datetimes will return an empty string.\n\nMinutes is the smallest unit used, and \"0 minutes\" will be returned for any\ndate that is in the future relative to the comparison point.\n\n.. templatefilter:: timeuntil\n\n``timeuntil``\n-------------\n\nSimilar to ``timesince``, except that it measures the time from now until the\ngiven date or datetime. For example, if today is 1 June 2006 and\n``conference_date`` is a date instance holding 29 June 2006, then\n``{{ conference_date|timeuntil }}`` will return \"4 weeks\".\n\nTakes an optional argument that is a variable containing the date to use as\nthe comparison point (instead of *now*). If ``from_date`` contains 22 June\n2006, then the following will return \"1 week\"::\n\n    {{ conference_date|timeuntil:from_date }}\n\nComparing offset-naive and offset-aware datetimes will return an empty string.\n\nMinutes is the smallest unit used, and \"0 minutes\" will be returned for any\ndate that is in the past relative to the comparison point.\n\n.. templatefilter:: title\n\n``title``\n---------\n\nConverts a string into titlecase by making words start with an uppercase\ncharacter and the remaining characters lowercase. This tag makes no effort to\nkeep \"trivial words\" in lowercase.\n\nFor example::\n\n    {{ value|title }}\n\nIf ``value`` is ``\"my FIRST post\"``, the output will be ``\"My First Post\"``.\n\n.. templatefilter:: truncatechars\n\n``truncatechars``\n-----------------\n\nTruncates a string if it is longer than the specified number of characters.\nTruncated strings will end with a translatable ellipsis character (\"…\").\n\n**Argument:** Number of characters to truncate to\n\nFor example::\n\n    {{ value|truncatechars:7 }}\n\nIf ``value`` is ``\"Joel is a slug\"``, the output will be ``\"Joel i…\"``.\n\n.. templatefilter:: truncatechars_html\n\n``truncatechars_html``\n----------------------\n\nSimilar to :tfilter:`truncatechars`, except that it is aware of HTML tags. Any\ntags that are opened in the string and not closed before the truncation point\nare closed immediately after the truncation.\n\nFor example::\n\n    {{ value|truncatechars_html:7 }}\n\nIf ``value`` is ``\"<p>Joel is a slug</p>\"``, the output will be\n``\"<p>Joel i…</p>\"``.\n\nNewlines in the HTML content will be preserved.\n\n.. templatefilter:: truncatewords\n\n``truncatewords``\n-----------------\n\nTruncates a string after a certain number of words.\n\n**Argument:** Number of words to truncate after\n\nFor example::\n\n    {{ value|truncatewords:2 }}\n\nIf ``value`` is ``\"Joel is a slug\"``, the output will be ``\"Joel is …\"``.\n\nNewlines within the string will be removed.\n\n.. templatefilter:: truncatewords_html\n\n``truncatewords_html``\n----------------------\n\nSimilar to :tfilter:`truncatewords`, except that it is aware of HTML tags. Any\ntags that are opened in the string and not closed before the truncation point,\nare closed immediately after the truncation.\n\nThis is less efficient than :tfilter:`truncatewords`, so should only be used\nwhen it is being passed HTML text.\n\nFor example::\n\n    {{ value|truncatewords_html:2 }}\n\nIf ``value`` is ``\"<p>Joel is a slug</p>\"``, the output will be\n``\"<p>Joel is …</p>\"``.\n\nNewlines in the HTML content will be preserved.\n\n.. templatefilter:: unordered_list\n\n``unordered_list``\n------------------\n\nRecursively takes a self-nested list and returns an HTML unordered list --\nWITHOUT opening and closing <ul> tags.\n\nThe list is assumed to be in the proper format. For example, if ``var``\ncontains ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then\n``{{ var|unordered_list }}`` would return::\n\n    <li>States\n    <ul>\n            <li>Kansas\n            <ul>\n                    <li>Lawrence</li>\n                    <li>Topeka</li>\n            </ul>\n            </li>\n            <li>Illinois</li>\n    </ul>\n    </li>\n\n.. templatefilter:: upper\n\n``upper``\n---------\n\nConverts a string into all uppercase.\n\nFor example::\n\n    {{ value|upper }}\n\nIf ``value`` is ``\"Joel is a slug\"``, the output will be ``\"JOEL IS A SLUG\"``.\n\n.. templatefilter:: urlencode\n\n``urlencode``\n-------------\n\nEscapes a value for use in a URL.\n\nFor example::\n\n    {{ value|urlencode }}\n\nIf ``value`` is ``\"https://www.example.org/foo?a=b&c=d\"``, the output will be\n``\"https%3A//www.example.org/foo%3Fa%3Db%26c%3Dd\"``.\n\nAn optional argument containing the characters which should not be escaped can\nbe provided.\n\nIf not provided, the '/' character is assumed safe. An empty string can be\nprovided when *all* characters should be escaped. For example::\n\n    {{ value|urlencode:\"\" }}\n\nIf ``value`` is ``\"https://www.example.org/\"``, the output will be\n``\"https%3A%2F%2Fwww.example.org%2F\"``.\n\n.. templatefilter:: urlize\n\n``urlize``\n----------\n\nConverts URLs and email addresses in text into clickable links.\n\nThis template tag works on links prefixed with ``http://``, ``https://``, or\n``www.``. For example, ``https://goo.gl/aia1t`` will get converted but\n``goo.gl/aia1t`` won't.\n\nIt also supports domain-only links ending in one of the original top level\ndomains (``.com``, ``.edu``, ``.gov``, ``.int``, ``.mil``, ``.net``, and\n``.org``). For example, ``djangoproject.com`` gets converted.\n\nLinks can have trailing punctuation (periods, commas, close-parens) and leading\npunctuation (opening parens), and ``urlize`` will still do the right thing.\n\nLinks generated by ``urlize`` have a ``rel=\"nofollow\"`` attribute added\nto them.\n\nFor example::\n\n    {{ value|urlize }}\n\nIf ``value`` is ``\"Check out www.djangoproject.com\"``, the output will be\n``\"Check out <a href=\"http://www.djangoproject.com\"\nrel=\"nofollow\">www.djangoproject.com</a>\"``.\n\nIn addition to web links, ``urlize`` also converts email addresses into\n``mailto:`` links. If ``value`` is\n``\"Send questions to foo@example.com\"``, the output will be\n``\"Send questions to <a href=\"mailto:foo@example.com\">foo@example.com</a>\"``.\n\nThe ``urlize`` filter also takes an optional parameter ``autoescape``. If\n``autoescape`` is ``True``, the link text and URLs will be escaped using\nDjango's built-in :tfilter:`escape` filter. The default value for\n``autoescape`` is ``True``.\n\n.. note::\n\n    If ``urlize`` is applied to text that already contains HTML markup, or to\n    email addresses that contain single quotes (``'``), things won't work as\n    expected. Apply this filter only to plain text.\n\n.. templatefilter:: urlizetrunc\n\n``urlizetrunc``\n---------------\n\nConverts URLs and email addresses into clickable links just like urlize_, but\ntruncates URLs longer than the given character limit.\n\n**Argument:** Number of characters that link text should be truncated to,\nincluding the ellipsis that's added if truncation is necessary.\n\nFor example::\n\n    {{ value|urlizetrunc:15 }}\n\nIf ``value`` is ``\"Check out www.djangoproject.com\"``, the output would be\n``'Check out <a href=\"http://www.djangoproject.com\"\nrel=\"nofollow\">www.djangoproj…</a>'``.\n\nAs with urlize_, this filter should only be applied to plain text.\n\n.. templatefilter:: wordcount\n\n``wordcount``\n-------------\n\nReturns the number of words.\n\nFor example::\n\n    {{ value|wordcount }}\n\nIf ``value`` is ``\"Joel is a slug\"``, the output will be ``4``.\n\n.. templatefilter:: wordwrap\n\n``wordwrap``\n------------\n\nWraps words at specified line length.\n\n**Argument:** number of characters at which to wrap the text\n\nFor example::\n\n    {{ value|wordwrap:5 }}\n\nIf ``value`` is ``Joel is a slug``, the output would be::\n\n    Joel\n    is a\n    slug\n\n.. templatefilter:: yesno\n\n``yesno``\n---------\n\nMaps values for ``True``, ``False``, and (optionally) ``None``, to the strings\n\"yes\", \"no\", \"maybe\", or a custom mapping passed as a comma-separated list, and\nreturns one of those strings according to the value:\n\nFor example::\n\n    {{ value|yesno:\"yeah,no,maybe\" }}\n\n==========  ======================  ===========================================\nValue       Argument                Outputs\n==========  ======================  ===========================================\n``True``                            ``yes``\n``True``    ``\"yeah,no,maybe\"``     ``yeah``\n``False``   ``\"yeah,no,maybe\"``     ``no``\n``None``    ``\"yeah,no,maybe\"``     ``maybe``\n``None``    ``\"yeah,no\"``           ``no`` (converts ``None`` to ``False``\n                                    if no mapping for ``None`` is given)\n==========  ======================  ===========================================\n\nInternationalization tags and filters\n=====================================\n\nDjango provides template tags and filters to control each aspect of\n:doc:`internationalization </topics/i18n/index>` in templates. They allow for\ngranular control of translations, formatting, and time zone conversions.\n\n``i18n``\n--------\n\nThis library allows specifying translatable text in templates.\nTo enable it, set :setting:`USE_I18N` to ``True``, then load it with\n``{% load i18n %}``.\n\nSee :ref:`specifying-translation-strings-in-template-code`.\n\n``l10n``\n--------\n\nThis library provides control over the localization of values in templates.\nYou only need to load the library using ``{% load l10n %}``, but you'll often\nset :setting:`USE_L10N` to ``True`` so that localization is active by default.\n\nSee :ref:`topic-l10n-templates`.\n\n``tz``\n------\n\nThis library provides control over time zone conversions in templates.\nLike ``l10n``, you only need to load the library using ``{% load tz %}``,\nbut you'll usually also set :setting:`USE_TZ` to ``True`` so that conversion\nto local time happens by default.\n\nSee :ref:`time-zones-in-templates`.\n\nOther tags and filters libraries\n================================\n\nDjango comes with a couple of other template-tag libraries that you have to\nenable explicitly in your :setting:`INSTALLED_APPS` setting and enable in your\ntemplate with the :ttag:`{% load %}<load>` tag.\n\n``django.contrib.humanize``\n---------------------------\n\nA set of Django template filters useful for adding a \"human touch\" to data. See\n:doc:`/ref/contrib/humanize`.\n\n``static``\n----------\n\n.. templatetag:: static\n\n``static``\n~~~~~~~~~~\n\nTo link to static files that are saved in :setting:`STATIC_ROOT` Django ships\nwith a :ttag:`static` template tag. If the :mod:`django.contrib.staticfiles`\napp is installed, the tag will serve files using ``url()`` method of the\nstorage specified by :setting:`STATICFILES_STORAGE`. For example::\n\n    {% load static %}\n    <img src=\"{% static \"images/hi.jpg\" %}\" alt=\"Hi!\">\n\nIt is also able to consume standard context variables, e.g. assuming a\n``user_stylesheet`` variable is passed to the template::\n\n    {% load static %}\n    <link rel=\"stylesheet\" href=\"{% static user_stylesheet %}\" type=\"text/css\" media=\"screen\">\n\nIf you'd like to retrieve a static URL without displaying it, you can use a\nslightly different call::\n\n    {% load static %}\n    {% static \"images/hi.jpg\" as myphoto %}\n    <img src=\"{{ myphoto }}\">\n\n.. admonition:: Using Jinja2 templates?\n\n    See :class:`~django.template.backends.jinja2.Jinja2` for information on\n    using the ``static`` tag with Jinja2.\n\n.. templatetag:: get_static_prefix\n\n``get_static_prefix``\n~~~~~~~~~~~~~~~~~~~~~\n\nYou should prefer the :ttag:`static` template tag, but if you need more control\nover exactly where and how :setting:`STATIC_URL` is injected into the template,\nyou can use the :ttag:`get_static_prefix` template tag::\n\n    {% load static %}\n    <img src=\"{% get_static_prefix %}images/hi.jpg\" alt=\"Hi!\">\n\nThere's also a second form you can use to avoid extra processing if you need\nthe value multiple times::\n\n    {% load static %}\n    {% get_static_prefix as STATIC_PREFIX %}\n\n    <img src=\"{{ STATIC_PREFIX }}images/hi.jpg\" alt=\"Hi!\">\n    <img src=\"{{ STATIC_PREFIX }}images/hi2.jpg\" alt=\"Hello!\">\n\n.. templatetag:: get_media_prefix\n\n``get_media_prefix``\n~~~~~~~~~~~~~~~~~~~~\n\nSimilar to the :ttag:`get_static_prefix`, ``get_media_prefix`` populates a\ntemplate variable with the media prefix :setting:`MEDIA_URL`, e.g.::\n\n    {% load static %}\n    <body data-media-url=\"{% get_media_prefix %}\">\n\nBy storing the value in a data attribute, we ensure it's escaped appropriately\nif we want to use it in a JavaScript context.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":184,"nodeType":"Package","repoName":null,"name":"docs/howto/deployment/asgi","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":185,"nodeType":"TextFile","repoName":null,"name":"uvicorn.txt","path":"docs/howto/deployment/asgi","text":"==============================\nHow to use Django with Uvicorn\n==============================\n\n.. highlight:: bash\n\nUvicorn_ is an ASGI server based on ``uvloop`` and ``httptools``, with an\nemphasis on speed.\n\nInstalling Uvicorn\n==================\n\nYou can install Uvicorn with ``pip``::\n\n    python -m pip install uvicorn\n\nRunning Django in Uvicorn\n=========================\n\nWhen Uvicorn is installed, a ``uvicorn`` command is available which runs ASGI\napplications. Uvicorn needs to be called with the location of a module\ncontaining an ASGI application object, followed by what the application is\ncalled (separated by a colon).\n\nFor a typical Django project, invoking Uvicorn would look like::\n\n    uvicorn myproject.asgi:application\n\nThis will start one process listening on ``127.0.0.1:8000``. It requires that\nyour project be on the Python path; to ensure that run this command from the\nsame directory as your ``manage.py`` file.\n\nFor more advanced usage, please read the `Uvicorn documentation <Uvicorn_>`_.\n\n.. _Uvicorn: https://www.uvicorn.org/\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":186,"nodeType":"TextFile","repoName":null,"name":"initial-data.txt","path":"docs/howto","text":"=================================\nProviding initial data for models\n=================================\n\nIt's sometimes useful to pre-populate your database with hard-coded data when\nyou're first setting up an app. You can provide initial data with migrations or\nfixtures.\n\nProviding initial data with migrations\n======================================\n\nIf you want to automatically load initial data for an app, create a\n:ref:`data migration <data-migrations>`. Migrations are run when setting up the\ntest database, so the data will be available there, subject to :ref:`some\nlimitations <test-case-serialized-rollback>`.\n\n.. _initial-data-via-fixtures:\n\nProviding data with fixtures\n============================\n\nYou can also provide data using fixtures, however, this data isn't loaded\nautomatically, except if you use :attr:`.TransactionTestCase.fixtures`.\n\nA fixture is a collection of data that Django knows how to import into a\ndatabase. The most straightforward way of creating a fixture if you've already\ngot some data is to use the :djadmin:`manage.py dumpdata <dumpdata>` command.\nOr, you can write fixtures by hand; fixtures can be written as JSON, XML or YAML\n(with PyYAML_ installed) documents. The :doc:`serialization documentation\n</topics/serialization>` has more details about each of these supported\n:ref:`serialization formats <serialization-formats>`.\n\n.. _PyYAML: https://pyyaml.org/\n\nAs an example, though, here's what a fixture for a ``Person`` model might look\nlike in JSON:\n\n.. code-block:: js\n\n    [\n      {\n        \"model\": \"myapp.person\",\n        \"pk\": 1,\n        \"fields\": {\n          \"first_name\": \"John\",\n          \"last_name\": \"Lennon\"\n        }\n      },\n      {\n        \"model\": \"myapp.person\",\n        \"pk\": 2,\n        \"fields\": {\n          \"first_name\": \"Paul\",\n          \"last_name\": \"McCartney\"\n        }\n      }\n    ]\n\nAnd here's that same fixture as YAML:\n\n.. code-block:: yaml\n\n    - model: myapp.person\n      pk: 1\n      fields:\n        first_name: John\n        last_name: Lennon\n    - model: myapp.person\n      pk: 2\n      fields:\n        first_name: Paul\n        last_name: McCartney\n\nYou'll store this data in a ``fixtures`` directory inside your app.\n\nYou can load data by calling :djadmin:`manage.py loaddata <loaddata>`\n``<fixturename>``, where ``<fixturename>`` is the name of the fixture file\nyou've created. Each time you run :djadmin:`loaddata`, the data will be read\nfrom the fixture and re-loaded into the database. Note this means that if you\nchange one of the rows created by a fixture and then run :djadmin:`loaddata`\nagain, you'll wipe out any changes you've made.\n\nWhere Django finds fixture files\n--------------------------------\n\nBy default, Django looks in the ``fixtures`` directory inside each app for\nfixtures. You can set the :setting:`FIXTURE_DIRS` setting to a list of\nadditional directories where Django should look.\n\nWhen running :djadmin:`manage.py loaddata <loaddata>`, you can also\nspecify a path to a fixture file, which overrides searching the usual\ndirectories.\n\n.. seealso::\n\n    Fixtures are also used by the :ref:`testing framework\n    <topics-testing-fixtures>` to help set up a consistent test environment.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":187,"nodeType":"Package","repoName":null,"name":"docs/howto/deployment","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":188,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/howto/deployment","text":"================\nDeploying Django\n================\n\nDjango is full of shortcuts to make Web developers' lives easier, but all\nthose tools are of no use if you can't easily deploy your sites. Since Django's\ninception, ease of deployment has been a major goal.\n\nThere are many options for deploying your Django application, based on your\narchitecture or your particular business needs, but that discussion is outside\nthe scope of what Django can give you as guidance.\n\nDjango, being a web framework, needs a web server in order to operate. And\nsince most web servers don't natively speak Python, we need an interface to\nmake that communication happen.\n\nDjango currently supports two interfaces: WSGI and ASGI.\n\n* `WSGI`_ is the main Python standard for communicating between Web servers and\n  applications, but it only supports synchronous code.\n\n* `ASGI`_ is the new, asynchronous-friendly standard that will allow your\n  Django site to use asynchronous Python features, and asynchronous Django\n  features as they are developed.\n\nYou should also consider how you will handle :doc:`static files\n</howto/static-files/deployment>` for your application, and how to handle\n:doc:`error reporting</howto/error-reporting>`.\n\nFinally, before you deploy your application to production, you should run\nthrough our :doc:`deployment checklist<checklist>` to ensure that your\nconfigurations are suitable.\n\n.. _WSGI: https://wsgi.readthedocs.io/en/latest/\n.. _ASGI: https://asgi.readthedocs.io/en/latest/\n\n.. toctree::\n   :maxdepth: 2\n\n   wsgi/index\n   asgi/index\n   checklist\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":189,"nodeType":"TextFile","repoName":null,"name":"windows.txt","path":"docs/howto","text":"================================\nHow to install Django on Windows\n================================\n\n.. highlight:: doscon\n\nThis document will guide you through installing Python 3.7 and Django on\nWindows. It also provides instructions for installing `virtualenv`_ and\n`virtualenvwrapper`_, which make it easier to work on Python projects. This is\nmeant as a beginner's guide for users working on Django projects and does not\nreflect how Django should be installed when developing patches for Django\nitself.\n\nThe steps in this guide have been tested with Windows 7, 8, and 10. In other\nversions, the steps would be similar. You will need to be familiar with using\nthe Windows command prompt.\n\nInstall Python\n==============\n\nDjango is a Python web framework, thus requiring Python to be installed on your\nmachine. At the time of writing, Python 3.7 is the latest version.\n\nTo install Python on your machine go to https://python.org/downloads/. The\nwebsite should offer you a download button for the latest Python version.\nDownload the executable installer and run it. Check the boxes next to ``Install\nlauncher for all users (recommended)`` and ``Add Python 3.7 to PATH`` then\nclick ``Install Now``.\n\nAfter installation, open the command prompt and check that the Python version\nmatches the version you installed by executing::\n\n    ...\\> py --version\n\n.. seealso::\n\n    For more details, see :doc:`python:using/windows` documentation.\n\nAbout ``pip``\n=============\n\n`pip`_ is a package manage for Python. It makes installing and uninstalling\nPython packages (such as Django!) very easy. For the rest of the installation,\nwe'll use ``pip`` to install Python packages from the command line.\n\nTo install pip on your machine, go to\nhttps://pip.pypa.io/en/latest/installing/, and follow the ``Installing with\nget-pip.py`` instructions.\n\n.. _pip: https://pypi.org/project/pip/\n\n.. _virtualenvwrapper-win:\n\nInstall ``virtualenv`` and ``virtualenvwrapper``\n================================================\n\n`virtualenv`_ and `virtualenvwrapper`_ provide a dedicated environment for\neach Django project you create. While not mandatory, this is considered a best\npractice and will save you time in the future when you're ready to deploy your\nproject. To do this, run::\n\n    ...\\> py -m pip install virtualenvwrapper-win\n\nThen create a virtual environment for your project::\n\n    ...\\> mkvirtualenv myproject\n\nThe virtual environment will be activated automatically and you'll see\n\"(myproject)\" next to the command prompt to designate that. If you start a new\ncommand prompt, you'll need to activate the environment again using::\n\n    ...\\> workon myproject\n\n.. _virtualenv: https://pypi.org/project/virtualenv/\n.. _virtualenvwrapper: https://pypi.org/project/virtualenvwrapper-win/\n\nInstall Django\n==============\n\nDjango can be installed easily using ``pip`` within your virtual environment.\n\nIn the command prompt, ensure your virtual environment is active, and execute\nthe following command::\n\n    ...\\> py -m pip install Django\n\nThis will download and install the latest Django release.\n\nAfter the installation has completed, you can verify your Django installation\nby executing ``django-admin --version`` in the command prompt.\n\nSee :ref:`database-installation` for information on database installation\nwith Django.\n\nCommon pitfalls\n===============\n\n* If ``django-admin`` only displays the help text no matter what arguments\n  it is given, there is probably a problem with the file association in\n  Windows. Check if there is more than one environment variable set for\n  running Python scripts in ``PATH``. This usually occurs when there is more\n  than one Python version installed.\n\n* If you are connecting to the internet behind a proxy, there might be problems\n  in running the command ``py -m pip install Django``. Set the environment\n  variables for proxy configuration in the command prompt as follows::\n\n    ...\\> set http_proxy=http://username:password@proxyserver:proxyport\n    ...\\> set https_proxy=https://username:password@proxyserver:proxyport\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":190,"nodeType":"TextFile","repoName":null,"name":"outputting-pdf.txt","path":"docs/howto","text":"===========================\nOutputting PDFs with Django\n===========================\n\nThis document explains how to output PDF files dynamically using Django views.\nThis is made possible by the excellent, open-source ReportLab_ Python PDF\nlibrary.\n\nThe advantage of generating PDF files dynamically is that you can create\ncustomized PDFs for different purposes -- say, for different users or different\npieces of content.\n\nFor example, Django was used at kusports.com_ to generate customized,\nprinter-friendly NCAA tournament brackets, as PDF files, for people\nparticipating in a March Madness contest.\n\n.. _ReportLab: https://www.reportlab.com/opensource/\n.. _kusports.com: http://www.kusports.com/\n\nInstall ReportLab\n=================\n\nThe ReportLab library is `available on PyPI`_. A `user guide`_ (not\ncoincidentally, a PDF file) is also available for download.\nYou can install ReportLab with ``pip``:\n\n.. console::\n\n    $ python -m pip install reportlab\n\nTest your installation by importing it in the Python interactive interpreter::\n\n    >>> import reportlab\n\nIf that command doesn't raise any errors, the installation worked.\n\n.. _available on PyPI: https://pypi.org/project/reportlab/\n.. _user guide: https://www.reportlab.com/docs/reportlab-userguide.pdf\n\nWrite your view\n===============\n\nThe key to generating PDFs dynamically with Django is that the ReportLab API\nacts on file-like objects, and Django's :class:`~django.http.FileResponse`\nobjects accept file-like objects.\n\nHere's a \"Hello World\" example::\n\n    import io\n    from django.http import FileResponse\n    from reportlab.pdfgen import canvas\n\n    def some_view(request):\n        # Create a file-like buffer to receive PDF data.\n        buffer = io.BytesIO()\n\n        # Create the PDF object, using the buffer as its \"file.\"\n        p = canvas.Canvas(buffer)\n\n        # Draw things on the PDF. Here's where the PDF generation happens.\n        # See the ReportLab documentation for the full list of functionality.\n        p.drawString(100, 100, \"Hello world.\")\n\n        # Close the PDF object cleanly, and we're done.\n        p.showPage()\n        p.save()\n\n        # FileResponse sets the Content-Disposition header so that browsers\n        # present the option to save the file.\n        buffer.seek(0)\n        return FileResponse(buffer, as_attachment=True, filename='hello.pdf')\n\nThe code and comments should be self-explanatory, but a few things deserve a\nmention:\n\n* The response will automatically set the MIME type :mimetype:`application/pdf`\n  based on the filename extension. This tells browsers that the document is a\n  PDF file, rather than an HTML file or a generic\n  :mimetype:`application/octet-stream` binary content.\n\n* When ``as_attachment=True`` is passed to ``FileResponse``, it sets the\n  appropriate ``Content-Disposition`` header and that tells Web browsers to\n  pop-up a dialog box prompting/confirming how to handle the document even if a\n  default is set on the machine. If the ``as_attachment`` parameter is omitted,\n  browsers will handle the PDF using whatever program/plugin they've been\n  configured to use for PDFs.\n\n* You can provide an arbitrary ``filename`` parameter. It'll be used by browsers\n  in the \"Save as...\" dialog.\n\n* You can hook into the ReportLab API: The same buffer passed as the first\n  argument to ``canvas.Canvas`` can be fed to the\n  :class:`~django.http.FileResponse` class.\n\n* Note that all subsequent PDF-generation methods are called on the PDF\n  object (in this case, ``p``) -- not on ``buffer``.\n\n* Finally, it's important to call ``showPage()`` and ``save()`` on the PDF\n  file.\n\n.. note::\n\n    ReportLab is not thread-safe. Some of our users have reported odd issues\n    with building PDF-generating Django views that are accessed by many people\n    at the same time.\n\nOther formats\n=============\n\nNotice that there isn't a lot in these examples that's PDF-specific -- just the\nbits using ``reportlab``. You can use a similar technique to generate any\narbitrary format that you can find a Python library for. Also see\n:doc:`/howto/outputting-csv` for another example and some techniques you can use\nwhen generated text-based formats.\n\n.. seealso::\n\n    Django Packages provides a `comparison of packages\n    <https://djangopackages.org/grids/g/pdf/>`_ that help generate PDF files\n    from Django.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":191,"nodeType":"TextFile","repoName":null,"name":"upgrade-version.txt","path":"docs/howto","text":"===================================\nUpgrading Django to a newer version\n===================================\n\nWhile it can be a complex process at times, upgrading to the latest Django\nversion has several benefits:\n\n* New features and improvements are added.\n* Bugs are fixed.\n* Older version of Django will eventually no longer receive security updates.\n  (see :ref:`supported-versions-policy`).\n* Upgrading as each new Django release is available makes future upgrades less\n  painful by keeping your code base up to date.\n\nHere are some things to consider to help make your upgrade process as smooth as\npossible.\n\nRequired Reading\n================\n\nIf it's your first time doing an upgrade, it is useful to read the :doc:`guide\non the different release processes </internals/release-process>`.\n\nAfterwards, you should familiarize yourself with the changes that were made in\nthe new Django version(s):\n\n* Read the :doc:`release notes </releases/index>` for each 'final' release from\n  the one after your current Django version, up to and including the version to\n  which you plan to upgrade.\n* Look at the :doc:`deprecation timeline</internals/deprecation>` for the\n  relevant versions.\n\nPay particular attention to backwards incompatible changes to get a clear idea\nof what will be needed for a successful upgrade.\n\nIf you're upgrading through more than one feature version (e.g. 2.0 to 2.2),\nit's usually easier to upgrade through each feature release incrementally\n(2.0 to 2.1 to 2.2) rather than to make all the changes for each feature\nrelease at once. For each feature release, use the latest patch release (e.g.\nfor 2.1, use 2.1.15).\n\nThe same incremental upgrade approach is recommended when upgrading from one\nLTS to the next.\n\nDependencies\n============\n\nIn most cases it will be necessary to upgrade to the latest version of your\nDjango-related dependencies as well. If the Django version was recently\nreleased or if some of your dependencies are not well-maintained, some of your\ndependencies may not yet support the new Django version. In these cases you may\nhave to wait until new versions of your dependencies are released.\n\nResolving deprecation warnings\n==============================\n\nBefore upgrading, it's a good idea to resolve any deprecation warnings raised\nby your project while using your current version of Django. Fixing these\nwarnings before upgrading ensures that you're informed about areas of the code\nthat need altering.\n\nIn Python, deprecation warnings are silenced by default. You must turn them on\nusing the ``-Wa`` Python command line option or the :envvar:`PYTHONWARNINGS`\nenvironment variable. For example, to show warnings while running tests:\n\n.. console::\n\n    $ python -Wa manage.py test\n\nIf you're not using the Django test runner, you may need to also ensure that\nany console output is not captured which would hide deprecation warnings. For\nexample, if you use `pytest <https://pytest.org/>`__:\n\n.. code-block:: console\n\n    $ PYTHONWARNINGS=always pytest tests --capture=no\n\nResolve any deprecation warnings with your current version of Django before\ncontinuing the upgrade process.\n\nThird party applications might use deprecated APIs in order to support multiple\nversions of Django, so deprecation warnings in packages you've installed don't\nnecessarily indicate a problem. If a package doesn't support the latest version\nof Django, consider raising an issue or sending a pull request for it.\n\nInstallation\n============\n\nOnce you're ready, it is time to :doc:`install the new Django version\n</topics/install>`. If you are using virtualenv_ and it is a major upgrade, you\nmight want to set up a new environment with all the dependencies first.\n\nIf you installed Django with pip_, you can use the ``--upgrade`` or ``-U`` flag:\n\n.. console::\n\n   $ python -m pip install -U Django\n\n.. _pip: https://pip.pypa.io/\n.. _virtualenv: https://virtualenv.pypa.io/\n\nTesting\n=======\n\nWhen the new environment is set up, :doc:`run the full test suite\n</topics/testing/overview>` for your application. Again, it's useful to turn\non deprecation warnings on so they're shown in the test output (you can also\nuse the flag if you test your app manually using ``manage.py runserver``):\n\n.. console::\n\n    $ python -Wa manage.py test\n\nAfter you have run the tests, fix any failures. While you have the release\nnotes fresh in your mind, it may also be a good time to take advantage of new\nfeatures in Django by refactoring your code to eliminate any deprecation\nwarnings.\n\nDeployment\n==========\n\nWhen you are sufficiently confident your app works with the new version of\nDjango, you're ready to go ahead and :doc:`deploy </howto/deployment/index>`\nyour upgraded Django project.\n\nIf you are using caching provided by Django, you should consider clearing your\ncache after upgrading. Otherwise you may run into problems, for example, if you\nare caching pickled objects as these objects are not guaranteed to be\npickle-compatible across Django versions. A past instance of incompatibility\nwas caching pickled :class:`~django.http.HttpResponse` objects, either\ndirectly or indirectly via the :func:`~django.views.decorators.cache.cache_page`\ndecorator.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":192,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/howto","text":"===============\n\"How-to\" guides\n===============\n\nHere you'll find short answers to \"How do I....?\" types of questions. These\nhow-to guides don't cover topics in depth -- you'll find that material in the\n:doc:`/topics/index` and the :doc:`/ref/index`. However, these guides will help\nyou quickly accomplish common tasks.\n\n.. toctree::\n   :maxdepth: 1\n\n   auth-remote-user\n   custom-management-commands\n   custom-model-fields\n   custom-lookups\n   custom-template-backend\n   custom-template-tags\n   custom-file-storage\n   deployment/index\n   upgrade-version\n   error-reporting\n   initial-data\n   legacy-databases\n   outputting-csv\n   outputting-pdf\n   overriding-templates\n   static-files/index\n   static-files/deployment\n   windows\n   writing-migrations\n\n.. seealso::\n\n    The `Django community aggregator`_, where we aggregate content from the\n    global Django community. Many writers in the aggregator write this sort of\n    how-to material.\n\n    .. _django community aggregator: https://www.djangoproject.com/community/\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":193,"nodeType":"TextFile","repoName":null,"name":"custom-file-storage.txt","path":"docs/howto","text":"===============================\nWriting a custom storage system\n===============================\n\n.. currentmodule:: django.core.files.storage\n\nIf you need to provide custom file storage -- a common example is storing files\non some remote system -- you can do so by defining a custom storage class.\nYou'll need to follow these steps:\n\n#. Your custom storage system must be a subclass of\n   ``django.core.files.storage.Storage``::\n\n        from django.core.files.storage import Storage\n\n        class MyStorage(Storage):\n            ...\n\n#. Django must be able to instantiate your storage system without any arguments.\n   This means that any settings should be taken from ``django.conf.settings``::\n\n        from django.conf import settings\n        from django.core.files.storage import Storage\n\n        class MyStorage(Storage):\n            def __init__(self, option=None):\n                if not option:\n                    option = settings.CUSTOM_STORAGE_OPTIONS\n                ...\n\n#. Your storage class must implement the :meth:`_open()` and :meth:`_save()`\n   methods, along with any other methods appropriate to your storage class. See\n   below for more on these methods.\n\n   In addition, if your class provides local file storage, it must override\n   the ``path()`` method.\n\n#. Your storage class must be :ref:`deconstructible <custom-deconstruct-method>`\n   so it can be serialized when it's used on a field in a migration. As long\n   as your field has arguments that are themselves\n   :ref:`serializable <migration-serializing>`, you can use the\n   ``django.utils.deconstruct.deconstructible`` class decorator for this\n   (that's what Django uses on FileSystemStorage).\n\nBy default, the following methods raise ``NotImplementedError`` and will\ntypically have to be overridden:\n\n* :meth:`Storage.delete`\n* :meth:`Storage.exists`\n* :meth:`Storage.listdir`\n* :meth:`Storage.size`\n* :meth:`Storage.url`\n\nNote however that not all these methods are required and may be deliberately\nomitted. As it happens, it is possible to leave each method unimplemented and\nstill have a working Storage.\n\nBy way of example, if listing the contents of certain storage backends turns\nout to be expensive, you might decide not to implement ``Storage.listdir()``.\n\nAnother example would be a backend that only handles writing to files. In this\ncase, you would not need to implement any of the above methods.\n\nUltimately, which of these methods are implemented is up to you. Leaving some\nmethods unimplemented will result in a partial (possibly broken) interface.\n\nYou'll also usually want to use hooks specifically designed for custom storage\nobjects. These are:\n\n.. method:: _open(name, mode='rb')\n\n**Required**.\n\nCalled by ``Storage.open()``, this is the actual mechanism the storage class\nuses to open the file. This must return a ``File`` object, though in most cases,\nyou'll want to return some subclass here that implements logic specific to the\nbackend storage system.\n\n.. method:: _save(name, content)\n\nCalled by ``Storage.save()``. The ``name`` will already have gone through\n``get_valid_name()`` and ``get_available_name()``, and the ``content`` will be a\n``File`` object itself.\n\nShould return the actual name of name of the file saved (usually the ``name``\npassed in, but if the storage needs to change the file name return the new name\ninstead).\n\n.. method:: get_valid_name(name)\n\nReturns a filename suitable for use with the underlying storage system. The\n``name`` argument passed to this method is either the original filename sent to\nthe server or, if ``upload_to`` is a callable, the filename returned by that\nmethod after any path information is removed. Override this to customize how\nnon-standard characters are converted to safe filenames.\n\nThe code provided on ``Storage`` retains only alpha-numeric characters, periods\nand underscores from the original filename, removing everything else.\n\n.. method:: get_alternative_name(file_root, file_ext)\n\nReturns an alternative filename based on the ``file_root`` and ``file_ext``\nparameters. By default, an underscore plus a random 7 character alphanumeric\nstring is appended to the filename before the extension.\n\n.. method:: get_available_name(name, max_length=None)\n\nReturns a filename that is available in the storage mechanism, possibly taking\nthe provided filename into account. The ``name`` argument passed to this method\nwill have already cleaned to a filename valid for the storage system, according\nto the ``get_valid_name()`` method described above.\n\nThe length of the filename will not exceed ``max_length``, if provided. If a\nfree unique filename cannot be found, a :exc:`SuspiciousFileOperation\n<django.core.exceptions.SuspiciousOperation>` exception is raised.\n\nIf a file with ``name`` already exists, ``get_alternative_name()`` is called to\nobtain an alternative name.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":194,"nodeType":"TextFile","repoName":null,"name":"writing-migrations.txt","path":"docs/howto","text":"===========================\nWriting database migrations\n===========================\n\nThis document explains how to structure and write database migrations for\ndifferent scenarios you might encounter. For introductory material on\nmigrations, see :doc:`the topic guide </topics/migrations>`.\n\n.. _data-migrations-and-multiple-databases:\n\nData migrations and multiple databases\n======================================\n\nWhen using multiple databases, you may need to figure out whether or not to\nrun a migration against a particular database. For example, you may want to\n**only** run a migration on a particular database.\n\nIn order to do that you can check the database connection's alias inside a\n``RunPython`` operation by looking at the ``schema_editor.connection.alias``\nattribute::\n\n    from django.db import migrations\n\n    def forwards(apps, schema_editor):\n        if schema_editor.connection.alias != 'default':\n            return\n        # Your migration code goes here\n\n    class Migration(migrations.Migration):\n\n        dependencies = [\n            # Dependencies to other migrations\n        ]\n\n        operations = [\n            migrations.RunPython(forwards),\n        ]\n\nYou can also provide hints that will be passed to the :meth:`allow_migrate()`\nmethod of database routers as ``**hints``:\n\n.. code-block:: python\n    :caption: myapp/dbrouters.py\n\n    class MyRouter:\n\n        def allow_migrate(self, db, app_label, model_name=None, **hints):\n            if 'target_db' in hints:\n                return db == hints['target_db']\n            return True\n\nThen, to leverage this in your migrations, do the following::\n\n    from django.db import migrations\n\n    def forwards(apps, schema_editor):\n        # Your migration code goes here\n        ...\n\n    class Migration(migrations.Migration):\n\n        dependencies = [\n            # Dependencies to other migrations\n        ]\n\n        operations = [\n            migrations.RunPython(forwards, hints={'target_db': 'default'}),\n        ]\n\nIf your ``RunPython`` or ``RunSQL`` operation only affects one model, it's good\npractice to pass ``model_name`` as a hint to make it as transparent as possible\nto the router. This is especially important for reusable and third-party apps.\n\nMigrations that add unique fields\n=================================\n\nApplying a \"plain\" migration that adds a unique non-nullable field to a table\nwith existing rows will raise an error because the value used to populate\nexisting rows is generated only once, thus breaking the unique constraint.\n\nTherefore, the following steps should be taken. In this example, we'll add a\nnon-nullable :class:`~django.db.models.UUIDField` with a default value. Modify\nthe respective field according to your needs.\n\n* Add the field on your model with ``default=uuid.uuid4`` and ``unique=True``\n  arguments (choose an appropriate default for the type of the field you're\n  adding).\n\n* Run the :djadmin:`makemigrations` command. This should generate a migration\n  with an ``AddField`` operation.\n\n* Generate two empty migration files for the same app by running\n  ``makemigrations myapp --empty`` twice. We've renamed the migration files to\n  give them meaningful names in the examples below.\n\n* Copy the ``AddField`` operation from the auto-generated migration (the first\n  of the three new files) to the last migration, change ``AddField`` to\n  ``AlterField``, and add imports of ``uuid`` and ``models``. For example:\n\n  .. code-block:: python\n    :caption: 0006_remove_uuid_null.py\n\n    # Generated by Django A.B on YYYY-MM-DD HH:MM\n    from django.db import migrations, models\n    import uuid\n\n    class Migration(migrations.Migration):\n\n        dependencies = [\n            ('myapp', '0005_populate_uuid_values'),\n        ]\n\n        operations = [\n            migrations.AlterField(\n                model_name='mymodel',\n                name='uuid',\n                field=models.UUIDField(default=uuid.uuid4, unique=True),\n            ),\n        ]\n\n* Edit the first migration file. The generated migration class should look\n  similar to this:\n\n  .. code-block:: python\n    :caption: 0004_add_uuid_field.py\n\n    class Migration(migrations.Migration):\n\n        dependencies = [\n            ('myapp', '0003_auto_20150129_1705'),\n        ]\n\n        operations = [\n            migrations.AddField(\n                model_name='mymodel',\n                name='uuid',\n                field=models.UUIDField(default=uuid.uuid4, unique=True),\n            ),\n        ]\n\n  Change ``unique=True`` to ``null=True`` -- this will create the intermediary\n  null field and defer creating the unique constraint until we've populated\n  unique values on all the rows.\n\n* In the first empty migration file, add a\n  :class:`~django.db.migrations.operations.RunPython` or\n  :class:`~django.db.migrations.operations.RunSQL` operation to generate a\n  unique value (UUID in the example) for each existing row. Also add an import\n  of ``uuid``. For example:\n\n  .. code-block:: python\n    :caption: 0005_populate_uuid_values.py\n\n    # Generated by Django A.B on YYYY-MM-DD HH:MM\n    from django.db import migrations\n    import uuid\n\n    def gen_uuid(apps, schema_editor):\n        MyModel = apps.get_model('myapp', 'MyModel')\n        for row in MyModel.objects.all():\n            row.uuid = uuid.uuid4()\n            row.save(update_fields=['uuid'])\n\n    class Migration(migrations.Migration):\n\n        dependencies = [\n            ('myapp', '0004_add_uuid_field'),\n        ]\n\n        operations = [\n            # omit reverse_code=... if you don't want the migration to be reversible.\n            migrations.RunPython(gen_uuid, reverse_code=migrations.RunPython.noop),\n        ]\n\n* Now you can apply the migrations as usual with the :djadmin:`migrate` command.\n\n  Note there is a race condition if you allow objects to be created while this\n  migration is running. Objects created after the ``AddField`` and before\n  ``RunPython`` will have their original ``uuid``’s overwritten.\n\n.. _non-atomic-migrations:\n\nNon-atomic migrations\n~~~~~~~~~~~~~~~~~~~~~\n\nOn databases that support DDL transactions (SQLite and PostgreSQL), migrations\nwill run inside a transaction by default. For use cases such as performing data\nmigrations on large tables, you may want to prevent a migration from running in\na transaction by setting the ``atomic`` attribute to ``False``::\n\n    from django.db import migrations\n\n    class Migration(migrations.Migration):\n        atomic = False\n\nWithin such a migration, all operations are run without a transaction. It's\npossible to execute parts of the migration inside a transaction using\n:func:`~django.db.transaction.atomic()` or by passing ``atomic=True`` to\n``RunPython``.\n\nHere's an example of a non-atomic data migration that updates a large table in\nsmaller batches::\n\n    import uuid\n\n    from django.db import migrations, transaction\n\n    def gen_uuid(apps, schema_editor):\n        MyModel = apps.get_model('myapp', 'MyModel')\n        while MyModel.objects.filter(uuid__isnull=True).exists():\n            with transaction.atomic():\n                for row in MyModel.objects.filter(uuid__isnull=True)[:1000]:\n                    row.uuid = uuid.uuid4()\n                    row.save()\n\n    class Migration(migrations.Migration):\n        atomic = False\n\n        operations = [\n            migrations.RunPython(gen_uuid),\n        ]\n\nThe ``atomic`` attribute doesn't have an effect on databases that don't support\nDDL transactions (e.g. MySQL, Oracle). (MySQL's `atomic DDL statement support\n<https://dev.mysql.com/doc/refman/en/atomic-ddl.html>`_ refers to individual\nstatements rather than multiple statements wrapped in a transaction that can be\nrolled back.)\n\nControlling the order of migrations\n===================================\n\nDjango determines the order in which migrations should be applied not by the\nfilename of each migration, but by building a graph using two properties on the\n``Migration`` class: ``dependencies`` and ``run_before``.\n\nIf you've used the :djadmin:`makemigrations` command you've probably\nalready seen ``dependencies`` in action because auto-created\nmigrations have this defined as part of their creation process.\n\nThe ``dependencies`` property is declared like this::\n\n    from django.db import migrations\n\n    class Migration(migrations.Migration):\n\n        dependencies = [\n            ('myapp', '0123_the_previous_migration'),\n        ]\n\nUsually this will be enough, but from time to time you may need to\nensure that your migration runs *before* other migrations. This is\nuseful, for example, to make third-party apps' migrations run *after*\nyour :setting:`AUTH_USER_MODEL` replacement.\n\nTo achieve this, place all migrations that should depend on yours in\nthe ``run_before`` attribute on your ``Migration`` class::\n\n    class Migration(migrations.Migration):\n        ...\n\n        run_before = [\n            ('third_party_app', '0001_do_awesome'),\n        ]\n\nPrefer using ``dependencies`` over ``run_before`` when possible. You should\nonly use ``run_before`` if it is undesirable or impractical to specify\n``dependencies`` in the migration which you want to run after the one you are\nwriting.\n\nMigrating data between third-party apps\n=======================================\n\nYou can use a data migration to move data from one third-party application to\nanother.\n\nIf you plan to remove the old app later, you'll need to set the ``dependencies``\nproperty based on whether or not the old app is installed. Otherwise, you'll\nhave missing dependencies once you uninstall the old app. Similarly, you'll\nneed to catch :exc:`LookupError` in the ``apps.get_model()`` call that\nretrieves models from the old app. This approach allows you to deploy your\nproject anywhere without first installing and then uninstalling the old app.\n\nHere's a sample migration:\n\n.. code-block:: python\n    :caption: myapp/migrations/0124_move_old_app_to_new_app.py\n\n    from django.apps import apps as global_apps\n    from django.db import migrations\n\n    def forwards(apps, schema_editor):\n        try:\n            OldModel = apps.get_model('old_app', 'OldModel')\n        except LookupError:\n            # The old app isn't installed.\n            return\n\n        NewModel = apps.get_model('new_app', 'NewModel')\n        NewModel.objects.bulk_create(\n            NewModel(new_attribute=old_object.old_attribute)\n            for old_object in OldModel.objects.all()\n        )\n\n    class Migration(migrations.Migration):\n        operations = [\n            migrations.RunPython(forwards, migrations.RunPython.noop),\n        ]\n        dependencies = [\n            ('myapp', '0123_the_previous_migration'),\n            ('new_app', '0001_initial'),\n        ]\n\n        if global_apps.is_installed('old_app'):\n            dependencies.append(('old_app', '0001_initial'))\n\nAlso consider what you want to happen when the migration is unapplied. You\ncould either do nothing (as in the example above) or remove some or all of the\ndata from the new application. Adjust the second argument of the\n:mod:`~django.db.migrations.operations.RunPython` operation accordingly.\n\n.. _changing-a-manytomanyfield-to-use-a-through-model:\n\nChanging a ``ManyToManyField`` to use a ``through`` model\n=========================================================\n\nIf you change a :class:`~django.db.models.ManyToManyField` to use a ``through``\nmodel, the default migration will delete the existing table and create a new\none, losing the existing relations. To avoid this, you can use\n:class:`.SeparateDatabaseAndState` to rename the existing table to the new\ntable name whilst telling the migration autodetector that the new model has\nbeen created. You can check the existing table name through\n:djadmin:`sqlmigrate` or :djadmin:`dbshell`. You can check the new table name\nwith the through model's ``_meta.db_table`` property. Your new ``through``\nmodel should use the same names for the ``ForeignKey``\\s as Django did. Also if\nit needs any extra fields, they should be added in operations after\n:class:`.SeparateDatabaseAndState`.\n\nFor example, if we had a ``Book`` model with a ``ManyToManyField`` linking to\n``Author``, we could add a through model ``AuthorBook`` with a new field\n``is_primary``, like so::\n\n    from django.db import migrations, models\n    import django.db.models.deletion\n\n\n    class Migration(migrations.Migration):\n        dependencies = [\n            ('core', '0001_initial'),\n        ]\n\n        operations = [\n            migrations.SeparateDatabaseAndState(\n                database_operations=[\n                    # Old table name from checking with sqlmigrate, new table\n                    # name from AuthorBook._meta.db_table.\n                    migrations.RunSQL(\n                        sql='ALTER TABLE core_book_authors RENAME TO core_authorbook',\n                        reverse_sql='ALTER TABLE core_authorbook RENAME TO core_book_authors',\n                    ),\n                ],\n                state_operations=[\n                    migrations.CreateModel(\n                        name='AuthorBook',\n                        fields=[\n                            (\n                                'id',\n                                models.AutoField(\n                                    auto_created=True,\n                                    primary_key=True,\n                                    serialize=False,\n                                    verbose_name='ID',\n                                ),\n                            ),\n                            (\n                                'author',\n                                models.ForeignKey(\n                                    on_delete=django.db.models.deletion.DO_NOTHING,\n                                    to='core.Author',\n                                ),\n                            ),\n                            (\n                                'book',\n                                models.ForeignKey(\n                                    on_delete=django.db.models.deletion.DO_NOTHING,\n                                    to='core.Book',\n                                ),\n                            ),\n                        ],\n                    ),\n                    migrations.AlterField(\n                        model_name='book',\n                        name='authors',\n                        field=models.ManyToManyField(\n                            to='core.Author',\n                            through='core.AuthorBook',\n                        ),\n                    ),\n                ],\n            ),\n            migrations.AddField(\n                model_name='authorbook',\n                name='is_primary',\n                field=models.BooleanField(default=False),\n            ),\n        ]\n\nChanging an unmanaged model to managed\n======================================\n\nIf you want to change an unmanaged model (:attr:`managed=False\n<django.db.models.Options.managed>`) to managed, you must remove\n``managed=False`` and generate a migration before making other schema-related\nchanges to the model, since schema changes that appear in the migration that\ncontains the operation to change ``Meta.managed`` may not be applied.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":195,"nodeType":"TextFile","repoName":null,"name":"error-reporting.txt","path":"docs/howto","text":"===============\nError reporting\n===============\n\nWhen you're running a public site you should always turn off the\n:setting:`DEBUG` setting. That will make your server run much faster, and will\nalso prevent malicious users from seeing details of your application that can be\nrevealed by the error pages.\n\nHowever, running with :setting:`DEBUG` set to ``False`` means you'll never see\nerrors generated by your site -- everyone will instead see your public error\npages. You need to keep track of errors that occur in deployed sites, so Django\ncan be configured to create reports with details about those errors.\n\nEmail reports\n=============\n\nServer errors\n-------------\n\nWhen :setting:`DEBUG` is ``False``, Django will email the users listed in the\n:setting:`ADMINS` setting whenever your code raises an unhandled exception and\nresults in an internal server error (strictly speaking, for any response with\nan HTTP status code of 500 or greater). This gives the administrators immediate\nnotification of any errors. The :setting:`ADMINS` will get a description of the\nerror, a complete Python traceback, and details about the HTTP request that\ncaused the error.\n\n.. note::\n\n   In order to send email, Django requires a few settings telling it\n   how to connect to your mail server. At the very least, you'll need\n   to specify :setting:`EMAIL_HOST` and possibly\n   :setting:`EMAIL_HOST_USER` and :setting:`EMAIL_HOST_PASSWORD`,\n   though other settings may be also required depending on your mail\n   server's configuration. Consult :doc:`the Django settings\n   documentation </ref/settings>` for a full list of email-related\n   settings.\n\nBy default, Django will send email from root@localhost. However, some mail\nproviders reject all email from this address. To use a different sender\naddress, modify the :setting:`SERVER_EMAIL` setting.\n\nTo activate this behavior, put the email addresses of the recipients in the\n:setting:`ADMINS` setting.\n\n.. seealso::\n\n    Server error emails are sent using the logging framework, so you can\n    customize this behavior by :doc:`customizing your logging configuration\n    </topics/logging>`.\n\n404 errors\n----------\n\nDjango can also be configured to email errors about broken links (404 \"page\nnot found\" errors). Django sends emails about 404 errors when:\n\n* :setting:`DEBUG` is ``False``;\n\n* Your :setting:`MIDDLEWARE` setting includes\n  :class:`django.middleware.common.BrokenLinkEmailsMiddleware`.\n\nIf those conditions are met, Django will email the users listed in the\n:setting:`MANAGERS` setting whenever your code raises a 404 and the request has\na referer. It doesn't bother to email for 404s that don't have a referer --\nthose are usually people typing in broken URLs or broken Web bots. It also\nignores 404s when the referer is equal to the requested URL, since this\nbehavior is from broken Web bots too.\n\n.. note::\n\n    :class:`~django.middleware.common.BrokenLinkEmailsMiddleware` must appear\n    before other middleware that intercepts 404 errors, such as\n    :class:`~django.middleware.locale.LocaleMiddleware` or\n    :class:`~django.contrib.flatpages.middleware.FlatpageFallbackMiddleware`.\n    Put it towards the top of your :setting:`MIDDLEWARE` setting.\n\nYou can tell Django to stop reporting particular 404s by tweaking the\n:setting:`IGNORABLE_404_URLS` setting. It should be a list of compiled\nregular expression objects. For example::\n\n    import re\n    IGNORABLE_404_URLS = [\n        re.compile(r'\\.(php|cgi)$'),\n        re.compile(r'^/phpmyadmin/'),\n    ]\n\nIn this example, a 404 to any URL ending with ``.php`` or ``.cgi`` will *not* be\nreported. Neither will any URL starting with ``/phpmyadmin/``.\n\nThe following example shows how to exclude some conventional URLs that browsers and\ncrawlers often request::\n\n    import re\n    IGNORABLE_404_URLS = [\n        re.compile(r'^/apple-touch-icon.*\\.png$'),\n        re.compile(r'^/favicon\\.ico$'),\n        re.compile(r'^/robots\\.txt$'),\n    ]\n\n(Note that these are regular expressions, so we put a backslash in front of\nperiods to escape them.)\n\nIf you'd like to customize the behavior of\n:class:`django.middleware.common.BrokenLinkEmailsMiddleware` further (for\nexample to ignore requests coming from web crawlers), you should subclass it\nand override its methods.\n\n.. seealso::\n\n    404 errors are logged using the logging framework. By default, these log\n    records are ignored, but you can use them for error reporting by writing a\n    handler and :doc:`configuring logging </topics/logging>` appropriately.\n\n.. _filtering-error-reports:\n\nFiltering error reports\n=======================\n\n.. warning::\n\n    Filtering sensitive data is a hard problem, and it's nearly impossible to\n    guarantee that sensitive data won't leak into an error report. Therefore,\n    error reports should only be available to trusted team members and you\n    should avoid transmitting error reports unencrypted over the Internet\n    (such as through email).\n\nFiltering sensitive information\n-------------------------------\n\n.. currentmodule:: django.views.decorators.debug\n\nError reports are really helpful for debugging errors, so it is generally\nuseful to record as much relevant information about those errors as possible.\nFor example, by default Django records the `full traceback`_ for the\nexception raised, each `traceback frame`_’s local variables, and the\n:class:`~django.http.HttpRequest`’s :ref:`attributes<httprequest-attributes>`.\n\nHowever, sometimes certain types of information may be too sensitive and thus\nmay not be appropriate to be kept track of, for example a user's password or\ncredit card number. So in addition to filtering out settings that appear to be\nsensitive as described in the :setting:`DEBUG` documentation, Django offers a\nset of function decorators to help you control which information should be\nfiltered out of error reports in a production environment (that is, where\n:setting:`DEBUG` is set to ``False``): :func:`sensitive_variables` and\n:func:`sensitive_post_parameters`.\n\n.. _`full traceback`: https://en.wikipedia.org/wiki/Stack_trace\n.. _`traceback frame`: https://en.wikipedia.org/wiki/Stack_frame\n\n.. function:: sensitive_variables(*variables)\n\n    If a function (either a view or any regular callback) in your code uses\n    local variables susceptible to contain sensitive information, you may\n    prevent the values of those variables from being included in error reports\n    using the ``sensitive_variables`` decorator::\n\n        from django.views.decorators.debug import sensitive_variables\n\n        @sensitive_variables('user', 'pw', 'cc')\n        def process_info(user):\n            pw = user.pass_word\n            cc = user.credit_card_number\n            name = user.name\n            ...\n\n    In the above example, the values for the ``user``, ``pw`` and ``cc``\n    variables will be hidden and replaced with stars (``**********``)\n    in the error reports, whereas the value of the ``name`` variable will be\n    disclosed.\n\n    To systematically hide all local variables of a function from error logs,\n    do not provide any argument to the ``sensitive_variables`` decorator::\n\n        @sensitive_variables()\n        def my_function():\n            ...\n\n    .. admonition:: When using multiple decorators\n\n        If the variable you want to hide is also a function argument (e.g.\n        '``user``’ in the following example), and if the decorated function has\n        multiple decorators, then make sure to place ``@sensitive_variables``\n        at the top of the decorator chain. This way it will also hide the\n        function argument as it gets passed through the other decorators::\n\n            @sensitive_variables('user', 'pw', 'cc')\n            @some_decorator\n            @another_decorator\n            def process_info(user):\n                ...\n\n.. function:: sensitive_post_parameters(*parameters)\n\n    If one of your views receives an :class:`~django.http.HttpRequest` object\n    with :attr:`POST parameters<django.http.HttpRequest.POST>` susceptible to\n    contain sensitive information, you may prevent the values of those\n    parameters from being included in the error reports using the\n    ``sensitive_post_parameters`` decorator::\n\n        from django.views.decorators.debug import sensitive_post_parameters\n\n        @sensitive_post_parameters('pass_word', 'credit_card_number')\n        def record_user_profile(request):\n            UserProfile.create(\n                user=request.user,\n                password=request.POST['pass_word'],\n                credit_card=request.POST['credit_card_number'],\n                name=request.POST['name'],\n            )\n            ...\n\n    In the above example, the values for the ``pass_word`` and\n    ``credit_card_number`` POST parameters will be hidden and replaced with\n    stars (``**********``) in the request's representation inside the\n    error reports, whereas the value of the ``name`` parameter will be\n    disclosed.\n\n    To systematically hide all POST parameters of a request in error reports,\n    do not provide any argument to the ``sensitive_post_parameters`` decorator::\n\n        @sensitive_post_parameters()\n        def my_view(request):\n            ...\n\n    All POST parameters are systematically filtered out of error reports for\n    certain :mod:`django.contrib.auth.views` views (``login``,\n    ``password_reset_confirm``, ``password_change``, and ``add_view`` and\n    ``user_change_password`` in the ``auth`` admin) to prevent the leaking of\n    sensitive information such as user passwords.\n\n.. _custom-error-reports:\n\nCustom error reports\n--------------------\n\nAll :func:`sensitive_variables` and :func:`sensitive_post_parameters` do is,\nrespectively, annotate the decorated function with the names of sensitive\nvariables and annotate the ``HttpRequest`` object with the names of sensitive\nPOST parameters, so that this sensitive information can later be filtered out\nof reports when an error occurs. The actual filtering is done by Django's\ndefault error reporter filter:\n:class:`django.views.debug.SafeExceptionReporterFilter`. This filter uses the\ndecorators' annotations to replace the corresponding values with stars\n(``**********``) when the error reports are produced. If you wish to\noverride or customize this default behavior for your entire site, you need to\ndefine your own filter class and tell Django to use it via the\n:setting:`DEFAULT_EXCEPTION_REPORTER_FILTER` setting::\n\n    DEFAULT_EXCEPTION_REPORTER_FILTER = 'path.to.your.CustomExceptionReporterFilter'\n\nYou may also control in a more granular way which filter to use within any\ngiven view by setting the ``HttpRequest``’s ``exception_reporter_filter``\nattribute::\n\n    def my_view(request):\n        if request.user.is_authenticated:\n            request.exception_reporter_filter = CustomExceptionReporterFilter()\n        ...\n\n.. currentmodule:: django.views.debug\n\nYour custom filter class needs to inherit from\n:class:`django.views.debug.SafeExceptionReporterFilter` and may override the\nfollowing attributes and methods:\n\n.. class:: SafeExceptionReporterFilter\n\n    .. attribute:: cleansed_substitute\n\n        .. versionadded:: 3.1\n\n        The string value to replace sensitive value with. By default it\n        replaces the values of sensitive variables with stars\n        (``**********``).\n\n    .. attribute:: hidden_settings\n\n        .. versionadded:: 3.1\n\n        A compiled regular expression object used to match settings and\n        ``request.META`` values considered as sensitive. By default equivalent\n        to::\n\n            import re\n\n            re.compile(r'API|TOKEN|KEY|SECRET|PASS|SIGNATURE', flags=re.IGNORECASE)\n\n    .. method:: is_active(request)\n\n        Returns ``True`` to activate the filtering in\n        :meth:`get_post_parameters` and :meth:`get_traceback_frame_variables`.\n        By default the filter is active if :setting:`DEBUG` is ``False``. Note\n        that sensitive ``request.META`` values are always filtered along with\n        sensitive setting values, as described in the :setting:`DEBUG`\n        documentation.\n\n    .. method:: get_post_parameters(request)\n\n        Returns the filtered dictionary of POST parameters. Sensitive values\n        are replaced with :attr:`cleansed_substitute`.\n\n    .. method:: get_traceback_frame_variables(request, tb_frame)\n\n        Returns the filtered dictionary of local variables for the given\n        traceback frame. Sensitive values are replaced with\n        :attr:`cleansed_substitute`.\n\n.. versionadded:: 3.1\n\nIf you need to customize error reports beyond filtering you may specify a\ncustom error reporter class by defining the\n:setting:`DEFAULT_EXCEPTION_REPORTER` setting::\n\n    DEFAULT_EXCEPTION_REPORTER = 'path.to.your.CustomExceptionReporter'\n\nThe exception reporter is responsible for compiling the exception report data,\nand formatting it as text or HTML appropriately. (The exception reporter uses\n:setting:`DEFAULT_EXCEPTION_REPORTER_FILTER` when preparing the exception\nreport data.)\n\nYour custom reporter class needs to inherit from\n:class:`django.views.debug.ExceptionReporter`.\n\n.. class:: ExceptionReporter\n\n    .. method:: get_traceback_data()\n\n        Return a dictionary containing traceback information.\n\n        This is the main extension point for customizing exception reports, for\n        example::\n\n            from django.views.debug import ExceptionReporter\n\n\n            class CustomExceptionReporter(ExceptionReporter):\n                def get_traceback_data(self):\n                    data = super().get_traceback_data()\n                    # ... remove/add something here ...\n                    return data\n\n    .. method:: get_traceback_html()\n\n        Return HTML version of exception report.\n\n        Used for HTML version of debug 500 HTTP error page.\n\n    .. method:: get_traceback_text()\n\n        Return plain text version of exception report.\n\n        Used for plain text version of debug 500 HTTP error page and email\n        reports.\n\nAs with the filter class, you may control which exception reporter class to use\nwithin any given view by setting the ``HttpRequest``’s\n``exception_reporter_class`` attribute::\n\n    def my_view(request):\n        if request.user.is_authenticated:\n            request.exception_reporter_class = CustomExceptionReporter()\n        ...\n\n.. seealso::\n\n    You can also set up custom error reporting by writing a custom piece of\n    :ref:`exception middleware <exception-middleware>`. If you do write custom\n    error handling, it's a good idea to emulate Django's built-in error handling\n    and only report/log errors if :setting:`DEBUG` is ``False``.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":196,"nodeType":"Package","repoName":null,"name":"docs/howto/deployment/wsgi","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":197,"nodeType":"TextFile","repoName":null,"name":"modwsgi.txt","path":"docs/howto/deployment/wsgi","text":"==============================================\nHow to use Django with Apache and ``mod_wsgi``\n==============================================\n\nDeploying Django with Apache_ and `mod_wsgi`_ is a tried and tested way to get\nDjango into production.\n\n.. _Apache: https://httpd.apache.org/\n.. _mod_wsgi: https://modwsgi.readthedocs.io/en/develop/\n\nmod_wsgi is an Apache module which can host any Python WSGI_ application,\nincluding Django. Django will work with any version of Apache which supports\nmod_wsgi.\n\n.. _WSGI: https://wsgi.readthedocs.io/en/latest/\n\nThe `official mod_wsgi documentation`_ is your source for all the details about\nhow to use mod_wsgi. You'll probably want to start with the `installation and\nconfiguration documentation`_.\n\n.. _official mod_wsgi documentation: https://modwsgi.readthedocs.io/\n.. _installation and configuration documentation: https://modwsgi.readthedocs.io/en/develop/installation.html\n\nBasic configuration\n===================\n\nOnce you've got mod_wsgi installed and activated, edit your Apache server's\n`httpd.conf`_ file and add the following. If you are using a version of Apache\nolder than 2.4, replace ``Require all granted`` with ``Allow from all`` and\nalso add the line ``Order deny,allow`` above it.\n\n.. _httpd.conf: https://wiki.apache.org/httpd/DistrosDefaultLayout\n\n.. code-block:: apache\n\n    WSGIScriptAlias / /path/to/mysite.com/mysite/wsgi.py\n    WSGIPythonHome /path/to/venv\n    WSGIPythonPath /path/to/mysite.com\n\n    <Directory /path/to/mysite.com/mysite>\n    <Files wsgi.py>\n    Require all granted\n    </Files>\n    </Directory>\n\nThe first bit in the ``WSGIScriptAlias`` line is the base URL path you want to\nserve your application at (``/`` indicates the root url), and the second is the\nlocation of a \"WSGI file\" -- see below -- on your system, usually inside of\nyour project package (``mysite`` in this example). This tells Apache to serve\nany request below the given URL using the WSGI application defined in that\nfile.\n\nIf you install your project's Python dependencies inside a `virtualenv`_, add\nthe path to the virtualenv using ``WSGIPythonHome``. See the `mod_wsgi\nvirtualenv guide`_ for more details.\n\nThe ``WSGIPythonPath`` line ensures that your project package is available for\nimport on the Python path; in other words, that ``import mysite`` works.\n\nThe ``<Directory>`` piece ensures that Apache can access your :file:`wsgi.py`\nfile.\n\nNext we'll need to ensure this :file:`wsgi.py` with a WSGI application object\nexists. As of Django version 1.4, :djadmin:`startproject` will have created one\nfor you; otherwise, you'll need to create it. See the :doc:`WSGI overview\ndocumentation</howto/deployment/wsgi/index>` for the default contents you\nshould put in this file, and what else you can add to it.\n\n.. _virtualenv: https://virtualenv.pypa.io/\n.. _mod_wsgi virtualenv guide: https://modwsgi.readthedocs.io/en/develop/user-guides/virtual-environments.html\n\n.. warning::\n\n    If multiple Django sites are run in a single mod_wsgi process, all of them\n    will use the settings of whichever one happens to run first. This can be\n    solved by changing::\n\n        os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"{{ project_name }}.settings\")\n\n    in ``wsgi.py``, to::\n\n        os.environ[\"DJANGO_SETTINGS_MODULE\"] = \"{{ project_name }}.settings\"\n\n    or by :ref:`using mod_wsgi daemon mode<daemon-mode>` and ensuring that each\n    site runs in its own daemon process.\n\n.. admonition:: Fixing ``UnicodeEncodeError`` for file uploads\n\n    If you get a ``UnicodeEncodeError`` when uploading files with file names\n    that contain non-ASCII characters, make sure Apache is configured to accept\n    non-ASCII file names::\n\n        export LANG='en_US.UTF-8'\n        export LC_ALL='en_US.UTF-8'\n\n    A common location to put this configuration is ``/etc/apache2/envvars``.\n\n    See the :ref:`unicode-files` section of the Unicode reference guide for\n    details.\n\n.. _daemon-mode:\n\nUsing ``mod_wsgi`` daemon mode\n==============================\n\n\"Daemon mode\" is the recommended mode for running mod_wsgi (on non-Windows\nplatforms). To create the required daemon process group and delegate the\nDjango instance to run in it, you will need to add appropriate\n``WSGIDaemonProcess`` and ``WSGIProcessGroup`` directives. A further change\nrequired to the above configuration if you use daemon mode is that you can't\nuse ``WSGIPythonPath``; instead you should use the ``python-path`` option to\n``WSGIDaemonProcess``, for example:\n\n.. code-block:: apache\n\n    WSGIDaemonProcess example.com python-home=/path/to/venv python-path=/path/to/mysite.com\n    WSGIProcessGroup example.com\n\nIf you want to serve your project in a subdirectory\n(``https://example.com/mysite`` in this example), you can add ``WSGIScriptAlias``\nto the configuration above:\n\n.. code-block:: apache\n\n    WSGIScriptAlias /mysite /path/to/mysite.com/mysite/wsgi.py process-group=example.com\n\nSee the official mod_wsgi documentation for `details on setting up daemon\nmode`_.\n\n.. _details on setting up daemon mode: https://modwsgi.readthedocs.io/en/develop/user-guides/quick-configuration-guide.html#delegation-to-daemon-process\n\n.. _serving-files:\n\nServing files\n=============\n\nDjango doesn't serve files itself; it leaves that job to whichever Web\nserver you choose.\n\nWe recommend using a separate Web server -- i.e., one that's not also running\nDjango -- for serving media. Here are some good choices:\n\n* Nginx_\n* A stripped-down version of Apache_\n\nIf, however, you have no option but to serve media files on the same Apache\n``VirtualHost`` as Django, you can set up Apache to serve some URLs as\nstatic media, and others using the mod_wsgi interface to Django.\n\nThis example sets up Django at the site root, but serves ``robots.txt``,\n``favicon.ico``, and anything in the ``/static/`` and ``/media/`` URL space as\na static file. All other URLs will be served using mod_wsgi:\n\n.. code-block:: apache\n\n    Alias /robots.txt /path/to/mysite.com/static/robots.txt\n    Alias /favicon.ico /path/to/mysite.com/static/favicon.ico\n\n    Alias /media/ /path/to/mysite.com/media/\n    Alias /static/ /path/to/mysite.com/static/\n\n    <Directory /path/to/mysite.com/static>\n    Require all granted\n    </Directory>\n\n    <Directory /path/to/mysite.com/media>\n    Require all granted\n    </Directory>\n\n    WSGIScriptAlias / /path/to/mysite.com/mysite/wsgi.py\n\n    <Directory /path/to/mysite.com/mysite>\n    <Files wsgi.py>\n    Require all granted\n    </Files>\n    </Directory>\n\nIf you are using a version of Apache older than 2.4, replace\n``Require all granted`` with ``Allow from all`` and also add the line\n``Order deny,allow`` above it.\n\n.. _Nginx: https://nginx.org/en/\n.. _Apache: https://httpd.apache.org/\n\n.. More details on configuring a mod_wsgi site to serve static files can be found\n.. in the mod_wsgi documentation on `hosting static files`_.\n\n.. _hosting static files: https://modwsgi.readthedocs.io/en/develop/user-guides/configuration-guidelines.html#hosting-of-static-files\n\n.. _serving-the-admin-files:\n\nServing the admin files\n=======================\n\nWhen :mod:`django.contrib.staticfiles` is in :setting:`INSTALLED_APPS`, the\nDjango development server automatically serves the static files of the\nadmin app (and any other installed apps). This is however not the case when you\nuse any other server arrangement. You're responsible for setting up Apache, or\nwhichever Web server you're using, to serve the admin files.\n\nThe admin files live in (:file:`django/contrib/admin/static/admin`) of the\nDjango distribution.\n\nWe **strongly** recommend using :mod:`django.contrib.staticfiles` to handle the\nadmin files (along with a Web server as outlined in the previous section; this\nmeans using the :djadmin:`collectstatic` management command to collect the\nstatic files in :setting:`STATIC_ROOT`, and then configuring your Web server to\nserve :setting:`STATIC_ROOT` at :setting:`STATIC_URL`), but here are three\nother approaches:\n\n1. Create a symbolic link to the admin static files from within your\n   document root (this may require ``+FollowSymLinks`` in your Apache\n   configuration).\n\n2. Use an ``Alias`` directive, as demonstrated above, to alias the appropriate\n   URL (probably :setting:`STATIC_URL` + ``admin/``) to the actual location of\n   the admin files.\n\n3. Copy the admin static files so that they live within your Apache\n   document root.\n\nAuthenticating against Django's user database from Apache\n=========================================================\n\nDjango provides a handler to allow Apache to authenticate users directly\nagainst Django's authentication backends. See the :doc:`mod_wsgi authentication\ndocumentation </howto/deployment/wsgi/apache-auth>`.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":198,"nodeType":"TextFile","repoName":null,"name":"custom-management-commands.txt","path":"docs/howto","text":"========================================\nWriting custom ``django-admin`` commands\n========================================\n\n.. module:: django.core.management\n\nApplications can register their own actions with ``manage.py``. For example,\nyou might want to add a ``manage.py`` action for a Django app that you're\ndistributing. In this document, we will be building a custom ``closepoll``\ncommand for the ``polls`` application from the\n:doc:`tutorial</intro/tutorial01>`.\n\nTo do this, add a ``management/commands`` directory to the application. Django\nwill register a ``manage.py`` command for each Python module in that directory\nwhose name doesn't begin with an underscore. For example::\n\n    polls/\n        __init__.py\n        models.py\n        management/\n            commands/\n                _private.py\n                closepoll.py\n        tests.py\n        views.py\n\nIn this example, the ``closepoll`` command will be made available to any project\nthat includes the ``polls`` application in :setting:`INSTALLED_APPS`.\n\nThe ``_private.py`` module will not be available as a management command.\n\nThe ``closepoll.py`` module has only one requirement -- it must define a class\n``Command`` that extends :class:`BaseCommand` or one of its\n:ref:`subclasses<ref-basecommand-subclasses>`.\n\n.. admonition:: Standalone scripts\n\n    Custom management commands are especially useful for running standalone\n    scripts or for scripts that are periodically executed from the UNIX crontab\n    or from Windows scheduled tasks control panel.\n\nTo implement the command, edit ``polls/management/commands/closepoll.py`` to\nlook like this::\n\n    from django.core.management.base import BaseCommand, CommandError\n    from polls.models import Question as Poll\n\n    class Command(BaseCommand):\n        help = 'Closes the specified poll for voting'\n\n        def add_arguments(self, parser):\n            parser.add_argument('poll_ids', nargs='+', type=int)\n\n        def handle(self, *args, **options):\n            for poll_id in options['poll_ids']:\n                try:\n                    poll = Poll.objects.get(pk=poll_id)\n                except Poll.DoesNotExist:\n                    raise CommandError('Poll \"%s\" does not exist' % poll_id)\n\n                poll.opened = False\n                poll.save()\n\n                self.stdout.write(self.style.SUCCESS('Successfully closed poll \"%s\"' % poll_id))\n\n.. _management-commands-output:\n\n.. note::\n    When you are using management commands and wish to provide console\n    output, you should write to ``self.stdout`` and ``self.stderr``,\n    instead of printing to ``stdout`` and ``stderr`` directly. By\n    using these proxies, it becomes much easier to test your custom\n    command. Note also that you don't need to end messages with a newline\n    character, it will be added automatically, unless you specify the ``ending``\n    parameter::\n\n        self.stdout.write(\"Unterminated line\", ending='')\n\nThe new custom command can be called using ``python manage.py closepoll\n<poll_ids>``.\n\nThe ``handle()`` method takes one or more ``poll_ids`` and sets ``poll.opened``\nto ``False`` for each one. If the user referenced any nonexistent polls, a\n:exc:`CommandError` is raised. The ``poll.opened`` attribute does not exist in\nthe :doc:`tutorial</intro/tutorial02>` and was added to\n``polls.models.Question`` for this example.\n\n.. _custom-commands-options:\n\nAccepting optional arguments\n============================\n\nThe same ``closepoll`` could be easily modified to delete a given poll instead\nof closing it by accepting additional command line options. These custom\noptions can be added in the :meth:`~BaseCommand.add_arguments` method like this::\n\n    class Command(BaseCommand):\n        def add_arguments(self, parser):\n            # Positional arguments\n            parser.add_argument('poll_ids', nargs='+', type=int)\n\n            # Named (optional) arguments\n            parser.add_argument(\n                '--delete',\n                action='store_true',\n                help='Delete poll instead of closing it',\n            )\n\n        def handle(self, *args, **options):\n            # ...\n            if options['delete']:\n                poll.delete()\n            # ...\n\nThe option (``delete`` in our example) is available in the options dict\nparameter of the handle method. See the :py:mod:`argparse` Python documentation\nfor more about ``add_argument`` usage.\n\nIn addition to being able to add custom command line options, all\n:doc:`management commands</ref/django-admin>` can accept some default options\nsuch as :option:`--verbosity` and :option:`--traceback`.\n\n.. _management-commands-and-locales:\n\nManagement commands and locales\n===============================\n\nBy default, management commands are executed with the current active locale.\n\nIf, for some reason, your custom management command must run without an active\nlocale (for example, to prevent translated content from being inserted into\nthe database), deactivate translations using the ``@no_translations``\ndecorator on your :meth:`~BaseCommand.handle` method::\n\n    from django.core.management.base import BaseCommand, no_translations\n\n    class Command(BaseCommand):\n        ...\n\n        @no_translations\n        def handle(self, *args, **options):\n            ...\n\nSince translation deactivation requires access to configured settings, the\ndecorator can't be used for commands that work without configured settings.\n\nTesting\n=======\n\nInformation on how to test custom management commands can be found in the\n:ref:`testing docs <topics-testing-management-commands>`.\n\nOverriding commands\n===================\n\nDjango registers the built-in commands and then searches for commands in\n:setting:`INSTALLED_APPS` in reverse. During the search, if a command name\nduplicates an already registered command, the newly discovered command\noverrides the first.\n\nIn other words, to override a command, the new command must have the same name\nand its app must be before the overridden command's app in\n:setting:`INSTALLED_APPS`.\n\nManagement commands from third-party apps that have been unintentionally\noverridden can be made available under a new name by creating a new command in\none of your project's apps (ordered before the third-party app in\n:setting:`INSTALLED_APPS`) which imports the ``Command`` of the overridden\ncommand.\n\nCommand objects\n===============\n\n.. class:: BaseCommand\n\nThe base class from which all management commands ultimately derive.\n\nUse this class if you want access to all of the mechanisms which\nparse the command-line arguments and work out what code to call in\nresponse; if you don't need to change any of that behavior,\nconsider using one of its :ref:`subclasses<ref-basecommand-subclasses>`.\n\nSubclassing the :class:`BaseCommand` class requires that you implement the\n:meth:`~BaseCommand.handle` method.\n\nAttributes\n----------\n\nAll attributes can be set in your derived class and can be used in\n:class:`BaseCommand`’s :ref:`subclasses<ref-basecommand-subclasses>`.\n\n.. attribute:: BaseCommand.help\n\n    A short description of the command, which will be printed in the\n    help message when the user runs the command\n    ``python manage.py help <command>``.\n\n.. attribute:: BaseCommand.missing_args_message\n\n    If your command defines mandatory positional arguments, you can customize\n    the message error returned in the case of missing arguments. The default is\n    output by :py:mod:`argparse` (\"too few arguments\").\n\n.. attribute:: BaseCommand.output_transaction\n\n    A boolean indicating whether the command outputs SQL statements; if\n    ``True``, the output will automatically be wrapped with ``BEGIN;`` and\n    ``COMMIT;``. Default value is ``False``.\n\n.. attribute:: BaseCommand.requires_migrations_checks\n\n    A boolean; if ``True``, the command prints a warning if the set of\n    migrations on disk don't match the migrations in the database. A warning\n    doesn't prevent the command from executing. Default value is ``False``.\n\n.. attribute:: BaseCommand.requires_system_checks\n\n    A boolean; if ``True``, the entire Django project will be checked for\n    potential problems prior to executing the command. Default value is ``True``.\n\n.. attribute:: BaseCommand.style\n\n    An instance attribute that helps create colored output when writing to\n    ``stdout`` or ``stderr``. For example::\n\n        self.stdout.write(self.style.SUCCESS('...'))\n\n    See :ref:`syntax-coloring` to learn how to modify the color palette and to\n    see the available styles (use uppercased versions of the \"roles\" described\n    in that section).\n\n    If you pass the :option:`--no-color` option when running your command, all\n    ``self.style()`` calls will return the original string uncolored.\n\nMethods\n-------\n\n:class:`BaseCommand` has a few methods that can be overridden but only\nthe :meth:`~BaseCommand.handle` method must be implemented.\n\n.. admonition:: Implementing a constructor in a subclass\n\n    If you implement ``__init__`` in your subclass of :class:`BaseCommand`,\n    you must call :class:`BaseCommand`’s ``__init__``::\n\n        class Command(BaseCommand):\n            def __init__(self, *args, **kwargs):\n                super().__init__(*args, **kwargs)\n                # ...\n\n.. method:: BaseCommand.create_parser(prog_name, subcommand, **kwargs)\n\n    Returns a ``CommandParser`` instance, which is an\n    :class:`~argparse.ArgumentParser` subclass with a few customizations for\n    Django.\n\n    You can customize the instance by overriding this method and calling\n    ``super()`` with ``kwargs`` of :class:`~argparse.ArgumentParser` parameters.\n\n.. method:: BaseCommand.add_arguments(parser)\n\n    Entry point to add parser arguments to handle command line arguments passed\n    to the command. Custom commands should override this method to add both\n    positional and optional arguments accepted by the command. Calling\n    ``super()`` is not needed when directly subclassing ``BaseCommand``.\n\n.. method:: BaseCommand.get_version()\n\n    Returns the Django version, which should be correct for all built-in Django\n    commands. User-supplied commands can override this method to return their\n    own version.\n\n.. method:: BaseCommand.execute(*args, **options)\n\n    Tries to execute this command, performing system checks if needed (as\n    controlled by the :attr:`requires_system_checks` attribute). If the command\n    raises a :exc:`CommandError`, it's intercepted and printed to stderr.\n\n.. admonition:: Calling a management command in your code\n\n    ``execute()`` should not be called directly from your code to execute a\n    command. Use :func:`~django.core.management.call_command` instead.\n\n.. method:: BaseCommand.handle(*args, **options)\n\n    The actual logic of the command. Subclasses must implement this method.\n\n    It may return a string which will be printed to ``stdout`` (wrapped\n    by ``BEGIN;`` and ``COMMIT;`` if :attr:`output_transaction` is ``True``).\n\n.. method:: BaseCommand.check(app_configs=None, tags=None, display_num_errors=False)\n\n    Uses the system check framework to inspect the entire Django project for\n    potential problems. Serious problems are raised as a :exc:`CommandError`;\n    warnings are output to stderr; minor notifications are output to stdout.\n\n    If ``app_configs`` and ``tags`` are both ``None``, all system checks are\n    performed. ``tags`` can be a list of check tags, like ``compatibility`` or\n    ``models``.\n\n.. _ref-basecommand-subclasses:\n\n``BaseCommand`` subclasses\n--------------------------\n\n.. class:: AppCommand\n\nA management command which takes one or more installed application labels as\narguments, and does something with each of them.\n\nRather than implementing :meth:`~BaseCommand.handle`, subclasses must\nimplement :meth:`~AppCommand.handle_app_config`, which will be called once for\neach application.\n\n.. method:: AppCommand.handle_app_config(app_config, **options)\n\n    Perform the command's actions for ``app_config``, which will be an\n    :class:`~django.apps.AppConfig` instance corresponding to an application\n    label given on the command line.\n\n.. class:: LabelCommand\n\nA management command which takes one or more arbitrary arguments (labels) on\nthe command line, and does something with each of them.\n\nRather than implementing :meth:`~BaseCommand.handle`, subclasses must implement\n:meth:`~LabelCommand.handle_label`, which will be called once for each label.\n\n.. attribute:: LabelCommand.label\n\n    A string describing the arbitrary arguments passed to the command. The\n    string is used in the usage text and error messages of the command.\n    Defaults to ``'label'``.\n\n.. method:: LabelCommand.handle_label(label, **options)\n\n    Perform the command's actions for ``label``, which will be the string as\n    given on the command line.\n\nCommand exceptions\n------------------\n\n.. exception:: CommandError(returncode=1)\n\nException class indicating a problem while executing a management command.\n\nIf this exception is raised during the execution of a management command from a\ncommand line console, it will be caught and turned into a nicely-printed error\nmessage to the appropriate output stream (i.e., stderr); as a result, raising\nthis exception (with a sensible description of the error) is the preferred way\nto indicate that something has gone wrong in the execution of a command. It\naccepts the optional ``returncode`` argument to customize the exit status for\nthe management command to exit with, using :func:`sys.exit`.\n\nIf a management command is called from code through\n:func:`~django.core.management.call_command`, it's up to you to catch the\nexception when needed.\n\n.. versionchanged:: 3.1\n\n    The ``returncode`` argument was added.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":199,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/howto/deployment/asgi","text":"=======================\nHow to deploy with ASGI\n=======================\n\nAs well as WSGI, Django also supports deploying on ASGI_, the emerging Python\nstandard for asynchronous web servers and applications.\n\n.. _ASGI: https://asgi.readthedocs.io/en/latest/\n\nDjango's :djadmin:`startproject` management command sets up a default ASGI\nconfiguration for you, which you can tweak as needed for your project, and\ndirect any ASGI-compliant application server to use.\n\nDjango includes getting-started documentation for the following ASGI servers:\n\n.. toctree::\n   :maxdepth: 1\n\n   daphne\n   uvicorn\n\nThe ``application`` object\n==========================\n\nLike WSGI, ASGI has you supply an ``application`` callable which\nthe application server uses to communicate with your code. It's commonly\nprovided as an object named ``application`` in a Python module accessible to\nthe server.\n\nThe :djadmin:`startproject` command creates a file\n:file:`<project_name>/asgi.py` that contains such an ``application`` callable.\n\nIt's not used by the development server (``runserver``), but can be used by\nany ASGI server either in development or in production.\n\nASGI servers usually take the path to the application callable as a string;\nfor most Django projects, this will look like ``myproject.asgi:application``.\n\n.. warning::\n\n    While Django's default ASGI handler will run all your code in a synchronous\n    thread, if you choose to run your own async handler you must be aware of\n    async-safety.\n\n    Do not call blocking synchronous functions or libraries in any async code.\n    Django prevents you from doing this with the parts of Django that are not\n    async-safe, but the same may not be true of third-party apps or Python\n    libraries.\n\nConfiguring the settings module\n===============================\n\nWhen the ASGI server loads your application, Django needs to import the\nsettings module — that's where your entire application is defined.\n\nDjango uses the :envvar:`DJANGO_SETTINGS_MODULE` environment variable to locate\nthe appropriate settings module. It must contain the dotted path to the\nsettings module. You can use a different value for development and production;\nit all depends on how you organize your settings.\n\nIf this variable isn't set, the default :file:`asgi.py` sets it to\n``mysite.settings``, where ``mysite`` is the name of your project.\n\nApplying ASGI middleware\n========================\n\nTo apply ASGI middleware, or to embed Django in another ASGI application, you\ncan wrap Django's ``application`` object in the ``asgi.py`` file. For example::\n\n    from some_asgi_library import AmazingMiddleware\n    application = AmazingMiddleware(application)\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":200,"nodeType":"TextFile","repoName":null,"name":"checklist.txt","path":"docs/howto/deployment","text":"====================\nDeployment checklist\n====================\n\nThe Internet is a hostile environment. Before deploying your Django project,\nyou should take some time to review your settings, with security, performance,\nand operations in mind.\n\nDjango includes many :doc:`security features </topics/security>`. Some are\nbuilt-in and always enabled. Others are optional because they aren't always\nappropriate, or because they're inconvenient for development. For example,\nforcing HTTPS may not be suitable for all websites, and it's impractical for\nlocal development.\n\nPerformance optimizations are another category of trade-offs with convenience.\nFor instance, caching is useful in production, less so for local development.\nError reporting needs are also widely different.\n\nThe following checklist includes settings that:\n\n- must be set properly for Django to provide the expected level of security;\n- are expected to be different in each environment;\n- enable optional security features;\n- enable performance optimizations;\n- provide error reporting.\n\nMany of these settings are sensitive and should be treated as confidential. If\nyou're releasing the source code for your project, a common practice is to\npublish suitable settings for development, and to use a private settings\nmodule for production.\n\nRun ``manage.py check --deploy``\n================================\n\nSome of the checks described below can be automated using the :option:`check\n--deploy` option. Be sure to run it against your production settings file as\ndescribed in the option's documentation.\n\nCritical settings\n=================\n\n:setting:`SECRET_KEY`\n---------------------\n\n**The secret key must be a large random value and it must be kept secret.**\n\nMake sure that the key used in production isn't used anywhere else and avoid\ncommitting it to source control. This reduces the number of vectors from which\nan attacker may acquire the key.\n\nInstead of hardcoding the secret key in your settings module, consider loading\nit from an environment variable::\n\n    import os\n    SECRET_KEY = os.environ['SECRET_KEY']\n\nor from a file::\n\n    with open('/etc/secret_key.txt') as f:\n        SECRET_KEY = f.read().strip()\n\n:setting:`DEBUG`\n----------------\n\n**You must never enable debug in production.**\n\nYou're certainly developing your project with :setting:`DEBUG = True <DEBUG>`,\nsince this enables handy features like full tracebacks in your browser.\n\nFor a production environment, though, this is a really bad idea, because it\nleaks lots of information about your project: excerpts of your source code,\nlocal variables, settings, libraries used, etc.\n\nEnvironment-specific settings\n=============================\n\n:setting:`ALLOWED_HOSTS`\n------------------------\n\nWhen :setting:`DEBUG = False <DEBUG>`, Django doesn't work at all without a\nsuitable value for :setting:`ALLOWED_HOSTS`.\n\nThis setting is required to protect your site against some CSRF attacks. If\nyou use a wildcard, you must perform your own validation of the ``Host`` HTTP\nheader, or otherwise ensure that you aren't vulnerable to this category of\nattacks.\n\nYou should also configure the Web server that sits in front of Django to\nvalidate the host. It should respond with a static error page or ignore\nrequests for incorrect hosts instead of forwarding the request to Django. This\nway you'll avoid spurious errors in your Django logs (or emails if you have\nerror reporting configured that way). For example, on nginx you might setup a\ndefault server to return \"444 No Response\" on an unrecognized host:\n\n.. code-block:: nginx\n\n    server {\n        listen 80 default_server;\n        return 444;\n    }\n\n:setting:`CACHES`\n-----------------\n\nIf you're using a cache, connection parameters may be different in development\nand in production. Django defaults to per-process :ref:`local-memory caching\n<local-memory-caching>` which may not be desirable.\n\nCache servers often have weak authentication. Make sure they only accept\nconnections from your application servers.\n\n:setting:`DATABASES`\n--------------------\n\nDatabase connection parameters are probably different in development and in\nproduction.\n\nDatabase passwords are very sensitive. You should protect them exactly like\n:setting:`SECRET_KEY`.\n\nFor maximum security, make sure database servers only accept connections from\nyour application servers.\n\nIf you haven't set up backups for your database, do it right now!\n\n:setting:`EMAIL_BACKEND` and related settings\n---------------------------------------------\n\nIf your site sends emails, these values need to be set correctly.\n\nBy default, Django sends email from webmaster@localhost and root@localhost.\nHowever, some mail providers reject email from these addresses. To use\ndifferent sender addresses, modify the :setting:`DEFAULT_FROM_EMAIL` and\n:setting:`SERVER_EMAIL` settings.\n\n:setting:`STATIC_ROOT` and :setting:`STATIC_URL`\n------------------------------------------------\n\nStatic files are automatically served by the development server. In\nproduction, you must define a :setting:`STATIC_ROOT` directory where\n:djadmin:`collectstatic` will copy them.\n\nSee :doc:`/howto/static-files/index` for more information.\n\n:setting:`MEDIA_ROOT` and :setting:`MEDIA_URL`\n----------------------------------------------\n\nMedia files are uploaded by your users. They're untrusted! Make sure your web\nserver never attempts to interpret them. For instance, if a user uploads a\n``.php`` file, the web server shouldn't execute it.\n\nNow is a good time to check your backup strategy for these files.\n\nHTTPS\n=====\n\nAny website which allows users to log in should enforce site-wide HTTPS to\navoid transmitting access tokens in clear. In Django, access tokens include\nthe login/password, the session cookie, and password reset tokens. (You can't\ndo much to protect password reset tokens if you're sending them by email.)\n\nProtecting sensitive areas such as the user account or the admin isn't\nsufficient, because the same session cookie is used for HTTP and HTTPS. Your\nweb server must redirect all HTTP traffic to HTTPS, and only transmit HTTPS\nrequests to Django.\n\nOnce you've set up HTTPS, enable the following settings.\n\n:setting:`CSRF_COOKIE_SECURE`\n-----------------------------\n\nSet this to ``True`` to avoid transmitting the CSRF cookie over HTTP\naccidentally.\n\n:setting:`SESSION_COOKIE_SECURE`\n--------------------------------\n\nSet this to ``True`` to avoid transmitting the session cookie over HTTP\naccidentally.\n\nPerformance optimizations\n=========================\n\nSetting :setting:`DEBUG = False <DEBUG>` disables several features that are\nonly useful in development. In addition, you can tune the following settings.\n\nSessions\n--------\n\nConsider using :ref:`cached sessions <cached-sessions-backend>` to improve\nperformance.\n\nIf using database-backed sessions, regularly :ref:`clear old sessions\n<clearing-the-session-store>` to avoid storing unnecessary data.\n\n:setting:`CONN_MAX_AGE`\n-----------------------\n\nEnabling :ref:`persistent database connections\n<persistent-database-connections>` can result in a nice speed-up when\nconnecting to the database accounts for a significant part of the request\nprocessing time.\n\nThis helps a lot on virtualized hosts with limited network performance.\n\n:setting:`TEMPLATES`\n--------------------\n\nEnabling the cached template loader often improves performance drastically, as\nit avoids compiling each template every time it needs to be rendered. See the\n:ref:`template loaders docs <template-loaders>` for more information.\n\nError reporting\n===============\n\nBy the time you push your code to production, it's hopefully robust, but you\ncan't rule out unexpected errors. Thankfully, Django can capture errors and\nnotify you accordingly.\n\n:setting:`LOGGING`\n------------------\n\nReview your logging configuration before putting your website in production,\nand check that it works as expected as soon as you have received some traffic.\n\nSee :doc:`/topics/logging` for details on logging.\n\n:setting:`ADMINS` and :setting:`MANAGERS`\n-----------------------------------------\n\n:setting:`ADMINS` will be notified of 500 errors by email.\n\n:setting:`MANAGERS` will be notified of 404 errors.\n:setting:`IGNORABLE_404_URLS` can help filter out spurious reports.\n\nSee :doc:`/howto/error-reporting` for details on error reporting by email.\n\n.. admonition:: Error reporting by email doesn't scale very well\n\n    Consider using an error monitoring system such as Sentry_ before your\n    inbox is flooded by reports. Sentry can also aggregate logs.\n\n    .. _Sentry: https://docs.sentry.io/\n\nCustomize the default error views\n---------------------------------\n\nDjango includes default views and templates for several HTTP error codes. You\nmay want to override the default templates by creating the following templates\nin your root template directory: ``404.html``, ``500.html``, ``403.html``, and\n``400.html``. The :ref:`default error views <error-views>` that use these\ntemplates should suffice for 99% of Web applications, but you can\n:ref:`customize them <customizing-error-views>` as well.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":201,"nodeType":"TextFile","repoName":null,"name":"custom-lookups.txt","path":"docs/howto","text":"==============\nCustom Lookups\n==============\n\n.. currentmodule:: django.db.models\n\nDjango offers a wide variety of :ref:`built-in lookups <field-lookups>` for\nfiltering (for example, ``exact`` and ``icontains``). This documentation\nexplains how to write custom lookups and how to alter the working of existing\nlookups. For the API references of lookups, see the :doc:`/ref/models/lookups`.\n\nA lookup example\n================\n\nLet's start with a small custom lookup. We will write a custom lookup ``ne``\nwhich works opposite to ``exact``. ``Author.objects.filter(name__ne='Jack')``\nwill translate to the SQL:\n\n.. code-block:: sql\n\n  \"author\".\"name\" <> 'Jack'\n\nThis SQL is backend independent, so we don't need to worry about different\ndatabases.\n\nThere are two steps to making this work. Firstly we need to implement the\nlookup, then we need to tell Django about it::\n\n  from django.db.models import Lookup\n\n  class NotEqual(Lookup):\n      lookup_name = 'ne'\n\n      def as_sql(self, compiler, connection):\n          lhs, lhs_params = self.process_lhs(compiler, connection)\n          rhs, rhs_params = self.process_rhs(compiler, connection)\n          params = lhs_params + rhs_params\n          return '%s <> %s' % (lhs, rhs), params\n\nTo register the ``NotEqual`` lookup we will need to call ``register_lookup`` on\nthe field class we want the lookup to be available for. In this case, the lookup\nmakes sense on all ``Field`` subclasses, so we register it with ``Field``\ndirectly::\n\n  from django.db.models import Field\n  Field.register_lookup(NotEqual)\n\nLookup registration can also be done using a decorator pattern::\n\n    from django.db.models import Field\n\n    @Field.register_lookup\n    class NotEqualLookup(Lookup):\n        # ...\n\nWe can now use ``foo__ne`` for any field ``foo``. You will need to ensure that\nthis registration happens before you try to create any querysets using it. You\ncould place the implementation in a ``models.py`` file, or register the lookup\nin the ``ready()`` method of an ``AppConfig``.\n\nTaking a closer look at the implementation, the first required attribute is\n``lookup_name``. This allows the ORM to understand how to interpret ``name__ne``\nand use ``NotEqual`` to generate the SQL. By convention, these names are always\nlowercase strings containing only letters, but the only hard requirement is\nthat it must not contain the string ``__``.\n\nWe then need to define the ``as_sql`` method. This takes a ``SQLCompiler``\nobject, called ``compiler``,  and the active database connection.\n``SQLCompiler`` objects are not documented, but the only thing we need to know\nabout them is that they have a ``compile()`` method which returns a tuple\ncontaining an SQL string, and the parameters to be interpolated into that\nstring. In most cases, you don't need to use it directly and can pass it on to\n``process_lhs()`` and ``process_rhs()``.\n\nA ``Lookup`` works against two values, ``lhs`` and ``rhs``, standing for\nleft-hand side and right-hand side. The left-hand side is usually a field\nreference, but it can be anything implementing the :ref:`query expression API\n<query-expression>`. The right-hand is the value given by the user. In the\nexample ``Author.objects.filter(name__ne='Jack')``, the left-hand side is a\nreference to the ``name`` field of the ``Author`` model, and ``'Jack'`` is the\nright-hand side.\n\nWe call ``process_lhs`` and ``process_rhs`` to convert them into the values we\nneed for SQL using the ``compiler`` object described before. These methods\nreturn tuples containing some SQL and the parameters to be interpolated into\nthat SQL, just as we need to return from our ``as_sql`` method. In the above\nexample, ``process_lhs`` returns ``('\"author\".\"name\"', [])`` and\n``process_rhs`` returns ``('\"%s\"', ['Jack'])``. In this example there were no\nparameters for the left hand side, but this would depend on the object we have,\nso we still need to include them in the parameters we return.\n\nFinally we combine the parts into an SQL expression with ``<>``, and supply all\nthe parameters for the query. We then return a tuple containing the generated\nSQL string and the parameters.\n\nA transformer example\n=====================\n\nThe custom lookup above is great, but in some cases you may want to be able to\nchain lookups together. For example, let's suppose we are building an\napplication where we want to make use of the ``abs()`` operator.\nWe have an ``Experiment`` model which records a start value, end value, and the\nchange (start - end). We would like to find all experiments where the change\nwas equal to a certain amount (``Experiment.objects.filter(change__abs=27)``),\nor where it did not exceed a certain amount\n(``Experiment.objects.filter(change__abs__lt=27)``).\n\n.. note::\n    This example is somewhat contrived, but it nicely demonstrates the range of\n    functionality which is possible in a database backend independent manner,\n    and without duplicating functionality already in Django.\n\nWe will start by writing an ``AbsoluteValue`` transformer. This will use the SQL\nfunction ``ABS()`` to transform the value before comparison::\n\n  from django.db.models import Transform\n\n  class AbsoluteValue(Transform):\n      lookup_name = 'abs'\n      function = 'ABS'\n\nNext, let's register it for ``IntegerField``::\n\n  from django.db.models import IntegerField\n  IntegerField.register_lookup(AbsoluteValue)\n\nWe can now run the queries we had before.\n``Experiment.objects.filter(change__abs=27)`` will generate the following SQL:\n\n.. code-block:: sql\n\n    SELECT ... WHERE ABS(\"experiments\".\"change\") = 27\n\nBy using ``Transform`` instead of ``Lookup`` it means we are able to chain\nfurther lookups afterwards. So\n``Experiment.objects.filter(change__abs__lt=27)`` will generate the following\nSQL:\n\n.. code-block:: sql\n\n    SELECT ... WHERE ABS(\"experiments\".\"change\") < 27\n\nNote that in case there is no other lookup specified, Django interprets\n``change__abs=27`` as ``change__abs__exact=27``.\n\nThis also allows the result to be used in ``ORDER BY`` and ``DISTINCT ON``\nclauses. For example ``Experiment.objects.order_by('change__abs')`` generates:\n\n.. code-block:: sql\n\n    SELECT ... ORDER BY ABS(\"experiments\".\"change\") ASC\n\nAnd on databases that support distinct on fields (such as PostgreSQL),\n``Experiment.objects.distinct('change__abs')`` generates:\n\n.. code-block:: sql\n\n    SELECT ... DISTINCT ON ABS(\"experiments\".\"change\")\n\nWhen looking for which lookups are allowable after the ``Transform`` has been\napplied, Django uses the ``output_field`` attribute. We didn't need to specify\nthis here as it didn't change, but supposing we were applying ``AbsoluteValue``\nto some field which represents a more complex type (for example a point\nrelative to an origin, or a complex number) then we may have wanted to specify\nthat the transform returns a ``FloatField`` type for further lookups. This can\nbe done by adding an ``output_field`` attribute to the transform::\n\n    from django.db.models import FloatField, Transform\n\n    class AbsoluteValue(Transform):\n        lookup_name = 'abs'\n        function = 'ABS'\n\n        @property\n        def output_field(self):\n            return FloatField()\n\nThis ensures that further lookups like ``abs__lte`` behave as they would for\na ``FloatField``.\n\nWriting an efficient ``abs__lt`` lookup\n=======================================\n\nWhen using the above written ``abs`` lookup, the SQL produced will not use\nindexes efficiently in some cases. In particular, when we use\n``change__abs__lt=27``, this is equivalent to ``change__gt=-27`` AND\n``change__lt=27``. (For the ``lte`` case we could use the SQL ``BETWEEN``).\n\nSo we would like ``Experiment.objects.filter(change__abs__lt=27)`` to generate\nthe following SQL:\n\n.. code-block:: sql\n\n    SELECT .. WHERE \"experiments\".\"change\" < 27 AND \"experiments\".\"change\" > -27\n\nThe implementation is::\n\n  from django.db.models import Lookup\n\n  class AbsoluteValueLessThan(Lookup):\n      lookup_name = 'lt'\n\n      def as_sql(self, compiler, connection):\n          lhs, lhs_params = compiler.compile(self.lhs.lhs)\n          rhs, rhs_params = self.process_rhs(compiler, connection)\n          params = lhs_params + rhs_params + lhs_params + rhs_params\n          return '%s < %s AND %s > -%s' % (lhs, rhs, lhs, rhs), params\n\n  AbsoluteValue.register_lookup(AbsoluteValueLessThan)\n\nThere are a couple of notable things going on. First, ``AbsoluteValueLessThan``\nisn't calling ``process_lhs()``. Instead it skips the transformation of the\n``lhs`` done by ``AbsoluteValue`` and uses the original ``lhs``. That is, we\nwant to get ``\"experiments\".\"change\"`` not ``ABS(\"experiments\".\"change\")``.\nReferring directly to ``self.lhs.lhs`` is safe as ``AbsoluteValueLessThan``\ncan be accessed only from the ``AbsoluteValue`` lookup, that is the ``lhs``\nis always an instance of ``AbsoluteValue``.\n\nNotice also that  as both sides are used multiple times in the query the params\nneed to contain ``lhs_params`` and ``rhs_params`` multiple times.\n\nThe final query does the inversion (``27`` to ``-27``) directly in the\ndatabase. The reason for doing this is that if the ``self.rhs`` is something else\nthan a plain integer value (for example an ``F()`` reference) we can't do the\ntransformations in Python.\n\n.. note::\n    In fact, most lookups with ``__abs`` could be implemented as range queries\n    like this, and on most database backends it is likely to be more sensible to\n    do so as you can make use of the indexes. However with PostgreSQL you may\n    want to add an index on ``abs(change)`` which would allow these queries to\n    be very efficient.\n\nA bilateral transformer example\n===============================\n\nThe ``AbsoluteValue`` example we discussed previously is a transformation which\napplies to the left-hand side of the lookup. There may be some cases where you\nwant the transformation to be applied to both the left-hand side and the\nright-hand side. For instance, if you want to filter a queryset based on the\nequality of the left and right-hand side insensitively to some SQL function.\n\nLet's examine case-insensitive transformations here. This transformation isn't\nvery useful in practice as Django already comes with a bunch of built-in\ncase-insensitive lookups, but it will be a nice demonstration of bilateral\ntransformations in a database-agnostic way.\n\nWe define an ``UpperCase`` transformer which uses the SQL function ``UPPER()`` to\ntransform the values before comparison. We define\n:attr:`bilateral = True <django.db.models.Transform.bilateral>` to indicate that\nthis transformation should apply to both ``lhs`` and ``rhs``::\n\n  from django.db.models import Transform\n\n  class UpperCase(Transform):\n      lookup_name = 'upper'\n      function = 'UPPER'\n      bilateral = True\n\nNext, let's register it::\n\n  from django.db.models import CharField, TextField\n  CharField.register_lookup(UpperCase)\n  TextField.register_lookup(UpperCase)\n\nNow, the queryset ``Author.objects.filter(name__upper=\"doe\")`` will generate a case\ninsensitive query like this:\n\n.. code-block:: sql\n\n    SELECT ... WHERE UPPER(\"author\".\"name\") = UPPER('doe')\n\nWriting alternative implementations for existing lookups\n========================================================\n\nSometimes different database vendors require different SQL for the same\noperation. For this example we will rewrite a custom implementation for\nMySQL for the NotEqual operator. Instead of ``<>`` we will be using ``!=``\noperator. (Note that in reality almost all databases support both, including\nall the official databases supported by Django).\n\nWe can change the behavior on a specific backend by creating a subclass of\n``NotEqual`` with an ``as_mysql`` method::\n\n  class MySQLNotEqual(NotEqual):\n      def as_mysql(self, compiler, connection, **extra_context):\n          lhs, lhs_params = self.process_lhs(compiler, connection)\n          rhs, rhs_params = self.process_rhs(compiler, connection)\n          params = lhs_params + rhs_params\n          return '%s != %s' % (lhs, rhs), params\n\n  Field.register_lookup(MySQLNotEqual)\n\nWe can then register it with ``Field``. It takes the place of the original\n``NotEqual`` class as it has the same ``lookup_name``.\n\nWhen compiling a query, Django first looks for ``as_%s % connection.vendor``\nmethods, and then falls back to ``as_sql``. The vendor names for the in-built\nbackends are ``sqlite``, ``postgresql``, ``oracle`` and ``mysql``.\n\nHow Django determines the lookups and transforms which are used\n===============================================================\n\nIn some cases you may wish to dynamically change which ``Transform`` or\n``Lookup`` is returned based on the name passed in, rather than fixing it. As\nan example, you could have a field which stores coordinates or an arbitrary\ndimension, and wish to allow a syntax like ``.filter(coords__x7=4)`` to return\nthe objects where the 7th coordinate has value 4. In order to do this, you\nwould override ``get_lookup`` with something like::\n\n    class CoordinatesField(Field):\n        def get_lookup(self, lookup_name):\n            if lookup_name.startswith('x'):\n                try:\n                    dimension = int(lookup_name[1:])\n                except ValueError:\n                    pass\n                else:\n                    return get_coordinate_lookup(dimension)\n            return super().get_lookup(lookup_name)\n\nYou would then define ``get_coordinate_lookup`` appropriately to return a\n``Lookup`` subclass which handles the relevant value of ``dimension``.\n\nThere is a similarly named method called ``get_transform()``. ``get_lookup()``\nshould always return a ``Lookup`` subclass, and ``get_transform()`` a\n``Transform`` subclass. It is important to remember that ``Transform``\nobjects can be further filtered on, and ``Lookup`` objects cannot.\n\nWhen filtering, if there is only one lookup name remaining to be resolved, we\nwill look for a ``Lookup``. If there are multiple names, it will look for a\n``Transform``. In the situation where there is only one name and a ``Lookup``\nis not found, we look for a ``Transform`` and then the ``exact`` lookup on that\n``Transform``. All call sequences always end with a ``Lookup``. To clarify:\n\n- ``.filter(myfield__mylookup)`` will call ``myfield.get_lookup('mylookup')``.\n- ``.filter(myfield__mytransform__mylookup)`` will call\n  ``myfield.get_transform('mytransform')``, and then\n  ``mytransform.get_lookup('mylookup')``.\n- ``.filter(myfield__mytransform)`` will first call\n  ``myfield.get_lookup('mytransform')``, which will fail, so it will fall back\n  to calling ``myfield.get_transform('mytransform')`` and then\n  ``mytransform.get_lookup('exact')``.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":202,"nodeType":"Package","repoName":null,"name":"docs/intro","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":203,"nodeType":"TextFile","repoName":null,"name":"overview.txt","path":"docs/intro","text":"==================\nDjango at a glance\n==================\n\nBecause Django was developed in a fast-paced newsroom environment, it was\ndesigned to make common Web-development tasks fast and easy. Here's an informal\noverview of how to write a database-driven Web app with Django.\n\nThe goal of this document is to give you enough technical specifics to\nunderstand how Django works, but this isn't intended to be a tutorial or\nreference -- but we've got both! When you're ready to start a project, you can\n:doc:`start with the tutorial </intro/tutorial01>` or :doc:`dive right into more\ndetailed documentation </topics/index>`.\n\nDesign your model\n=================\n\nAlthough you can use Django without a database, it comes with an\n`object-relational mapper`_ in which you describe your database layout in Python\ncode.\n\n.. _object-relational mapper: https://en.wikipedia.org/wiki/Object-relational_mapping\n\nThe :doc:`data-model syntax </topics/db/models>` offers many rich ways of\nrepresenting your models -- so far, it's been solving many years' worth of\ndatabase-schema problems. Here's a quick example:\n\n.. code-block:: python\n    :caption: mysite/news/models.py\n\n    from django.db import models\n\n    class Reporter(models.Model):\n        full_name = models.CharField(max_length=70)\n\n        def __str__(self):\n            return self.full_name\n\n    class Article(models.Model):\n        pub_date = models.DateField()\n        headline = models.CharField(max_length=200)\n        content = models.TextField()\n        reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)\n\n        def __str__(self):\n            return self.headline\n\nInstall it\n==========\n\nNext, run the Django command-line utilities to create the database tables\nautomatically:\n\n.. console::\n\n    $ python manage.py makemigrations\n    $ python manage.py migrate\n\nThe :djadmin:`makemigrations` command looks at all your available models and\ncreates migrations for whichever tables don't already exist. :djadmin:`migrate`\nruns the migrations and creates tables in your database, as well as optionally\nproviding :doc:`much richer schema control </topics/migrations>`.\n\nEnjoy the free API\n==================\n\nWith that, you've got a free, and rich, :doc:`Python API </topics/db/queries>`\nto access your data. The API is created on the fly, no code generation\nnecessary::\n\n    # Import the models we created from our \"news\" app\n    >>> from news.models import Article, Reporter\n\n    # No reporters are in the system yet.\n    >>> Reporter.objects.all()\n    <QuerySet []>\n\n    # Create a new Reporter.\n    >>> r = Reporter(full_name='John Smith')\n\n    # Save the object into the database. You have to call save() explicitly.\n    >>> r.save()\n\n    # Now it has an ID.\n    >>> r.id\n    1\n\n    # Now the new reporter is in the database.\n    >>> Reporter.objects.all()\n    <QuerySet [<Reporter: John Smith>]>\n\n    # Fields are represented as attributes on the Python object.\n    >>> r.full_name\n    'John Smith'\n\n    # Django provides a rich database lookup API.\n    >>> Reporter.objects.get(id=1)\n    <Reporter: John Smith>\n    >>> Reporter.objects.get(full_name__startswith='John')\n    <Reporter: John Smith>\n    >>> Reporter.objects.get(full_name__contains='mith')\n    <Reporter: John Smith>\n    >>> Reporter.objects.get(id=2)\n    Traceback (most recent call last):\n        ...\n    DoesNotExist: Reporter matching query does not exist.\n\n    # Create an article.\n    >>> from datetime import date\n    >>> a = Article(pub_date=date.today(), headline='Django is cool',\n    ...     content='Yeah.', reporter=r)\n    >>> a.save()\n\n    # Now the article is in the database.\n    >>> Article.objects.all()\n    <QuerySet [<Article: Django is cool>]>\n\n    # Article objects get API access to related Reporter objects.\n    >>> r = a.reporter\n    >>> r.full_name\n    'John Smith'\n\n    # And vice versa: Reporter objects get API access to Article objects.\n    >>> r.article_set.all()\n    <QuerySet [<Article: Django is cool>]>\n\n    # The API follows relationships as far as you need, performing efficient\n    # JOINs for you behind the scenes.\n    # This finds all articles by a reporter whose name starts with \"John\".\n    >>> Article.objects.filter(reporter__full_name__startswith='John')\n    <QuerySet [<Article: Django is cool>]>\n\n    # Change an object by altering its attributes and calling save().\n    >>> r.full_name = 'Billy Goat'\n    >>> r.save()\n\n    # Delete an object with delete().\n    >>> r.delete()\n\nA dynamic admin interface: it's not just scaffolding -- it's the whole house\n============================================================================\n\nOnce your models are defined, Django can automatically create a professional,\nproduction ready :doc:`administrative interface </ref/contrib/admin/index>` --\na website that lets authenticated users add, change and delete objects. The\nonly step required is to register your model in the admin site:\n\n.. code-block:: python\n    :caption: mysite/news/models.py\n\n    from django.db import models\n\n    class Article(models.Model):\n        pub_date = models.DateField()\n        headline = models.CharField(max_length=200)\n        content = models.TextField()\n        reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)\n\n.. code-block:: python\n    :caption: mysite/news/admin.py\n\n    from django.contrib import admin\n\n    from . import models\n\n    admin.site.register(models.Article)\n\nThe philosophy here is that your site is edited by a staff, or a client, or\nmaybe just you -- and you don't want to have to deal with creating backend\ninterfaces only to manage content.\n\nOne typical workflow in creating Django apps is to create models and get the\nadmin sites up and running as fast as possible, so your staff (or clients) can\nstart populating data. Then, develop the way data is presented to the public.\n\nDesign your URLs\n================\n\nA clean, elegant URL scheme is an important detail in a high-quality Web\napplication. Django encourages beautiful URL design and doesn't put any cruft\nin URLs, like ``.php`` or ``.asp``.\n\nTo design URLs for an app, you create a Python module called a :doc:`URLconf\n</topics/http/urls>`. A table of contents for your app, it contains a mapping\nbetween URL patterns and Python callback functions. URLconfs also serve to\ndecouple URLs from Python code.\n\nHere's what a URLconf might look like for the ``Reporter``/``Article``\nexample above:\n\n.. code-block:: python\n    :caption: mysite/news/urls.py\n\n    from django.urls import path\n\n    from . import views\n\n    urlpatterns = [\n        path('articles/<int:year>/', views.year_archive),\n        path('articles/<int:year>/<int:month>/', views.month_archive),\n        path('articles/<int:year>/<int:month>/<int:pk>/', views.article_detail),\n    ]\n\nThe code above maps URL paths to Python callback functions (\"views\"). The path\nstrings use parameter tags to \"capture\" values from the URLs. When a user\nrequests a page, Django runs through each path, in order, and stops at the\nfirst one that matches the requested URL. (If none of them matches, Django\ncalls a special-case 404 view.) This is blazingly fast, because the paths are\ncompiled into regular expressions at load time.\n\nOnce one of the URL patterns matches, Django calls the given view, which is a\nPython function. Each view gets passed a request object -- which contains\nrequest metadata -- and the values captured in the pattern.\n\nFor example, if a user requested the URL \"/articles/2005/05/39323/\", Django\nwould call the function ``news.views.article_detail(request,\nyear=2005, month=5, pk=39323)``.\n\nWrite your views\n================\n\nEach view is responsible for doing one of two things: Returning an\n:class:`~django.http.HttpResponse` object containing the content for the\nrequested page, or raising an exception such as :class:`~django.http.Http404`.\nThe rest is up to you.\n\nGenerally, a view retrieves data according to the parameters, loads a template\nand renders the template with the retrieved data. Here's an example view for\n``year_archive`` from above:\n\n.. code-block:: python\n    :caption: mysite/news/views.py\n\n    from django.shortcuts import render\n\n    from .models import Article\n\n    def year_archive(request, year):\n        a_list = Article.objects.filter(pub_date__year=year)\n        context = {'year': year, 'article_list': a_list}\n        return render(request, 'news/year_archive.html', context)\n\nThis example uses Django's :doc:`template system </topics/templates>`, which has\nseveral powerful features but strives to stay simple enough for non-programmers\nto use.\n\nDesign your templates\n=====================\n\nThe code above loads the ``news/year_archive.html`` template.\n\nDjango has a template search path, which allows you to minimize redundancy among\ntemplates. In your Django settings, you specify a list of directories to check\nfor templates with :setting:`DIRS <TEMPLATES-DIRS>`. If a template doesn't exist\nin the first directory, it checks the second, and so on.\n\nLet's say the ``news/year_archive.html`` template was found. Here's what that\nmight look like:\n\n.. code-block:: html+django\n    :caption: mysite/news/templates/news/year_archive.html\n\n    {% extends \"base.html\" %}\n\n    {% block title %}Articles for {{ year }}{% endblock %}\n\n    {% block content %}\n    <h1>Articles for {{ year }}</h1>\n\n    {% for article in article_list %}\n        <p>{{ article.headline }}</p>\n        <p>By {{ article.reporter.full_name }}</p>\n        <p>Published {{ article.pub_date|date:\"F j, Y\" }}</p>\n    {% endfor %}\n    {% endblock %}\n\nVariables are surrounded by double-curly braces. ``{{ article.headline }}``\nmeans \"Output the value of the article's headline attribute.\" But dots aren't\nused only for attribute lookup. They also can do dictionary-key lookup, index\nlookup and function calls.\n\nNote ``{{ article.pub_date|date:\"F j, Y\" }}`` uses a Unix-style \"pipe\" (the \"|\"\ncharacter). This is called a template filter, and it's a way to filter the value\nof a variable. In this case, the date filter formats a Python datetime object in\nthe given format (as found in PHP's date function).\n\nYou can chain together as many filters as you'd like. You can write :ref:`custom\ntemplate filters <howto-writing-custom-template-filters>`. You can write\n:doc:`custom template tags </howto/custom-template-tags>`, which run custom\nPython code behind the scenes.\n\nFinally, Django uses the concept of \"template inheritance\". That's what the\n``{% extends \"base.html\" %}`` does. It means \"First load the template called\n'base', which has defined a bunch of blocks, and fill the blocks with the\nfollowing blocks.\" In short, that lets you dramatically cut down on redundancy\nin templates: each template has to define only what's unique to that template.\n\nHere's what the \"base.html\" template, including the use of :doc:`static files\n</howto/static-files/index>`, might look like:\n\n.. code-block:: html+django\n    :caption: mysite/templates/base.html\n\n    {% load static %}\n    <html>\n    <head>\n        <title>{% block title %}{% endblock %}</title>\n    </head>\n    <body>\n        <img src=\"{% static \"images/sitelogo.png\" %}\" alt=\"Logo\">\n        {% block content %}{% endblock %}\n    </body>\n    </html>\n\nSimplistically, it defines the look-and-feel of the site (with the site's logo),\nand provides \"holes\" for child templates to fill. This means that a site redesign\ncan be done by changing a single file -- the base template.\n\nIt also lets you create multiple versions of a site, with different base\ntemplates, while reusing child templates. Django's creators have used this\ntechnique to create strikingly different mobile versions of sites by only\ncreating a new base template.\n\nNote that you don't have to use Django's template system if you prefer another\nsystem. While Django's template system is particularly well-integrated with\nDjango's model layer, nothing forces you to use it. For that matter, you don't\nhave to use Django's database API, either. You can use another database\nabstraction layer, you can read XML files, you can read files off disk, or\nanything you want. Each piece of Django -- models, views, templates -- is\ndecoupled from the next.\n\nThis is just the surface\n========================\n\nThis has been only a quick overview of Django's functionality. Some more useful\nfeatures:\n\n* A :doc:`caching framework </topics/cache>` that integrates with memcached\n  or other backends.\n\n* A :doc:`syndication framework </ref/contrib/syndication>` that lets you\n  create RSS and Atom feeds by writing a small Python class.\n\n* More attractive automatically-generated admin features -- this overview\n  barely scratched the surface.\n\nThe next steps are for you to `download Django`_, read :doc:`the tutorial\n</intro/tutorial01>` and join `the community`_. Thanks for your interest!\n\n.. _download Django: https://www.djangoproject.com/download/\n.. _the community: https://www.djangoproject.com/community/\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":204,"nodeType":"TextFile","repoName":null,"name":"install.txt","path":"docs/intro","text":"===================\nQuick install guide\n===================\n\nBefore you can use Django, you'll need to get it installed. We have a\n:doc:`complete installation guide </topics/install>` that covers all the\npossibilities; this guide will guide you to a minimal installation that'll work\nwhile you walk through the introduction.\n\nInstall Python\n==============\n\nBeing a Python Web framework, Django requires Python. See\n:ref:`faq-python-version-support` for details. Python includes a lightweight\ndatabase called SQLite_ so you won't need to set up a database just yet.\n\n.. _sqlite: https://sqlite.org/\n\nGet the latest version of Python at https://www.python.org/downloads/ or with\nyour operating system's package manager.\n\nYou can verify that Python is installed by typing ``python`` from your shell;\nyou should see something like::\n\n    Python 3.x.y\n    [GCC 4.x] on linux\n    Type \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n    >>>\n\nSet up a database\n=================\n\nThis step is only necessary if you'd like to work with a \"large\" database engine\nlike PostgreSQL, MariaDB, MySQL, or Oracle. To install such a database, consult\nthe :ref:`database installation information <database-installation>`.\n\nInstall Django\n==============\n\nYou've got three options to install Django:\n\n* :ref:`Install an official release <installing-official-release>`. This\n  is the best approach for most users.\n\n* Install a version of Django :ref:`provided by your operating system\n  distribution <installing-distribution-package>`.\n\n* :ref:`Install the latest development version\n  <installing-development-version>`. This option is for enthusiasts who want\n  the latest-and-greatest features and aren't afraid of running brand new code.\n  You might encounter new bugs in the development version, but reporting them\n  helps the development of Django. Also, releases of third-party packages are\n  less likely to be compatible with the development version than with the\n  latest stable release.\n\n.. admonition:: Always refer to the documentation that corresponds to the\n    version of Django you're using!\n\n    If you do either of the first two steps, keep an eye out for parts of the\n    documentation marked **new in development version**. That phrase flags\n    features that are only available in development versions of Django, and\n    they likely won't work with an official release.\n\n\nVerifying\n=========\n\nTo verify that Django can be seen by Python, type ``python`` from your shell.\nThen at the Python prompt, try to import Django:\n\n.. parsed-literal::\n\n    >>> import django\n    >>> print(django.get_version())\n    |version|\n\nYou may have another version of Django installed.\n\nThat's it!\n==========\n\nThat's it -- you can now :doc:`move onto the tutorial </intro/tutorial01>`.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":205,"nodeType":"TextFile","repoName":null,"name":"custom-template-tags.txt","path":"docs/howto","text":"================================\nCustom template tags and filters\n================================\n\nDjango's template language comes with a wide variety of :doc:`built-in\ntags and filters </ref/templates/builtins>` designed to address the\npresentation logic needs of your application. Nevertheless, you may\nfind yourself needing functionality that is not covered by the core\nset of template primitives. You can extend the template engine by\ndefining custom tags and filters using Python, and then make them\navailable to your templates using the :ttag:`{% load %}<load>` tag.\n\nCode layout\n===========\n\nThe most common place to specify custom template tags and filters is inside\na Django app. If they relate to an existing app, it makes sense to bundle them\nthere; otherwise, they can be added to a new app. When a Django app is added\nto :setting:`INSTALLED_APPS`, any tags it defines in the conventional location\ndescribed below are automatically made available to load within templates.\n\nThe app should contain a ``templatetags`` directory, at the same level as\n``models.py``, ``views.py``, etc. If this doesn't already exist, create it -\ndon't forget the ``__init__.py`` file to ensure the directory is treated as a\nPython package.\n\n.. admonition:: Development server won't automatically restart\n\n    After adding the ``templatetags``  module, you will need to restart your\n    server before you can use the tags or filters in templates.\n\nYour custom tags and filters will live in a module inside the ``templatetags``\ndirectory. The name of the module file is the name you'll use to load the tags\nlater, so be careful to pick a name that won't clash with custom tags and\nfilters in another app.\n\nFor example, if your custom tags/filters are in a file called\n``poll_extras.py``, your app layout might look like this::\n\n    polls/\n        __init__.py\n        models.py\n        templatetags/\n            __init__.py\n            poll_extras.py\n        views.py\n\nAnd in your template you would use the following:\n\n.. code-block:: html+django\n\n    {% load poll_extras %}\n\nThe app that contains the custom tags must be in :setting:`INSTALLED_APPS` in\norder for the :ttag:`{% load %}<load>` tag to work. This is a security feature:\nIt allows you to host Python code for many template libraries on a single host\nmachine without enabling access to all of them for every Django installation.\n\nThere's no limit on how many modules you put in the ``templatetags`` package.\nJust keep in mind that a :ttag:`{% load %}<load>` statement will load\ntags/filters for the given Python module name, not the name of the app.\n\nTo be a valid tag library, the module must contain a module-level variable\nnamed ``register`` that is a ``template.Library`` instance, in which all the\ntags and filters are registered. So, near the top of your module, put the\nfollowing::\n\n    from django import template\n\n    register = template.Library()\n\nAlternatively, template tag modules can be registered through the\n``'libraries'`` argument to\n:class:`~django.template.backends.django.DjangoTemplates`. This is useful if\nyou want to use a different label from the template tag module name when\nloading template tags. It also enables you to register tags without installing\nan application.\n\n.. admonition:: Behind the scenes\n\n    For a ton of examples, read the source code for Django's default filters\n    and tags. They're in ``django/template/defaultfilters.py`` and\n    ``django/template/defaulttags.py``, respectively.\n\n    For more information on the :ttag:`load` tag, read its documentation.\n\n.. _howto-writing-custom-template-filters:\n\nWriting custom template filters\n===============================\n\nCustom filters are Python functions that take one or two arguments:\n\n* The value of the variable (input) -- not necessarily a string.\n* The value of the argument -- this can have a default value, or be left\n  out altogether.\n\nFor example, in the filter ``{{ var|foo:\"bar\" }}``, the filter ``foo`` would be\npassed the variable ``var`` and the argument ``\"bar\"``.\n\nSince the template language doesn't provide exception handling, any exception\nraised from a template filter will be exposed as a server error. Thus, filter\nfunctions should avoid raising exceptions if there is a reasonable fallback\nvalue to return. In case of input that represents a clear bug in a template,\nraising an exception may still be better than silent failure which hides the\nbug.\n\nHere's an example filter definition::\n\n    def cut(value, arg):\n        \"\"\"Removes all values of arg from the given string\"\"\"\n        return value.replace(arg, '')\n\nAnd here's an example of how that filter would be used:\n\n.. code-block:: html+django\n\n    {{ somevariable|cut:\"0\" }}\n\nMost filters don't take arguments. In this case, leave the argument out of your\nfunction::\n\n    def lower(value): # Only one argument.\n        \"\"\"Converts a string into all lowercase\"\"\"\n        return value.lower()\n\nRegistering custom filters\n--------------------------\n\n.. method:: django.template.Library.filter()\n\nOnce you've written your filter definition, you need to register it with\nyour ``Library`` instance, to make it available to Django's template language::\n\n    register.filter('cut', cut)\n    register.filter('lower', lower)\n\nThe ``Library.filter()`` method takes two arguments:\n\n1. The name of the filter -- a string.\n2. The compilation function -- a Python function (not the name of the\n   function as a string).\n\nYou can use ``register.filter()`` as a decorator instead::\n\n    @register.filter(name='cut')\n    def cut(value, arg):\n        return value.replace(arg, '')\n\n    @register.filter\n    def lower(value):\n        return value.lower()\n\nIf you leave off the ``name`` argument, as in the second example above, Django\nwill use the function's name as the filter name.\n\nFinally, ``register.filter()`` also accepts three keyword arguments,\n``is_safe``, ``needs_autoescape``, and ``expects_localtime``. These arguments\nare described in :ref:`filters and auto-escaping <filters-auto-escaping>` and\n:ref:`filters and time zones <filters-timezones>` below.\n\nTemplate filters that expect strings\n------------------------------------\n\n.. method:: django.template.defaultfilters.stringfilter()\n\nIf you're writing a template filter that only expects a string as the first\nargument, you should use the decorator ``stringfilter``. This will\nconvert an object to its string value before being passed to your function::\n\n    from django import template\n    from django.template.defaultfilters import stringfilter\n\n    register = template.Library()\n\n    @register.filter\n    @stringfilter\n    def lower(value):\n        return value.lower()\n\nThis way, you'll be able to pass, say, an integer to this filter, and it\nwon't cause an ``AttributeError`` (because integers don't have ``lower()``\nmethods).\n\n.. _filters-auto-escaping:\n\nFilters and auto-escaping\n-------------------------\n\nWhen writing a custom filter, give some thought to how the filter will interact\nwith Django's auto-escaping behavior. Note that two types of strings can be\npassed around inside the template code:\n\n* **Raw strings** are the native Python strings. On output, they're escaped if\n  auto-escaping is in effect and presented unchanged, otherwise.\n\n* **Safe strings** are strings that have been marked safe from further\n  escaping at output time. Any necessary escaping has already been done.\n  They're commonly used for output that contains raw HTML that is intended\n  to be interpreted as-is on the client side.\n\n  Internally, these strings are of type\n  :class:`~django.utils.safestring.SafeString`. You can test for them\n  using code like::\n\n      from django.utils.safestring import SafeString\n\n      if isinstance(value, SafeString):\n          # Do something with the \"safe\" string.\n          ...\n\nTemplate filter code falls into one of two situations:\n\n1. Your filter does not introduce any HTML-unsafe characters (``<``, ``>``,\n   ``'``, ``\"`` or ``&``) into the result that were not already present. In\n   this case, you can let Django take care of all the auto-escaping\n   handling for you. All you need to do is set the ``is_safe`` flag to ``True``\n   when you register your filter function, like so::\n\n       @register.filter(is_safe=True)\n       def myfilter(value):\n           return value\n\n   This flag tells Django that if a \"safe\" string is passed into your\n   filter, the result will still be \"safe\" and if a non-safe string is\n   passed in, Django will automatically escape it, if necessary.\n\n   You can think of this as meaning \"this filter is safe -- it doesn't\n   introduce any possibility of unsafe HTML.\"\n\n   The reason ``is_safe`` is necessary is because there are plenty of\n   normal string operations that will turn a ``SafeData`` object back into\n   a normal ``str`` object and, rather than try to catch them all, which would\n   be very difficult, Django repairs the damage after the filter has completed.\n\n   For example, suppose you have a filter that adds the string ``xx`` to\n   the end of any input. Since this introduces no dangerous HTML characters\n   to the result (aside from any that were already present), you should\n   mark your filter with ``is_safe``::\n\n       @register.filter(is_safe=True)\n       def add_xx(value):\n           return '%sxx' % value\n\n   When this filter is used in a template where auto-escaping is enabled,\n   Django will escape the output whenever the input is not already marked\n   as \"safe\".\n\n   By default, ``is_safe`` is ``False``, and you can omit it from any filters\n   where it isn't required.\n\n   Be careful when deciding if your filter really does leave safe strings\n   as safe. If you're *removing* characters, you might inadvertently leave\n   unbalanced HTML tags or entities in the result. For example, removing a\n   ``>`` from the input might turn ``<a>`` into ``<a``, which would need to\n   be escaped on output to avoid causing problems. Similarly, removing a\n   semicolon (``;``) can turn ``&amp;`` into ``&amp``, which is no longer a\n   valid entity and thus needs further escaping. Most cases won't be nearly\n   this tricky, but keep an eye out for any problems like that when\n   reviewing your code.\n\n   Marking a filter ``is_safe`` will coerce the filter's return value to\n   a string.  If your filter should return a boolean or other non-string\n   value, marking it ``is_safe`` will probably have unintended\n   consequences (such as converting a boolean False to the string\n   'False').\n\n2. Alternatively, your filter code can manually take care of any necessary\n   escaping. This is necessary when you're introducing new HTML markup into\n   the result. You want to mark the output as safe from further\n   escaping so that your HTML markup isn't escaped further, so you'll need\n   to handle the input yourself.\n\n   To mark the output as a safe string, use\n   :func:`django.utils.safestring.mark_safe`.\n\n   Be careful, though. You need to do more than just mark the output as\n   safe. You need to ensure it really *is* safe, and what you do depends on\n   whether auto-escaping is in effect. The idea is to write filters that\n   can operate in templates where auto-escaping is either on or off in\n   order to make things easier for your template authors.\n\n   In order for your filter to know the current auto-escaping state, set the\n   ``needs_autoescape`` flag to ``True`` when you register your filter function.\n   (If you don't specify this flag, it defaults to ``False``). This flag tells\n   Django that your filter function wants to be passed an extra keyword\n   argument, called ``autoescape``, that is ``True`` if auto-escaping is in\n   effect and ``False`` otherwise. It is recommended to set the default of the\n   ``autoescape`` parameter to ``True``, so that if you call the function\n   from Python code it will have escaping enabled by default.\n\n   For example, let's write a filter that emphasizes the first character of\n   a string::\n\n      from django import template\n      from django.utils.html import conditional_escape\n      from django.utils.safestring import mark_safe\n\n      register = template.Library()\n\n      @register.filter(needs_autoescape=True)\n      def initial_letter_filter(text, autoescape=True):\n          first, other = text[0], text[1:]\n          if autoescape:\n              esc = conditional_escape\n          else:\n              esc = lambda x: x\n          result = '<strong>%s</strong>%s' % (esc(first), esc(other))\n          return mark_safe(result)\n\n   The ``needs_autoescape`` flag and the ``autoescape`` keyword argument mean\n   that our function will know whether automatic escaping is in effect when the\n   filter is called. We use ``autoescape`` to decide whether the input data\n   needs to be passed through ``django.utils.html.conditional_escape`` or not.\n   (In the latter case, we use the identity function as the \"escape\" function.)\n   The ``conditional_escape()`` function is like ``escape()`` except it only\n   escapes input that is **not** a ``SafeData`` instance. If a ``SafeData``\n   instance is passed to ``conditional_escape()``, the data is returned\n   unchanged.\n\n   Finally, in the above example, we remember to mark the result as safe\n   so that our HTML is inserted directly into the template without further\n   escaping.\n\n   There's no need to worry about the ``is_safe`` flag in this case\n   (although including it wouldn't hurt anything). Whenever you manually\n   handle the auto-escaping issues and return a safe string, the\n   ``is_safe`` flag won't change anything either way.\n\n.. warning:: Avoiding XSS vulnerabilities when reusing built-in filters\n\n    Django's built-in filters have ``autoescape=True`` by default in order to\n    get the proper autoescaping behavior and avoid a cross-site script\n    vulnerability.\n\n    In older versions of Django, be careful when reusing Django's built-in\n    filters as ``autoescape`` defaults to ``None``. You'll need to pass\n    ``autoescape=True`` to get autoescaping.\n\n    For example, if you wanted to write a custom filter called\n    ``urlize_and_linebreaks`` that combined the :tfilter:`urlize` and\n    :tfilter:`linebreaksbr` filters, the filter would look like::\n\n        from django.template.defaultfilters import linebreaksbr, urlize\n\n        @register.filter(needs_autoescape=True)\n        def urlize_and_linebreaks(text, autoescape=True):\n            return linebreaksbr(\n                urlize(text, autoescape=autoescape),\n                autoescape=autoescape\n            )\n\n    Then:\n\n    .. code-block:: html+django\n\n        {{ comment|urlize_and_linebreaks }}\n\n    would be equivalent to:\n\n    .. code-block:: html+django\n\n        {{ comment|urlize|linebreaksbr }}\n\n.. _filters-timezones:\n\nFilters and time zones\n----------------------\n\nIf you write a custom filter that operates on :class:`~datetime.datetime`\nobjects, you'll usually register it with the ``expects_localtime`` flag set to\n``True``::\n\n    @register.filter(expects_localtime=True)\n    def businesshours(value):\n        try:\n            return 9 <= value.hour < 17\n        except AttributeError:\n            return ''\n\nWhen this flag is set, if the first argument to your filter is a time zone\naware datetime, Django will convert it to the current time zone before passing\nit to your filter when appropriate, according to :ref:`rules for time zones\nconversions in templates <time-zones-in-templates>`.\n\n.. _howto-writing-custom-template-tags:\n\nWriting custom template tags\n============================\n\nTags are more complex than filters, because tags can do anything. Django\nprovides a number of shortcuts that make writing most types of tags easier.\nFirst we'll explore those shortcuts, then explain how to write a tag from\nscratch for those cases when the shortcuts aren't powerful enough.\n\n.. _howto-custom-template-tags-simple-tags:\n\nSimple tags\n-----------\n\n.. method:: django.template.Library.simple_tag()\n\nMany template tags take a number of arguments -- strings or template variables\n-- and return a result after doing some processing based solely on\nthe input arguments and some external information. For example, a\n``current_time`` tag might accept a format string and return the time as a\nstring formatted accordingly.\n\nTo ease the creation of these types of tags, Django provides a helper function,\n``simple_tag``. This function, which is a method of\n``django.template.Library``, takes a function that accepts any number of\narguments, wraps it in a ``render`` function and the other necessary bits\nmentioned above and registers it with the template system.\n\nOur ``current_time`` function could thus be written like this::\n\n    import datetime\n    from django import template\n\n    register = template.Library()\n\n    @register.simple_tag\n    def current_time(format_string):\n        return datetime.datetime.now().strftime(format_string)\n\nA few things to note about the ``simple_tag`` helper function:\n\n* Checking for the required number of arguments, etc., has already been\n  done by the time our function is called, so we don't need to do that.\n* The quotes around the argument (if any) have already been stripped away,\n  so we receive a plain string.\n* If the argument was a template variable, our function is passed the\n  current value of the variable, not the variable itself.\n\nUnlike other tag utilities, ``simple_tag`` passes its output through\n:func:`~django.utils.html.conditional_escape` if the template context is in\nautoescape mode, to ensure correct HTML and protect you from XSS\nvulnerabilities.\n\nIf additional escaping is not desired, you will need to use\n:func:`~django.utils.safestring.mark_safe` if you are absolutely sure that your\ncode does not contain XSS vulnerabilities. For building small HTML snippets,\nuse of :func:`~django.utils.html.format_html` instead of ``mark_safe()`` is\nstrongly recommended.\n\nIf your template tag needs to access the current context, you can use the\n``takes_context`` argument when registering your tag::\n\n    @register.simple_tag(takes_context=True)\n    def current_time(context, format_string):\n        timezone = context['timezone']\n        return your_get_current_time_method(timezone, format_string)\n\nNote that the first argument *must* be called ``context``.\n\nFor more information on how the ``takes_context`` option works, see the section\non :ref:`inclusion tags<howto-custom-template-tags-inclusion-tags>`.\n\nIf you need to rename your tag, you can provide a custom name for it::\n\n    register.simple_tag(lambda x: x - 1, name='minusone')\n\n    @register.simple_tag(name='minustwo')\n    def some_function(value):\n        return value - 2\n\n``simple_tag`` functions may accept any number of positional or keyword\narguments. For example::\n\n    @register.simple_tag\n    def my_tag(a, b, *args, **kwargs):\n        warning = kwargs['warning']\n        profile = kwargs['profile']\n        ...\n        return ...\n\nThen in the template any number of arguments, separated by spaces, may be\npassed to the template tag. Like in Python, the values for keyword arguments\nare set using the equal sign (\"``=``\") and must be provided after the\npositional arguments. For example:\n\n.. code-block:: html+django\n\n    {% my_tag 123 \"abcd\" book.title warning=message|lower profile=user.profile %}\n\nIt's possible to store the tag results in a template variable rather than\ndirectly outputting it. This is done by using the ``as`` argument followed by\nthe variable name. Doing so enables you to output the content yourself where\nyou see fit:\n\n.. code-block:: html+django\n\n    {% current_time \"%Y-%m-%d %I:%M %p\" as the_time %}\n    <p>The time is {{ the_time }}.</p>\n\n.. _howto-custom-template-tags-inclusion-tags:\n\nInclusion tags\n--------------\n\n.. method:: django.template.Library.inclusion_tag()\n\nAnother common type of template tag is the type that displays some data by\nrendering *another* template. For example, Django's admin interface uses custom\ntemplate tags to display the buttons along the bottom of the \"add/change\" form\npages. Those buttons always look the same, but the link targets change\ndepending on the object being edited -- so they're a perfect case for using a\nsmall template that is filled with details from the current object. (In the\nadmin's case, this is the ``submit_row`` tag.)\n\nThese sorts of tags are called \"inclusion tags\".\n\nWriting inclusion tags is probably best demonstrated by example. Let's write a\ntag that outputs a list of choices for a given ``Poll`` object, such as was\ncreated in the :ref:`tutorials <creating-models>`. We'll use the tag like this:\n\n.. code-block:: html+django\n\n    {% show_results poll %}\n\n...and the output will be something like this:\n\n.. code-block:: html\n\n    <ul>\n      <li>First choice</li>\n      <li>Second choice</li>\n      <li>Third choice</li>\n    </ul>\n\nFirst, define the function that takes the argument and produces a dictionary of\ndata for the result. The important point here is we only need to return a\ndictionary, not anything more complex. This will be used as a template context\nfor the template fragment. Example::\n\n    def show_results(poll):\n        choices = poll.choice_set.all()\n        return {'choices': choices}\n\nNext, create the template used to render the tag's output. This template is a\nfixed feature of the tag: the tag writer specifies it, not the template\ndesigner. Following our example, the template is very short:\n\n.. code-block:: html+django\n\n    <ul>\n    {% for choice in choices %}\n        <li> {{ choice }} </li>\n    {% endfor %}\n    </ul>\n\nNow, create and register the inclusion tag by calling the ``inclusion_tag()``\nmethod on a ``Library`` object. Following our example, if the above template is\nin a file called ``results.html`` in a directory that's searched by the\ntemplate loader, we'd register the tag like this::\n\n    # Here, register is a django.template.Library instance, as before\n    @register.inclusion_tag('results.html')\n    def show_results(poll):\n        ...\n\nAlternatively it is possible to register the inclusion tag using a\n:class:`django.template.Template` instance::\n\n    from django.template.loader import get_template\n    t = get_template('results.html')\n    register.inclusion_tag(t)(show_results)\n\n...when first creating the function.\n\nSometimes, your inclusion tags might require a large number of arguments,\nmaking it a pain for template authors to pass in all the arguments and remember\ntheir order. To solve this, Django provides a ``takes_context`` option for\ninclusion tags. If you specify ``takes_context`` in creating a template tag,\nthe tag will have no required arguments, and the underlying Python function\nwill have one argument -- the template context as of when the tag was called.\n\nFor example, say you're writing an inclusion tag that will always be used in a\ncontext that contains ``home_link`` and ``home_title`` variables that point\nback to the main page. Here's what the Python function would look like::\n\n    @register.inclusion_tag('link.html', takes_context=True)\n    def jump_link(context):\n        return {\n            'link': context['home_link'],\n            'title': context['home_title'],\n        }\n\nNote that the first parameter to the function *must* be called ``context``.\n\nIn that ``register.inclusion_tag()`` line, we specified ``takes_context=True``\nand the name of the template. Here's what the template ``link.html`` might look\nlike:\n\n.. code-block:: html+django\n\n    Jump directly to <a href=\"{{ link }}\">{{ title }}</a>.\n\nThen, any time you want to use that custom tag, load its library and call it\nwithout any arguments, like so:\n\n.. code-block:: html+django\n\n    {% jump_link %}\n\nNote that when you're using ``takes_context=True``, there's no need to pass\narguments to the template tag. It automatically gets access to the context.\n\nThe ``takes_context`` parameter defaults to ``False``. When it's set to\n``True``, the tag is passed the context object, as in this example. That's the\nonly difference between this case and the previous ``inclusion_tag`` example.\n\n``inclusion_tag`` functions may accept any number of positional or keyword\narguments. For example::\n\n    @register.inclusion_tag('my_template.html')\n    def my_tag(a, b, *args, **kwargs):\n        warning = kwargs['warning']\n        profile = kwargs['profile']\n        ...\n        return ...\n\nThen in the template any number of arguments, separated by spaces, may be\npassed to the template tag. Like in Python, the values for keyword arguments\nare set using the equal sign (\"``=``\") and must be provided after the\npositional arguments. For example:\n\n.. code-block:: html+django\n\n    {% my_tag 123 \"abcd\" book.title warning=message|lower profile=user.profile %}\n\nAdvanced custom template tags\n-----------------------------\n\nSometimes the basic features for custom template tag creation aren't enough.\nDon't worry, Django gives you complete access to the internals required to build\na template tag from the ground up.\n\nA quick overview\n----------------\n\nThe template system works in a two-step process: compiling and rendering. To\ndefine a custom template tag, you specify how the compilation works and how\nthe rendering works.\n\nWhen Django compiles a template, it splits the raw template text into\n''nodes''. Each node is an instance of ``django.template.Node`` and has\na ``render()`` method. A compiled template is a list of ``Node`` objects. When\nyou call ``render()`` on a compiled template object, the template calls\n``render()`` on each ``Node`` in its node list, with the given context.  The\nresults are all concatenated together to form the output of the template.\n\nThus, to define a custom template tag, you specify how the raw template tag is\nconverted into a ``Node`` (the compilation function), and what the node's\n``render()`` method does.\n\nWriting the compilation function\n--------------------------------\n\nFor each template tag the template parser encounters, it calls a Python\nfunction with the tag contents and the parser object itself. This function is\nresponsible for returning a ``Node`` instance based on the contents of the tag.\n\nFor example, let's write a full implementation of our template tag,\n``{% current_time %}``, that displays the current date/time, formatted according\nto a parameter given in the tag, in :func:`~time.strftime` syntax. It's a good\nidea to decide the tag syntax before anything else. In our case, let's say the\ntag should be used like this:\n\n.. code-block:: html+django\n\n    <p>The time is {% current_time \"%Y-%m-%d %I:%M %p\" %}.</p>\n\nThe parser for this function should grab the parameter and create a ``Node``\nobject::\n\n    from django import template\n\n    def do_current_time(parser, token):\n        try:\n            # split_contents() knows not to split quoted strings.\n            tag_name, format_string = token.split_contents()\n        except ValueError:\n            raise template.TemplateSyntaxError(\n                \"%r tag requires a single argument\" % token.contents.split()[0]\n            )\n        if not (format_string[0] == format_string[-1] and format_string[0] in ('\"', \"'\")):\n            raise template.TemplateSyntaxError(\n                \"%r tag's argument should be in quotes\" % tag_name\n            )\n        return CurrentTimeNode(format_string[1:-1])\n\nNotes:\n\n* ``parser`` is the template parser object. We don't need it in this\n  example.\n\n* ``token.contents`` is a string of the raw contents of the tag. In our\n  example, it's ``'current_time \"%Y-%m-%d %I:%M %p\"'``.\n\n* The ``token.split_contents()`` method separates the arguments on spaces\n  while keeping quoted strings together. The more straightforward\n  ``token.contents.split()`` wouldn't be as robust, as it would naively\n  split on *all* spaces, including those within quoted strings. It's a good\n  idea to always use ``token.split_contents()``.\n\n* This function is responsible for raising\n  ``django.template.TemplateSyntaxError``, with helpful messages, for\n  any syntax error.\n\n* The ``TemplateSyntaxError`` exceptions use the ``tag_name`` variable.\n  Don't hard-code the tag's name in your error messages, because that\n  couples the tag's name to your function. ``token.contents.split()[0]``\n  will ''always'' be the name of your tag -- even when the tag has no\n  arguments.\n\n* The function returns a ``CurrentTimeNode`` with everything the node needs\n  to know about this tag. In this case, it passes the argument --\n  ``\"%Y-%m-%d %I:%M %p\"``. The leading and trailing quotes from the\n  template tag are removed in ``format_string[1:-1]``.\n\n* The parsing is very low-level. The Django developers have experimented\n  with writing small frameworks on top of this parsing system, using\n  techniques such as EBNF grammars, but those experiments made the template\n  engine too slow. It's low-level because that's fastest.\n\nWriting the renderer\n--------------------\n\nThe second step in writing custom tags is to define a ``Node`` subclass that\nhas a ``render()`` method.\n\nContinuing the above example, we need to define ``CurrentTimeNode``::\n\n    import datetime\n    from django import template\n\n    class CurrentTimeNode(template.Node):\n        def __init__(self, format_string):\n            self.format_string = format_string\n\n        def render(self, context):\n            return datetime.datetime.now().strftime(self.format_string)\n\nNotes:\n\n* ``__init__()`` gets the ``format_string`` from ``do_current_time()``.\n  Always pass any options/parameters/arguments to a ``Node`` via its\n  ``__init__()``.\n\n* The ``render()`` method is where the work actually happens.\n\n* ``render()`` should generally fail silently, particularly in a production\n  environment. In some cases however, particularly if\n  ``context.template.engine.debug`` is ``True``, this method may raise an\n  exception to make debugging easier. For example, several core tags raise\n  ``django.template.TemplateSyntaxError`` if they receive the wrong number or\n  type of arguments.\n\nUltimately, this decoupling of compilation and rendering results in an\nefficient template system, because a template can render multiple contexts\nwithout having to be parsed multiple times.\n\n.. _tags-auto-escaping:\n\nAuto-escaping considerations\n----------------------------\n\nThe output from template tags is **not** automatically run through the\nauto-escaping filters (with the exception of\n:meth:`~django.template.Library.simple_tag` as described above). However, there\nare still a couple of things you should keep in mind when writing a template\ntag.\n\nIf the ``render()`` method of your template tag stores the result in a context\nvariable (rather than returning the result in a string), it should take care\nto call ``mark_safe()`` if appropriate. When the variable is ultimately\nrendered, it will be affected by the auto-escape setting in effect at the\ntime, so content that should be safe from further escaping needs to be marked\nas such.\n\nAlso, if your template tag creates a new context for performing some\nsub-rendering, set the auto-escape attribute to the current context's value.\nThe ``__init__`` method for the ``Context`` class takes a parameter called\n``autoescape`` that you can use for this purpose. For example::\n\n    from django.template import Context\n\n    def render(self, context):\n        # ...\n        new_context = Context({'var': obj}, autoescape=context.autoescape)\n        # ... Do something with new_context ...\n\nThis is not a very common situation, but it's useful if you're rendering a\ntemplate yourself. For example::\n\n    def render(self, context):\n        t = context.template.engine.get_template('small_fragment.html')\n        return t.render(Context({'var': obj}, autoescape=context.autoescape))\n\nIf we had neglected to pass in the current ``context.autoescape`` value to our\nnew ``Context`` in this example, the results would have *always* been\nautomatically escaped, which may not be the desired behavior if the template\ntag is used inside a :ttag:`{% autoescape off %}<autoescape>` block.\n\n.. _template_tag_thread_safety:\n\nThread-safety considerations\n----------------------------\n\nOnce a node is parsed, its ``render`` method may be called any number of times.\nSince Django is sometimes run in multi-threaded environments, a single node may\nbe simultaneously rendering with different contexts in response to two separate\nrequests. Therefore, it's important to make sure your template tags are thread\nsafe.\n\nTo make sure your template tags are thread safe, you should never store state\ninformation on the node itself. For example, Django provides a builtin\n:ttag:`cycle` template tag that cycles among a list of given strings each time\nit's rendered:\n\n.. code-block:: html+django\n\n    {% for o in some_list %}\n        <tr class=\"{% cycle 'row1' 'row2' %}\">\n            ...\n        </tr>\n    {% endfor %}\n\nA naive implementation of ``CycleNode`` might look something like this::\n\n    import itertools\n    from django import template\n\n    class CycleNode(template.Node):\n        def __init__(self, cyclevars):\n            self.cycle_iter = itertools.cycle(cyclevars)\n\n        def render(self, context):\n            return next(self.cycle_iter)\n\nBut, suppose we have two templates rendering the template snippet from above at\nthe same time:\n\n#. Thread 1 performs its first loop iteration, ``CycleNode.render()``\n   returns 'row1'\n#. Thread 2 performs its first loop iteration, ``CycleNode.render()``\n   returns 'row2'\n#. Thread 1 performs its second loop iteration, ``CycleNode.render()``\n   returns 'row1'\n#. Thread 2 performs its second loop iteration, ``CycleNode.render()``\n   returns 'row2'\n\nThe CycleNode is iterating, but it's iterating globally. As far as Thread 1\nand Thread 2 are concerned, it's always returning the same value. This is\nnot what we want!\n\nTo address this problem, Django provides a ``render_context`` that's associated\nwith the ``context`` of the template that is currently being rendered. The\n``render_context`` behaves like a Python dictionary, and should be used to\nstore ``Node`` state between invocations of the ``render`` method.\n\nLet's refactor our ``CycleNode`` implementation to use the ``render_context``::\n\n    class CycleNode(template.Node):\n        def __init__(self, cyclevars):\n            self.cyclevars = cyclevars\n\n        def render(self, context):\n            if self not in context.render_context:\n                context.render_context[self] = itertools.cycle(self.cyclevars)\n            cycle_iter = context.render_context[self]\n            return next(cycle_iter)\n\nNote that it's perfectly safe to store global information that will not change\nthroughout the life of the ``Node`` as an attribute. In the case of\n``CycleNode``, the ``cyclevars`` argument doesn't change after the ``Node`` is\ninstantiated, so we don't need to put it in the ``render_context``. But state\ninformation that is specific to the template that is currently being rendered,\nlike the current iteration of the ``CycleNode``, should be stored in the\n``render_context``.\n\n.. note::\n    Notice how we used ``self`` to scope the ``CycleNode`` specific information\n    within the ``render_context``. There may be multiple ``CycleNodes`` in a\n    given template, so we need to be careful not to clobber another node's\n    state information. The easiest way to do this is to always use ``self`` as\n    the key into ``render_context``. If you're keeping track of several state\n    variables, make ``render_context[self]`` a dictionary.\n\nRegistering the tag\n-------------------\n\nFinally, register the tag with your module's ``Library`` instance, as explained\nin :ref:`writing custom template tags<howto-writing-custom-template-tags>`\nabove. Example::\n\n    register.tag('current_time', do_current_time)\n\nThe ``tag()`` method takes two arguments:\n\n1. The name of the template tag -- a string. If this is left out, the\n   name of the compilation function will be used.\n2. The compilation function -- a Python function (not the name of the\n   function as a string).\n\nAs with filter registration, it is also possible to use this as a decorator::\n\n    @register.tag(name=\"current_time\")\n    def do_current_time(parser, token):\n        ...\n\n    @register.tag\n    def shout(parser, token):\n        ...\n\nIf you leave off the ``name`` argument, as in the second example above, Django\nwill use the function's name as the tag name.\n\nPassing template variables to the tag\n-------------------------------------\n\nAlthough you can pass any number of arguments to a template tag using\n``token.split_contents()``, the arguments are all unpacked as\nstring literals. A little more work is required in order to pass dynamic\ncontent (a template variable) to a template tag as an argument.\n\nWhile the previous examples have formatted the current time into a string and\nreturned the string, suppose you wanted to pass in a\n:class:`~django.db.models.DateTimeField` from an object and have the template\ntag format that date-time:\n\n.. code-block:: html+django\n\n    <p>This post was last updated at {% format_time blog_entry.date_updated \"%Y-%m-%d %I:%M %p\" %}.</p>\n\nInitially, ``token.split_contents()`` will return three values:\n\n1. The tag name ``format_time``.\n2. The string ``'blog_entry.date_updated'`` (without the surrounding\n   quotes).\n3. The formatting string ``'\"%Y-%m-%d %I:%M %p\"'``. The return value from\n   ``split_contents()`` will include the leading and trailing quotes for\n   string literals like this.\n\nNow your tag should begin to look like this::\n\n    from django import template\n\n    def do_format_time(parser, token):\n        try:\n            # split_contents() knows not to split quoted strings.\n            tag_name, date_to_be_formatted, format_string = token.split_contents()\n        except ValueError:\n            raise template.TemplateSyntaxError(\n                \"%r tag requires exactly two arguments\" % token.contents.split()[0]\n            )\n        if not (format_string[0] == format_string[-1] and format_string[0] in ('\"', \"'\")):\n            raise template.TemplateSyntaxError(\n                \"%r tag's argument should be in quotes\" % tag_name\n            )\n        return FormatTimeNode(date_to_be_formatted, format_string[1:-1])\n\nYou also have to change the renderer to retrieve the actual contents of the\n``date_updated`` property of the ``blog_entry`` object.  This can be\naccomplished by using the ``Variable()`` class in ``django.template``.\n\nTo use the ``Variable`` class, instantiate it with the name of the variable to\nbe resolved, and then call ``variable.resolve(context)``. So, for example::\n\n    class FormatTimeNode(template.Node):\n        def __init__(self, date_to_be_formatted, format_string):\n            self.date_to_be_formatted = template.Variable(date_to_be_formatted)\n            self.format_string = format_string\n\n        def render(self, context):\n            try:\n                actual_date = self.date_to_be_formatted.resolve(context)\n                return actual_date.strftime(self.format_string)\n            except template.VariableDoesNotExist:\n                return ''\n\nVariable resolution will throw a ``VariableDoesNotExist`` exception if it\ncannot resolve the string passed to it in the current context of the page.\n\nSetting a variable in the context\n---------------------------------\n\nThe above examples output a value. Generally, it's more flexible if your\ntemplate tags set template variables instead of outputting values. That way,\ntemplate authors can reuse the values that your template tags create.\n\nTo set a variable in the context, use dictionary assignment on the context\nobject in the ``render()`` method. Here's an updated version of\n``CurrentTimeNode`` that sets a template variable ``current_time`` instead of\noutputting it::\n\n    import datetime\n    from django import template\n\n    class CurrentTimeNode2(template.Node):\n        def __init__(self, format_string):\n            self.format_string = format_string\n        def render(self, context):\n            context['current_time'] = datetime.datetime.now().strftime(self.format_string)\n            return ''\n\nNote that ``render()`` returns the empty string. ``render()`` should always\nreturn string output. If all the template tag does is set a variable,\n``render()`` should return the empty string.\n\nHere's how you'd use this new version of the tag:\n\n.. code-block:: html+django\n\n    {% current_time \"%Y-%m-%d %I:%M %p\" %}<p>The time is {{ current_time }}.</p>\n\n.. admonition:: Variable scope in context\n\n    Any variable set in the context will only be available in the same\n    ``block`` of the template in which it was assigned. This behavior is\n    intentional; it provides a scope for variables so that they don't conflict\n    with context in other blocks.\n\nBut, there's a problem with ``CurrentTimeNode2``: The variable name\n``current_time`` is hard-coded. This means you'll need to make sure your\ntemplate doesn't use ``{{ current_time }}`` anywhere else, because the\n``{% current_time %}`` will blindly overwrite that variable's value. A cleaner\nsolution is to make the template tag specify the name of the output variable,\nlike so:\n\n.. code-block:: html+django\n\n    {% current_time \"%Y-%m-%d %I:%M %p\" as my_current_time %}\n    <p>The current time is {{ my_current_time }}.</p>\n\nTo do that, you'll need to refactor both the compilation function and ``Node``\nclass, like so::\n\n    import re\n\n    class CurrentTimeNode3(template.Node):\n        def __init__(self, format_string, var_name):\n            self.format_string = format_string\n            self.var_name = var_name\n        def render(self, context):\n            context[self.var_name] = datetime.datetime.now().strftime(self.format_string)\n            return ''\n\n    def do_current_time(parser, token):\n        # This version uses a regular expression to parse tag contents.\n        try:\n            # Splitting by None == splitting by spaces.\n            tag_name, arg = token.contents.split(None, 1)\n        except ValueError:\n            raise template.TemplateSyntaxError(\n                \"%r tag requires arguments\" % token.contents.split()[0]\n            )\n        m = re.search(r'(.*?) as (\\w+)', arg)\n        if not m:\n            raise template.TemplateSyntaxError(\"%r tag had invalid arguments\" % tag_name)\n        format_string, var_name = m.groups()\n        if not (format_string[0] == format_string[-1] and format_string[0] in ('\"', \"'\")):\n            raise template.TemplateSyntaxError(\n                \"%r tag's argument should be in quotes\" % tag_name\n            )\n        return CurrentTimeNode3(format_string[1:-1], var_name)\n\nThe difference here is that ``do_current_time()`` grabs the format string and\nthe variable name, passing both to ``CurrentTimeNode3``.\n\nFinally, if you only need to have a simple syntax for your custom\ncontext-updating template tag, consider using the\n:meth:`~django.template.Library.simple_tag` shortcut, which supports assigning\nthe tag results to a template variable.\n\nParsing until another block tag\n-------------------------------\n\nTemplate tags can work in tandem. For instance, the standard\n:ttag:`{% comment %}<comment>` tag hides everything until ``{% endcomment %}``.\nTo create a template tag such as this, use ``parser.parse()`` in your\ncompilation function.\n\nHere's how a simplified ``{% comment %}`` tag might be implemented::\n\n    def do_comment(parser, token):\n        nodelist = parser.parse(('endcomment',))\n        parser.delete_first_token()\n        return CommentNode()\n\n    class CommentNode(template.Node):\n        def render(self, context):\n            return ''\n\n.. note::\n    The actual implementation of :ttag:`{% comment %}<comment>` is slightly\n    different in that it allows broken template tags to appear between\n    ``{% comment %}`` and ``{% endcomment %}``. It does so by calling\n    ``parser.skip_past('endcomment')`` instead of ``parser.parse(('endcomment',))``\n    followed by ``parser.delete_first_token()``, thus avoiding the generation of a\n    node list.\n\n``parser.parse()`` takes a tuple of names of block tags ''to parse until''. It\nreturns an instance of ``django.template.NodeList``, which is a list of\nall ``Node`` objects that the parser encountered ''before'' it encountered\nany of the tags named in the tuple.\n\nIn ``\"nodelist = parser.parse(('endcomment',))\"`` in the above example,\n``nodelist`` is a list of all nodes between the ``{% comment %}`` and\n``{% endcomment %}``, not counting ``{% comment %}`` and ``{% endcomment %}``\nthemselves.\n\nAfter ``parser.parse()`` is called, the parser hasn't yet \"consumed\" the\n``{% endcomment %}`` tag, so the code needs to explicitly call\n``parser.delete_first_token()``.\n\n``CommentNode.render()`` returns an empty string. Anything between\n``{% comment %}`` and ``{% endcomment %}`` is ignored.\n\nParsing until another block tag, and saving contents\n----------------------------------------------------\n\nIn the previous example, ``do_comment()`` discarded everything between\n``{% comment %}`` and ``{% endcomment %}``. Instead of doing that, it's\npossible to do something with the code between block tags.\n\nFor example, here's a custom template tag, ``{% upper %}``, that capitalizes\neverything between itself and ``{% endupper %}``.\n\nUsage:\n\n.. code-block:: html+django\n\n    {% upper %}This will appear in uppercase, {{ your_name }}.{% endupper %}\n\nAs in the previous example, we'll use ``parser.parse()``. But this time, we\npass the resulting ``nodelist`` to the ``Node``::\n\n    def do_upper(parser, token):\n        nodelist = parser.parse(('endupper',))\n        parser.delete_first_token()\n        return UpperNode(nodelist)\n\n    class UpperNode(template.Node):\n        def __init__(self, nodelist):\n            self.nodelist = nodelist\n        def render(self, context):\n            output = self.nodelist.render(context)\n            return output.upper()\n\nThe only new concept here is the ``self.nodelist.render(context)`` in\n``UpperNode.render()``.\n\nFor more examples of complex rendering, see the source code of\n:ttag:`{% for %}<for>` in ``django/template/defaulttags.py`` and\n:ttag:`{% if %}<if>` in ``django/template/smartif.py``.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":206,"nodeType":"TextFile","repoName":null,"name":"tutorial02.txt","path":"docs/intro","text":"=====================================\nWriting your first Django app, part 2\n=====================================\n\nThis tutorial begins where :doc:`Tutorial 1 </intro/tutorial01>` left off.\nWe'll setup the database, create your first model, and get a quick introduction\nto Django's automatically-generated admin site.\n\n.. admonition:: Where to get help:\n\n    If you're having trouble going through this tutorial, please head over to\n    the :doc:`Getting Help</faq/help>` section of the FAQ.\n\nDatabase setup\n==============\n\nNow, open up :file:`mysite/settings.py`. It's a normal Python module with\nmodule-level variables representing Django settings.\n\nBy default, the configuration uses SQLite. If you're new to databases, or\nyou're just interested in trying Django, this is the easiest choice. SQLite is\nincluded in Python, so you won't need to install anything else to support your\ndatabase. When starting your first real project, however, you may want to use a\nmore scalable database like PostgreSQL, to avoid database-switching headaches\ndown the road.\n\nIf you wish to use another database, install the appropriate :ref:`database\nbindings <database-installation>` and change the following keys in the\n:setting:`DATABASES` ``'default'`` item to match your database connection\nsettings:\n\n* :setting:`ENGINE <DATABASE-ENGINE>` -- Either\n  ``'django.db.backends.sqlite3'``,\n  ``'django.db.backends.postgresql'``,\n  ``'django.db.backends.mysql'``, or\n  ``'django.db.backends.oracle'``. Other backends are :ref:`also available\n  <third-party-notes>`.\n\n* :setting:`NAME` -- The name of your database. If you're using SQLite, the\n  database will be a file on your computer; in that case, :setting:`NAME`\n  should be the full absolute path, including filename, of that file. The\n  default value, ``BASE_DIR / 'db.sqlite3'``, will store the file in your\n  project directory.\n\nIf you are not using SQLite as your database, additional settings such as\n:setting:`USER`, :setting:`PASSWORD`, and :setting:`HOST` must be added.\nFor more details, see the reference documentation for :setting:`DATABASES`.\n\n.. admonition:: For databases other than SQLite\n\n    If you're using a database besides SQLite, make sure you've created a\n    database by this point. Do that with \"``CREATE DATABASE database_name;``\"\n    within your database's interactive prompt.\n\n    Also make sure that the database user provided in :file:`mysite/settings.py`\n    has \"create database\" privileges. This allows automatic creation of a\n    :ref:`test database <the-test-database>` which will be needed in a later\n    tutorial.\n\n    If you're using SQLite, you don't need to create anything beforehand - the\n    database file will be created automatically when it is needed.\n\nWhile you're editing :file:`mysite/settings.py`, set :setting:`TIME_ZONE` to\nyour time zone.\n\nAlso, note the :setting:`INSTALLED_APPS` setting at the top of the file. That\nholds the names of all Django applications that are activated in this Django\ninstance. Apps can be used in multiple projects, and you can package and\ndistribute them for use by others in their projects.\n\nBy default, :setting:`INSTALLED_APPS` contains the following apps, all of which\ncome with Django:\n\n* :mod:`django.contrib.admin` -- The admin site. You'll use it shortly.\n\n* :mod:`django.contrib.auth` -- An authentication system.\n\n* :mod:`django.contrib.contenttypes` -- A framework for content types.\n\n* :mod:`django.contrib.sessions` -- A session framework.\n\n* :mod:`django.contrib.messages` -- A messaging framework.\n\n* :mod:`django.contrib.staticfiles` -- A framework for managing\n  static files.\n\nThese applications are included by default as a convenience for the common case.\n\nSome of these applications make use of at least one database table, though,\nso we need to create the tables in the database before we can use them. To do\nthat, run the following command:\n\n.. console::\n\n    $ python manage.py migrate\n\nThe :djadmin:`migrate` command looks at the :setting:`INSTALLED_APPS` setting\nand creates any necessary database tables according to the database settings\nin your :file:`mysite/settings.py` file and the database migrations shipped\nwith the app (we'll cover those later). You'll see a message for each\nmigration it applies. If you're interested, run the command-line client for your\ndatabase and type ``\\dt`` (PostgreSQL), ``SHOW TABLES;`` (MariaDB, MySQL),\n``.schema`` (SQLite), or ``SELECT TABLE_NAME FROM USER_TABLES;`` (Oracle) to\ndisplay the tables Django created.\n\n.. admonition:: For the minimalists\n\n    Like we said above, the default applications are included for the common\n    case, but not everybody needs them. If you don't need any or all of them,\n    feel free to comment-out or delete the appropriate line(s) from\n    :setting:`INSTALLED_APPS` before running :djadmin:`migrate`. The\n    :djadmin:`migrate` command will only run migrations for apps in\n    :setting:`INSTALLED_APPS`.\n\n.. _creating-models:\n\nCreating models\n===============\n\nNow we'll define your models -- essentially, your database layout, with\nadditional metadata.\n\n.. admonition:: Philosophy\n\n   A model is the single, definitive source of truth about your data. It contains\n   the essential fields and behaviors of the data you're storing. Django follows\n   the :ref:`DRY Principle <dry>`. The goal is to define your data model in one\n   place and automatically derive things from it.\n\n   This includes the migrations - unlike in Ruby On Rails, for example, migrations\n   are entirely derived from your models file, and are essentially a\n   history that Django can roll through to update your database schema to\n   match your current models.\n\nIn our poll app, we'll create two models: ``Question`` and ``Choice``. A\n``Question`` has a question and a publication date. A ``Choice`` has two\nfields: the text of the choice and a vote tally. Each ``Choice`` is associated\nwith a ``Question``.\n\nThese concepts are represented by Python classes. Edit the\n:file:`polls/models.py` file so it looks like this:\n\n.. code-block:: python\n    :caption: polls/models.py\n\n    from django.db import models\n\n\n    class Question(models.Model):\n        question_text = models.CharField(max_length=200)\n        pub_date = models.DateTimeField('date published')\n\n\n    class Choice(models.Model):\n        question = models.ForeignKey(Question, on_delete=models.CASCADE)\n        choice_text = models.CharField(max_length=200)\n        votes = models.IntegerField(default=0)\n\nHere, each model is represented by a class that subclasses\n:class:`django.db.models.Model`. Each model has a number of class variables,\neach of which represents a database field in the model.\n\nEach field is represented by an instance of a :class:`~django.db.models.Field`\nclass -- e.g., :class:`~django.db.models.CharField` for character fields and\n:class:`~django.db.models.DateTimeField` for datetimes. This tells Django what\ntype of data each field holds.\n\nThe name of each :class:`~django.db.models.Field` instance (e.g.\n``question_text`` or ``pub_date``) is the field's name, in machine-friendly\nformat. You'll use this value in your Python code, and your database will use\nit as the column name.\n\nYou can use an optional first positional argument to a\n:class:`~django.db.models.Field` to designate a human-readable name. That's used\nin a couple of introspective parts of Django, and it doubles as documentation.\nIf this field isn't provided, Django will use the machine-readable name. In this\nexample, we've only defined a human-readable name for ``Question.pub_date``.\nFor all other fields in this model, the field's machine-readable name will\nsuffice as its human-readable name.\n\nSome :class:`~django.db.models.Field` classes have required arguments.\n:class:`~django.db.models.CharField`, for example, requires that you give it a\n:attr:`~django.db.models.CharField.max_length`. That's used not only in the\ndatabase schema, but in validation, as we'll soon see.\n\nA :class:`~django.db.models.Field` can also have various optional arguments; in\nthis case, we've set the :attr:`~django.db.models.Field.default` value of\n``votes`` to 0.\n\nFinally, note a relationship is defined, using\n:class:`~django.db.models.ForeignKey`. That tells Django each ``Choice`` is\nrelated to a single ``Question``. Django supports all the common database\nrelationships: many-to-one, many-to-many, and one-to-one.\n\nActivating models\n=================\n\nThat small bit of model code gives Django a lot of information. With it, Django\nis able to:\n\n* Create a database schema (``CREATE TABLE`` statements) for this app.\n* Create a Python database-access API for accessing ``Question`` and ``Choice`` objects.\n\nBut first we need to tell our project that the ``polls`` app is installed.\n\n.. admonition:: Philosophy\n\n    Django apps are \"pluggable\": You can use an app in multiple projects, and\n    you can distribute apps, because they don't have to be tied to a given\n    Django installation.\n\nTo include the app in our project, we need to add a reference to its\nconfiguration class in the :setting:`INSTALLED_APPS` setting. The\n``PollsConfig`` class is in the :file:`polls/apps.py` file, so its dotted path\nis ``'polls.apps.PollsConfig'``. Edit the :file:`mysite/settings.py` file and\nadd that dotted path to the :setting:`INSTALLED_APPS` setting. It'll look like\nthis:\n\n.. code-block:: python\n    :caption: mysite/settings.py\n\n    INSTALLED_APPS = [\n        'polls.apps.PollsConfig',\n        'django.contrib.admin',\n        'django.contrib.auth',\n        'django.contrib.contenttypes',\n        'django.contrib.sessions',\n        'django.contrib.messages',\n        'django.contrib.staticfiles',\n    ]\n\nNow Django knows to include the ``polls`` app. Let's run another command:\n\n.. console::\n\n    $ python manage.py makemigrations polls\n\nYou should see something similar to the following:\n\n.. code-block:: text\n\n    Migrations for 'polls':\n      polls/migrations/0001_initial.py\n        - Create model Question\n        - Create model Choice\n\nBy running ``makemigrations``, you're telling Django that you've made\nsome changes to your models (in this case, you've made new ones) and that\nyou'd like the changes to be stored as a *migration*.\n\nMigrations are how Django stores changes to your models (and thus your\ndatabase schema) - they're files on disk. You can read the migration for your\nnew model if you like; it's the file ``polls/migrations/0001_initial.py``.\nDon't worry, you're not expected to read them every time Django makes one, but\nthey're designed to be human-editable in case you want to manually tweak how\nDjango changes things.\n\nThere's a command that will run the migrations for you and manage your database\nschema automatically - that's called :djadmin:`migrate`, and we'll come to it in a\nmoment - but first, let's see what SQL that migration would run. The\n:djadmin:`sqlmigrate` command takes migration names and returns their SQL:\n\n.. console::\n\n    $ python manage.py sqlmigrate polls 0001\n\nYou should see something similar to the following (we've reformatted it for\nreadability):\n\n.. code-block:: sql\n\n    BEGIN;\n    --\n    -- Create model Question\n    --\n    CREATE TABLE \"polls_question\" (\n        \"id\" serial NOT NULL PRIMARY KEY,\n        \"question_text\" varchar(200) NOT NULL,\n        \"pub_date\" timestamp with time zone NOT NULL\n    );\n    --\n    -- Create model Choice\n    --\n    CREATE TABLE \"polls_choice\" (\n        \"id\" serial NOT NULL PRIMARY KEY,\n        \"choice_text\" varchar(200) NOT NULL,\n        \"votes\" integer NOT NULL,\n        \"question_id\" integer NOT NULL\n    );\n    ALTER TABLE \"polls_choice\"\n      ADD CONSTRAINT \"polls_choice_question_id_c5b4b260_fk_polls_question_id\"\n        FOREIGN KEY (\"question_id\")\n        REFERENCES \"polls_question\" (\"id\")\n        DEFERRABLE INITIALLY DEFERRED;\n    CREATE INDEX \"polls_choice_question_id_c5b4b260\" ON \"polls_choice\" (\"question_id\");\n\n    COMMIT;\n\nNote the following:\n\n* The exact output will vary depending on the database you are using. The\n  example above is generated for PostgreSQL.\n\n* Table names are automatically generated by combining the name of the app\n  (``polls``) and the lowercase name of the model -- ``question`` and\n  ``choice``. (You can override this behavior.)\n\n* Primary keys (IDs) are added automatically. (You can override this, too.)\n\n* By convention, Django appends ``\"_id\"`` to the foreign key field name.\n  (Yes, you can override this, as well.)\n\n* The foreign key relationship is made explicit by a ``FOREIGN KEY``\n  constraint. Don't worry about the ``DEFERRABLE`` parts; it's telling\n  PostgreSQL to not enforce the foreign key until the end of the transaction.\n\n* It's tailored to the database you're using, so database-specific field types\n  such as ``auto_increment`` (MySQL), ``serial`` (PostgreSQL), or ``integer\n  primary key autoincrement`` (SQLite) are handled for you automatically. Same\n  goes for the quoting of field names -- e.g., using double quotes or\n  single quotes.\n\n* The :djadmin:`sqlmigrate` command doesn't actually run the migration on your\n  database - instead, it prints it to the screen so that you can see what SQL\n  Django thinks is required. It's useful for checking what Django is going to\n  do or if you have database administrators who require SQL scripts for\n  changes.\n\nIf you're interested, you can also run\n:djadmin:`python manage.py check <check>`; this checks for any problems in\nyour project without making migrations or touching the database.\n\nNow, run :djadmin:`migrate` again to create those model tables in your database:\n\n.. console::\n\n    $ python manage.py migrate\n    Operations to perform:\n      Apply all migrations: admin, auth, contenttypes, polls, sessions\n    Running migrations:\n      Rendering model states... DONE\n      Applying polls.0001_initial... OK\n\nThe :djadmin:`migrate` command takes all the migrations that haven't been\napplied (Django tracks which ones are applied using a special table in your\ndatabase called ``django_migrations``) and runs them against your database -\nessentially, synchronizing the changes you made to your models with the schema\nin the database.\n\nMigrations are very powerful and let you change your models over time, as you\ndevelop your project, without the need to delete your database or tables and\nmake new ones - it specializes in upgrading your database live, without\nlosing data. We'll cover them in more depth in a later part of the tutorial,\nbut for now, remember the three-step guide to making model changes:\n\n* Change your models (in ``models.py``).\n* Run :djadmin:`python manage.py makemigrations <makemigrations>` to create\n  migrations for those changes\n* Run :djadmin:`python manage.py migrate <migrate>` to apply those changes to\n  the database.\n\nThe reason that there are separate commands to make and apply migrations is\nbecause you'll commit migrations to your version control system and ship them\nwith your app; they not only make your development easier, they're also\nusable by other developers and in production.\n\nRead the :doc:`django-admin documentation </ref/django-admin>` for full\ninformation on what the ``manage.py`` utility can do.\n\nPlaying with the API\n====================\n\nNow, let's hop into the interactive Python shell and play around with the free\nAPI Django gives you. To invoke the Python shell, use this command:\n\n.. console::\n\n    $ python manage.py shell\n\nWe're using this instead of simply typing \"python\", because :file:`manage.py`\nsets the :envvar:`DJANGO_SETTINGS_MODULE` environment variable, which gives\nDjango the Python import path to your :file:`mysite/settings.py` file.\n\nOnce you're in the shell, explore the :doc:`database API </topics/db/queries>`::\n\n    >>> from polls.models import Choice, Question  # Import the model classes we just wrote.\n\n    # No questions are in the system yet.\n    >>> Question.objects.all()\n    <QuerySet []>\n\n    # Create a new Question.\n    # Support for time zones is enabled in the default settings file, so\n    # Django expects a datetime with tzinfo for pub_date. Use timezone.now()\n    # instead of datetime.datetime.now() and it will do the right thing.\n    >>> from django.utils import timezone\n    >>> q = Question(question_text=\"What's new?\", pub_date=timezone.now())\n\n    # Save the object into the database. You have to call save() explicitly.\n    >>> q.save()\n\n    # Now it has an ID.\n    >>> q.id\n    1\n\n    # Access model field values via Python attributes.\n    >>> q.question_text\n    \"What's new?\"\n    >>> q.pub_date\n    datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)\n\n    # Change values by changing the attributes, then calling save().\n    >>> q.question_text = \"What's up?\"\n    >>> q.save()\n\n    # objects.all() displays all the questions in the database.\n    >>> Question.objects.all()\n    <QuerySet [<Question: Question object (1)>]>\n\nWait a minute. ``<Question: Question object (1)>`` isn't a helpful\nrepresentation of this object. Let's fix that by editing the ``Question`` model\n(in the ``polls/models.py`` file) and adding a\n:meth:`~django.db.models.Model.__str__` method to both ``Question`` and\n``Choice``:\n\n.. code-block:: python\n    :caption: polls/models.py\n\n    from django.db import models\n\n    class Question(models.Model):\n        # ...\n        def __str__(self):\n            return self.question_text\n\n    class Choice(models.Model):\n        # ...\n        def __str__(self):\n            return self.choice_text\n\nIt's important to add :meth:`~django.db.models.Model.__str__` methods to your\nmodels, not only for your own convenience when dealing with the interactive\nprompt, but also because objects' representations are used throughout Django's\nautomatically-generated admin.\n\n.. _tutorial02-import-timezone:\n\nLet's also add a custom method to this model:\n\n.. code-block:: python\n    :caption: polls/models.py\n\n    import datetime\n\n    from django.db import models\n    from django.utils import timezone\n\n\n    class Question(models.Model):\n        # ...\n        def was_published_recently(self):\n            return self.pub_date >= timezone.now() - datetime.timedelta(days=1)\n\nNote the addition of ``import datetime`` and ``from django.utils import\ntimezone``, to reference Python's standard :mod:`datetime` module and Django's\ntime-zone-related utilities in :mod:`django.utils.timezone`, respectively. If\nyou aren't familiar with time zone handling in Python, you can learn more in\nthe :doc:`time zone support docs </topics/i18n/timezones>`.\n\nSave these changes and start a new Python interactive shell by running\n``python manage.py shell`` again::\n\n    >>> from polls.models import Choice, Question\n\n    # Make sure our __str__() addition worked.\n    >>> Question.objects.all()\n    <QuerySet [<Question: What's up?>]>\n\n    # Django provides a rich database lookup API that's entirely driven by\n    # keyword arguments.\n    >>> Question.objects.filter(id=1)\n    <QuerySet [<Question: What's up?>]>\n    >>> Question.objects.filter(question_text__startswith='What')\n    <QuerySet [<Question: What's up?>]>\n\n    # Get the question that was published this year.\n    >>> from django.utils import timezone\n    >>> current_year = timezone.now().year\n    >>> Question.objects.get(pub_date__year=current_year)\n    <Question: What's up?>\n\n    # Request an ID that doesn't exist, this will raise an exception.\n    >>> Question.objects.get(id=2)\n    Traceback (most recent call last):\n        ...\n    DoesNotExist: Question matching query does not exist.\n\n    # Lookup by a primary key is the most common case, so Django provides a\n    # shortcut for primary-key exact lookups.\n    # The following is identical to Question.objects.get(id=1).\n    >>> Question.objects.get(pk=1)\n    <Question: What's up?>\n\n    # Make sure our custom method worked.\n    >>> q = Question.objects.get(pk=1)\n    >>> q.was_published_recently()\n    True\n\n    # Give the Question a couple of Choices. The create call constructs a new\n    # Choice object, does the INSERT statement, adds the choice to the set\n    # of available choices and returns the new Choice object. Django creates\n    # a set to hold the \"other side\" of a ForeignKey relation\n    # (e.g. a question's choice) which can be accessed via the API.\n    >>> q = Question.objects.get(pk=1)\n\n    # Display any choices from the related object set -- none so far.\n    >>> q.choice_set.all()\n    <QuerySet []>\n\n    # Create three choices.\n    >>> q.choice_set.create(choice_text='Not much', votes=0)\n    <Choice: Not much>\n    >>> q.choice_set.create(choice_text='The sky', votes=0)\n    <Choice: The sky>\n    >>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)\n\n    # Choice objects have API access to their related Question objects.\n    >>> c.question\n    <Question: What's up?>\n\n    # And vice versa: Question objects get access to Choice objects.\n    >>> q.choice_set.all()\n    <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>\n    >>> q.choice_set.count()\n    3\n\n    # The API automatically follows relationships as far as you need.\n    # Use double underscores to separate relationships.\n    # This works as many levels deep as you want; there's no limit.\n    # Find all Choices for any question whose pub_date is in this year\n    # (reusing the 'current_year' variable we created above).\n    >>> Choice.objects.filter(question__pub_date__year=current_year)\n    <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>\n\n    # Let's delete one of the choices. Use delete() for that.\n    >>> c = q.choice_set.filter(choice_text__startswith='Just hacking')\n    >>> c.delete()\n\nFor more information on model relations, see :doc:`Accessing related objects\n</ref/models/relations>`. For more on how to use double underscores to perform\nfield lookups via the API, see :ref:`Field lookups <field-lookups-intro>`. For\nfull details on the database API, see our :doc:`Database API reference\n</topics/db/queries>`.\n\nIntroducing the Django Admin\n============================\n\n.. admonition:: Philosophy\n\n    Generating admin sites for your staff or clients to add, change, and delete\n    content is tedious work that doesn't require much creativity. For that\n    reason, Django entirely automates creation of admin interfaces for models.\n\n    Django was written in a newsroom environment, with a very clear separation\n    between \"content publishers\" and the \"public\" site. Site managers use the\n    system to add news stories, events, sports scores, etc., and that content is\n    displayed on the public site. Django solves the problem of creating a\n    unified interface for site administrators to edit content.\n\n    The admin isn't intended to be used by site visitors. It's for site\n    managers.\n\nCreating an admin user\n----------------------\n\nFirst we'll need to create a user who can login to the admin site. Run the\nfollowing command:\n\n.. console::\n\n    $ python manage.py createsuperuser\n\nEnter your desired username and press enter.\n\n.. code-block:: text\n\n    Username: admin\n\nYou will then be prompted for your desired email address:\n\n.. code-block:: text\n\n    Email address: admin@example.com\n\nThe final step is to enter your password. You will be asked to enter your\npassword twice, the second time as a confirmation of the first.\n\n.. code-block:: text\n\n    Password: **********\n    Password (again): *********\n    Superuser created successfully.\n\nStart the development server\n----------------------------\n\nThe Django admin site is activated by default. Let's start the development\nserver and explore it.\n\nIf the server is not running start it like so:\n\n.. console::\n\n    $ python manage.py runserver\n\nNow, open a Web browser and go to \"/admin/\" on your local domain -- e.g.,\nhttp://127.0.0.1:8000/admin/. You should see the admin's login screen:\n\n.. image:: _images/admin01.png\n   :alt: Django admin login screen\n\nSince :doc:`translation </topics/i18n/translation>` is turned on by default, if\nyou set :setting:`LANGUAGE_CODE`, the login screen will be displayed in the\ngiven language (if Django has appropriate translations).\n\nEnter the admin site\n--------------------\n\nNow, try logging in with the superuser account you created in the previous step.\nYou should see the Django admin index page:\n\n.. image:: _images/admin02.png\n   :alt: Django admin index page\n\nYou should see a few types of editable content: groups and users. They are\nprovided by :mod:`django.contrib.auth`, the authentication framework shipped\nby Django.\n\nMake the poll app modifiable in the admin\n-----------------------------------------\n\nBut where's our poll app? It's not displayed on the admin index page.\n\nOnly one more thing to do: we need to tell the admin that ``Question`` objects\nhave an admin interface. To do this, open the :file:`polls/admin.py` file, and\nedit it to look like this:\n\n.. code-block:: python\n    :caption: polls/admin.py\n\n    from django.contrib import admin\n\n    from .models import Question\n\n    admin.site.register(Question)\n\nExplore the free admin functionality\n------------------------------------\n\nNow that we've registered ``Question``, Django knows that it should be displayed on\nthe admin index page:\n\n.. image:: _images/admin03t.png\n   :alt: Django admin index page, now with polls displayed\n\nClick \"Questions\". Now you're at the \"change list\" page for questions. This page\ndisplays all the questions in the database and lets you choose one to change it.\nThere's the \"What's up?\" question we created earlier:\n\n.. image:: _images/admin04t.png\n   :alt: Polls change list page\n\nClick the \"What's up?\" question to edit it:\n\n.. image:: _images/admin05t.png\n   :alt: Editing form for question object\n\nThings to note here:\n\n* The form is automatically generated from the ``Question`` model.\n\n* The different model field types (:class:`~django.db.models.DateTimeField`,\n  :class:`~django.db.models.CharField`) correspond to the appropriate HTML\n  input widget. Each type of field knows how to display itself in the Django\n  admin.\n\n* Each :class:`~django.db.models.DateTimeField` gets free JavaScript\n  shortcuts. Dates get a \"Today\" shortcut and calendar popup, and times get\n  a \"Now\" shortcut and a convenient popup that lists commonly entered times.\n\nThe bottom part of the page gives you a couple of options:\n\n* Save -- Saves changes and returns to the change-list page for this type of\n  object.\n\n* Save and continue editing -- Saves changes and reloads the admin page for\n  this object.\n\n* Save and add another -- Saves changes and loads a new, blank form for this\n  type of object.\n\n* Delete -- Displays a delete confirmation page.\n\nIf the value of \"Date published\" doesn't match the time when you created the\nquestion in :doc:`Tutorial 1</intro/tutorial01>`, it probably\nmeans you forgot to set the correct value for the :setting:`TIME_ZONE` setting.\nChange it, reload the page and check that the correct value appears.\n\nChange the \"Date published\" by clicking the \"Today\" and \"Now\" shortcuts. Then\nclick \"Save and continue editing.\" Then click \"History\" in the upper right.\nYou'll see a page listing all changes made to this object via the Django admin,\nwith the timestamp and username of the person who made the change:\n\n.. image:: _images/admin06t.png\n   :alt: History page for question object\n\nWhen you're comfortable with the models API and have familiarized yourself with\nthe admin site, read :doc:`part 3 of this tutorial</intro/tutorial03>` to learn\nabout how to add more views to our polls app.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":207,"nodeType":"Package","repoName":null,"name":"docs/howto/static-files","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":208,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/howto/static-files","text":"====================================================\nManaging static files (e.g. images, JavaScript, CSS)\n====================================================\n\nWebsites generally need to serve additional files such as images, JavaScript,\nor CSS. In Django, we refer to these files as \"static files\".  Django provides\n:mod:`django.contrib.staticfiles` to help you manage them.\n\nThis page describes how you can serve these static files.\n\nConfiguring static files\n========================\n\n#. Make sure that ``django.contrib.staticfiles`` is included in your\n   :setting:`INSTALLED_APPS`.\n\n#. In your settings file, define :setting:`STATIC_URL`, for example::\n\n      STATIC_URL = '/static/'\n\n#. In your templates, use the :ttag:`static` template tag to build the URL for\n   the given relative path using the configured :setting:`STATICFILES_STORAGE`.\n\n   .. _staticfiles-in-templates:\n\n   .. code-block:: html+django\n\n        {% load static %}\n        <img src=\"{% static \"my_app/example.jpg\" %}\" alt=\"My image\">\n\n#. Store your static files in a folder called ``static`` in your app. For\n   example ``my_app/static/my_app/example.jpg``.\n\n.. admonition:: Serving the files\n\n    In addition to these configuration steps, you'll also need to actually\n    serve the static files.\n\n    During development, if you use :mod:`django.contrib.staticfiles`, this will\n    be done automatically by :djadmin:`runserver` when :setting:`DEBUG` is set\n    to ``True`` (see :func:`django.contrib.staticfiles.views.serve`).\n\n    This method is **grossly inefficient** and probably **insecure**,\n    so it is **unsuitable for production**.\n\n    See :doc:`/howto/static-files/deployment` for proper strategies to serve\n    static files in production environments.\n\nYour project will probably also have static assets that aren't tied to a\nparticular app. In addition to using a ``static/`` directory inside your apps,\nyou can define a list of directories (:setting:`STATICFILES_DIRS`) in your\nsettings file where Django will also look for static files. For example::\n\n    STATICFILES_DIRS = [\n        BASE_DIR / \"static\",\n        '/var/www/static/',\n    ]\n\nSee the documentation for the :setting:`STATICFILES_FINDERS` setting for\ndetails on how ``staticfiles`` finds your files.\n\n.. admonition:: Static file namespacing\n\n    Now we *might* be able to get away with putting our static files directly\n    in ``my_app/static/`` (rather than creating another ``my_app``\n    subdirectory), but it would actually be a bad idea. Django will use the\n    first static file it finds whose name matches, and if you had a static file\n    with the same name in a *different* application, Django would be unable to\n    distinguish between them. We need to be able to point Django at the right\n    one, and the best way to ensure this is by *namespacing* them. That is,\n    by putting those static files inside *another* directory named for the\n    application itself.\n\n    You can namespace static assets in :setting:`STATICFILES_DIRS` by\n    specifying :ref:`prefixes <staticfiles-dirs-prefixes>`.\n\n.. _serving-static-files-in-development:\n\nServing static files during development\n=======================================\n\nIf you use :mod:`django.contrib.staticfiles` as explained above,\n:djadmin:`runserver` will do this automatically when :setting:`DEBUG` is set\nto ``True``. If you don't have ``django.contrib.staticfiles`` in\n:setting:`INSTALLED_APPS`, you can still manually serve static files using the\n:func:`django.views.static.serve` view.\n\nThis is not suitable for production use! For some common deployment\nstrategies, see :doc:`/howto/static-files/deployment`.\n\nFor example, if your :setting:`STATIC_URL` is defined as ``/static/``, you can do\nthis by adding the following snippet to your urls.py::\n\n    from django.conf import settings\n    from django.conf.urls.static import static\n\n    urlpatterns = [\n        # ... the rest of your URLconf goes here ...\n    ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n\n.. note::\n\n    This helper function works only in debug mode and only if\n    the given prefix is local (e.g. ``/static/``) and not a URL (e.g.\n    ``http://static.example.com/``).\n\n    Also this helper function only serves the actual :setting:`STATIC_ROOT`\n    folder; it doesn't perform static files discovery like\n    :mod:`django.contrib.staticfiles`.\n\n.. _serving-uploaded-files-in-development:\n\nServing files uploaded by a user during development\n===================================================\n\nDuring development, you can serve user-uploaded media files from\n:setting:`MEDIA_ROOT` using the :func:`django.views.static.serve` view.\n\nThis is not suitable for production use! For some common deployment\nstrategies, see :doc:`/howto/static-files/deployment`.\n\nFor example, if your :setting:`MEDIA_URL` is defined as ``/media/``, you can do\nthis by adding the following snippet to your urls.py::\n\n    from django.conf import settings\n    from django.conf.urls.static import static\n\n    urlpatterns = [\n        # ... the rest of your URLconf goes here ...\n    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\n.. note::\n\n    This helper function works only in debug mode and only if\n    the given prefix is local (e.g. ``/media/``) and not a URL (e.g.\n    ``http://media.example.com/``).\n\n.. _staticfiles-testing-support:\n\nTesting\n=======\n\nWhen running tests that use actual HTTP requests instead of the built-in\ntesting client (i.e. when using the built-in :class:`LiveServerTestCase\n<django.test.LiveServerTestCase>`) the static assets need to be served along\nthe rest of the content so the test environment reproduces the real one as\nfaithfully as possible, but ``LiveServerTestCase`` has only very basic static\nfile-serving functionality: It doesn't know about the finders feature of the\n``staticfiles`` application and assumes the static content has already been\ncollected under :setting:`STATIC_ROOT`.\n\nBecause of this, ``staticfiles`` ships its own\n:class:`django.contrib.staticfiles.testing.StaticLiveServerTestCase`, a subclass\nof the built-in one that has the ability to transparently serve all the assets\nduring execution of these tests in a way very similar to what we get at\ndevelopment time with ``DEBUG = True``, i.e. without having to collect them\nusing :djadmin:`collectstatic` first.\n\nDeployment\n==========\n\n:mod:`django.contrib.staticfiles` provides a convenience management command\nfor gathering static files in a single directory so you can serve them easily.\n\n#. Set the :setting:`STATIC_ROOT` setting to the directory from which you'd\n   like to serve these files, for example::\n\n       STATIC_ROOT = \"/var/www/example.com/static/\"\n\n#. Run the :djadmin:`collectstatic` management command::\n\n       $ python manage.py collectstatic\n\n   This will copy all files from your static folders into the\n   :setting:`STATIC_ROOT` directory.\n\n#. Use a web server of your choice to serve the\n   files. :doc:`/howto/static-files/deployment` covers some common deployment\n   strategies for static files.\n\nLearn more\n==========\n\nThis document has covered the basics and some common usage patterns. For\ncomplete details on all the settings, commands, template tags, and other pieces\nincluded in :mod:`django.contrib.staticfiles`, see :doc:`the staticfiles\nreference </ref/contrib/staticfiles>`.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":209,"nodeType":"TextFile","repoName":null,"name":"deployment.txt","path":"docs/howto/static-files","text":"======================\nDeploying static files\n======================\n\n.. seealso::\n\n    For an introduction to the use of :mod:`django.contrib.staticfiles`, see\n    :doc:`/howto/static-files/index`.\n\n.. _staticfiles-production:\n\nServing static files in production\n==================================\n\nThe basic outline of putting static files into production consists of two\nsteps: run the :djadmin:`collectstatic` command when static files change, then\narrange for the collected static files directory (:setting:`STATIC_ROOT`) to be\nmoved to the static file server and served. Depending on\n:setting:`STATICFILES_STORAGE`, files may need to be moved to a new location\nmanually or the :func:`post_process\n<django.contrib.staticfiles.storage.StaticFilesStorage.post_process>` method of\nthe ``Storage`` class might take care of that.\n\nAs with all deployment tasks, the devil's in the details. Every production\nsetup will be a bit different, so you'll need to adapt the basic outline to fit\nyour needs. Below are a few common patterns that might help.\n\nServing the site and your static files from the same server\n-----------------------------------------------------------\n\nIf you want to serve your static files from the same server that's already\nserving your site, the process may look something like:\n\n* Push your code up to the deployment server.\n* On the server, run :djadmin:`collectstatic` to copy all the static files\n  into :setting:`STATIC_ROOT`.\n* Configure your web server to serve the files in :setting:`STATIC_ROOT`\n  under the URL :setting:`STATIC_URL`. For example, here's\n  :ref:`how to do this with Apache and mod_wsgi <serving-files>`.\n\nYou'll probably want to automate this process, especially if you've got\nmultiple web servers.\n\nServing static files from a dedicated server\n--------------------------------------------\n\nMost larger Django sites use a separate Web server -- i.e., one that's not also\nrunning Django -- for serving static files. This server often runs a different\ntype of web server -- faster but less full-featured. Some common choices are:\n\n* Nginx_\n* A stripped-down version of Apache_\n\n.. _Nginx: https://nginx.org/en/\n.. _Apache: https://httpd.apache.org/\n\nConfiguring these servers is out of scope of this document; check each\nserver's respective documentation for instructions.\n\nSince your static file server won't be running Django, you'll need to modify\nthe deployment strategy to look something like:\n\n* When your static files change, run :djadmin:`collectstatic` locally.\n\n* Push your local :setting:`STATIC_ROOT` up to the static file server into the\n  directory that's being served. `rsync <https://rsync.samba.org/>`_ is a\n  common choice for this step since it only needs to transfer the bits of\n  static files that have changed.\n\n.. _staticfiles-from-cdn:\n\nServing static files from a cloud service or CDN\n------------------------------------------------\n\nAnother common tactic is to serve static files from a cloud storage provider\nlike Amazon's S3 and/or a CDN (content delivery network). This lets you\nignore the problems of serving static files and can often make for\nfaster-loading Web pages (especially when using a CDN).\n\nWhen using these services, the basic workflow would look a bit like the above,\nexcept that instead of using ``rsync`` to transfer your static files to the\nserver you'd need to transfer the static files to the storage provider or CDN.\n\nThere's any number of ways you might do this, but if the provider has an API,\nyou can use a :doc:`custom file storage backend </howto/custom-file-storage>`\nto integrate the CDN with your Django project. If you've written or are using a\n3rd party custom storage backend, you can tell :djadmin:`collectstatic` to use\nit by setting :setting:`STATICFILES_STORAGE` to the storage engine.\n\nFor example, if you've written an S3 storage backend in\n``myproject.storage.S3Storage`` you could use it with::\n\n    STATICFILES_STORAGE = 'myproject.storage.S3Storage'\n\nOnce that's done, all you have to do is run :djadmin:`collectstatic` and your\nstatic files would be pushed through your storage package up to S3. If you\nlater needed to switch to a different storage provider, you may only have to\nchange your :setting:`STATICFILES_STORAGE` setting.\n\nFor details on how you'd write one of these backends, see\n:doc:`/howto/custom-file-storage`. There are 3rd party apps available that\nprovide storage backends for many common file storage APIs. A good starting\npoint is the `overview at djangopackages.org\n<https://djangopackages.org/grids/g/storage-backends/>`_.\n\nLearn more\n==========\n\nFor complete details on all the settings, commands, template tags, and other\npieces included in :mod:`django.contrib.staticfiles`, see :doc:`the\nstaticfiles reference </ref/contrib/staticfiles>`.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":210,"nodeType":"TextFile","repoName":null,"name":"custom-model-fields.txt","path":"docs/howto","text":"===========================\nWriting custom model fields\n===========================\n\n.. currentmodule:: django.db.models\n\nIntroduction\n============\n\nThe :doc:`model reference </topics/db/models>` documentation explains how to use\nDjango's standard field classes -- :class:`~django.db.models.CharField`,\n:class:`~django.db.models.DateField`, etc. For many purposes, those classes are\nall you'll need. Sometimes, though, the Django version won't meet your precise\nrequirements, or you'll want to use a field that is entirely different from\nthose shipped with Django.\n\nDjango's built-in field types don't cover every possible database column type --\nonly the common types, such as ``VARCHAR`` and ``INTEGER``. For more obscure\ncolumn types, such as geographic polygons or even user-created types such as\n`PostgreSQL custom types`_, you can define your own Django ``Field`` subclasses.\n\n.. _PostgreSQL custom types: https://www.postgresql.org/docs/current/sql-createtype.html\n\nAlternatively, you may have a complex Python object that can somehow be\nserialized to fit into a standard database column type. This is another case\nwhere a ``Field`` subclass will help you use your object with your models.\n\nOur example object\n------------------\n\nCreating custom fields requires a bit of attention to detail. To make things\neasier to follow, we'll use a consistent example throughout this document:\nwrapping a Python object representing the deal of cards in a hand of Bridge_.\nDon't worry, you don't have to know how to play Bridge to follow this example.\nYou only need to know that 52 cards are dealt out equally to four players, who\nare traditionally called *north*, *east*, *south* and *west*.  Our class looks\nsomething like this::\n\n    class Hand:\n        \"\"\"A hand of cards (bridge style)\"\"\"\n\n        def __init__(self, north, east, south, west):\n            # Input parameters are lists of cards ('Ah', '9s', etc.)\n            self.north = north\n            self.east = east\n            self.south = south\n            self.west = west\n\n        # ... (other possibly useful methods omitted) ...\n\n.. _Bridge: https://en.wikipedia.org/wiki/Contract_bridge\n\nThis is an ordinary Python class, with nothing Django-specific about it.\nWe'd like to be able to do things like this in our models (we assume the\n``hand`` attribute on the model is an instance of ``Hand``)::\n\n    example = MyModel.objects.get(pk=1)\n    print(example.hand.north)\n\n    new_hand = Hand(north, east, south, west)\n    example.hand = new_hand\n    example.save()\n\nWe assign to and retrieve from the ``hand`` attribute in our model just like\nany other Python class. The trick is to tell Django how to handle saving and\nloading such an object.\n\nIn order to use the ``Hand`` class in our models, we **do not** have to change\nthis class at all. This is ideal, because it means you can easily write\nmodel support for existing classes where you cannot change the source code.\n\n.. note::\n    You might only be wanting to take advantage of custom database column\n    types and deal with the data as standard Python types in your models;\n    strings, or floats, for example. This case is similar to our ``Hand``\n    example and we'll note any differences as we go along.\n\nBackground theory\n=================\n\nDatabase storage\n----------------\n\nLet's start with model fields. If you break it down, a model field provides a\nway to take a normal Python object -- string, boolean, ``datetime``, or\nsomething more complex like ``Hand`` -- and convert it to and from a format\nthat is useful when dealing with the database. (Such a format is also useful\nfor serialization, but as we'll see later, that is easier once you have the\ndatabase side under control).\n\nFields in a model must somehow be converted to fit into an existing database\ncolumn type. Different databases provide different sets of valid column types,\nbut the rule is still the same: those are the only types you have to work\nwith. Anything you want to store in the database must fit into one of\nthose types.\n\nNormally, you're either writing a Django field to match a particular database\ncolumn type, or you will need a way to convert your data to, say, a string.\n\nFor our ``Hand`` example, we could convert the card data to a string of 104\ncharacters by concatenating all the cards together in a pre-determined order --\nsay, all the *north* cards first, then the *east*, *south* and *west* cards. So\n``Hand`` objects can be saved to text or character columns in the database.\n\nWhat does a field class do?\n---------------------------\n\nAll of Django's fields (and when we say *fields* in this document, we always\nmean model fields and not :doc:`form fields </ref/forms/fields>`) are subclasses\nof :class:`django.db.models.Field`. Most of the information that Django records\nabout a field is common to all fields -- name, help text, uniqueness and so\nforth. Storing all that information is handled by ``Field``. We'll get into the\nprecise details of what ``Field`` can do later on; for now, suffice it to say\nthat everything descends from ``Field`` and then customizes key pieces of the\nclass behavior.\n\nIt's important to realize that a Django field class is not what is stored in\nyour model attributes. The model attributes contain normal Python objects. The\nfield classes you define in a model are actually stored in the ``Meta`` class\nwhen the model class is created (the precise details of how this is done are\nunimportant here). This is because the field classes aren't necessary when\nyou're just creating and modifying attributes. Instead, they provide the\nmachinery for converting between the attribute value and what is stored in the\ndatabase or sent to the :doc:`serializer </topics/serialization>`.\n\nKeep this in mind when creating your own custom fields. The Django ``Field``\nsubclass you write provides the machinery for converting between your Python\ninstances and the database/serializer values in various ways (there are\ndifferences between storing a value and using a value for lookups, for\nexample). If this sounds a bit tricky, don't worry -- it will become clearer in\nthe examples below. Just remember that you will often end up creating two\nclasses when you want a custom field:\n\n* The first class is the Python object that your users will manipulate.\n  They will assign it to the model attribute, they will read from it for\n  displaying purposes, things like that. This is the ``Hand`` class in our\n  example.\n\n* The second class is the ``Field`` subclass. This is the class that knows\n  how to convert your first class back and forth between its permanent\n  storage form and the Python form.\n\nWriting a field subclass\n========================\n\nWhen planning your :class:`~django.db.models.Field` subclass, first give some\nthought to which existing :class:`~django.db.models.Field` class your new field\nis most similar to. Can you subclass an existing Django field and save yourself\nsome work? If not, you should subclass the :class:`~django.db.models.Field`\nclass, from which everything is descended.\n\nInitializing your new field is a matter of separating out any arguments that are\nspecific to your case from the common arguments and passing the latter to the\n``__init__()`` method of :class:`~django.db.models.Field` (or your parent\nclass).\n\nIn our example, we'll call our field ``HandField``. (It's a good idea to call\nyour :class:`~django.db.models.Field` subclass ``<Something>Field``, so it's\neasily identifiable as a :class:`~django.db.models.Field` subclass.) It doesn't\nbehave like any existing field, so we'll subclass directly from\n:class:`~django.db.models.Field`::\n\n    from django.db import models\n\n    class HandField(models.Field):\n\n        description = \"A hand of cards (bridge style)\"\n\n        def __init__(self, *args, **kwargs):\n            kwargs['max_length'] = 104\n            super().__init__(*args, **kwargs)\n\nOur ``HandField`` accepts most of the standard field options (see the list\nbelow), but we ensure it has a fixed length, since it only needs to hold 52\ncard values plus their suits; 104 characters in total.\n\n.. note::\n\n    Many of Django's model fields accept options that they don't do anything\n    with. For example, you can pass both\n    :attr:`~django.db.models.Field.editable` and\n    :attr:`~django.db.models.DateField.auto_now` to a\n    :class:`django.db.models.DateField` and it will ignore the\n    :attr:`~django.db.models.Field.editable` parameter\n    (:attr:`~django.db.models.DateField.auto_now` being set implies\n    ``editable=False``). No error is raised in this case.\n\n    This behavior simplifies the field classes, because they don't need to\n    check for options that aren't necessary. They pass all the options to\n    the parent class and then don't use them later on. It's up to you whether\n    you want your fields to be more strict about the options they select, or to\n    use the more permissive behavior of the current fields.\n\nThe ``Field.__init__()`` method takes the following parameters:\n\n* :attr:`~django.db.models.Field.verbose_name`\n* ``name``\n* :attr:`~django.db.models.Field.primary_key`\n* :attr:`~django.db.models.CharField.max_length`\n* :attr:`~django.db.models.Field.unique`\n* :attr:`~django.db.models.Field.blank`\n* :attr:`~django.db.models.Field.null`\n* :attr:`~django.db.models.Field.db_index`\n* ``rel``: Used for related fields (like :class:`ForeignKey`). For advanced\n  use only.\n* :attr:`~django.db.models.Field.default`\n* :attr:`~django.db.models.Field.editable`\n* ``serialize``: If ``False``, the field will not be serialized when the model\n  is passed to Django's :doc:`serializers </topics/serialization>`. Defaults to\n  ``True``.\n* :attr:`~django.db.models.Field.unique_for_date`\n* :attr:`~django.db.models.Field.unique_for_month`\n* :attr:`~django.db.models.Field.unique_for_year`\n* :attr:`~django.db.models.Field.choices`\n* :attr:`~django.db.models.Field.help_text`\n* :attr:`~django.db.models.Field.db_column`\n* :attr:`~django.db.models.Field.db_tablespace`: Only for index creation, if the\n  backend supports :doc:`tablespaces </topics/db/tablespaces>`. You can usually\n  ignore this option.\n* :attr:`~django.db.models.Field.auto_created`: ``True`` if the field was\n  automatically created, as for the :class:`~django.db.models.OneToOneField`\n  used by model inheritance. For advanced use only.\n\nAll of the options without an explanation in the above list have the same\nmeaning they do for normal Django fields. See the :doc:`field documentation\n</ref/models/fields>` for examples and details.\n\n.. _custom-field-deconstruct-method:\n\nField deconstruction\n--------------------\n\nThe counterpoint to writing your ``__init__()`` method is writing the\n:meth:`~.Field.deconstruct` method. It's used during :doc:`model migrations\n</topics/migrations>` to tell Django how to take an instance of your new field\nand reduce it to a serialized form - in particular, what arguments to pass to\n``__init__()`` to re-create it.\n\nIf you haven't added any extra options on top of the field you inherited from,\nthen there's no need to write a new ``deconstruct()`` method. If, however,\nyou're changing the arguments passed in ``__init__()`` (like we are in\n``HandField``), you'll need to supplement the values being passed.\n\n``deconstruct()`` returns a tuple of four items: the field's attribute name,\nthe full import path of the field class, the positional arguments (as a list),\nand the keyword arguments (as a dict). Note this is different from the\n``deconstruct()`` method :ref:`for custom classes <custom-deconstruct-method>`\nwhich returns a tuple of three things.\n\nAs a custom field author, you don't need to care about the first two values;\nthe base ``Field`` class has all the code to work out the field's attribute\nname and import path. You do, however, have to care about the positional\nand keyword arguments, as these are likely the things you are changing.\n\nFor example, in our ``HandField`` class we're always forcibly setting\nmax_length in ``__init__()``. The ``deconstruct()`` method on the base ``Field``\nclass will see this and try to return it in the keyword arguments; thus,\nwe can drop it from the keyword arguments for readability::\n\n    from django.db import models\n\n    class HandField(models.Field):\n\n        def __init__(self, *args, **kwargs):\n            kwargs['max_length'] = 104\n            super().__init__(*args, **kwargs)\n\n        def deconstruct(self):\n            name, path, args, kwargs = super().deconstruct()\n            del kwargs[\"max_length\"]\n            return name, path, args, kwargs\n\nIf you add a new keyword argument, you need to write code in ``deconstruct()``\nthat puts its value into ``kwargs`` yourself. You should also omit the value\nfrom ``kwargs`` when it isn't necessary to reconstruct the state of the field,\nsuch as when the default value is being used::\n\n    from django.db import models\n\n    class CommaSepField(models.Field):\n        \"Implements comma-separated storage of lists\"\n\n        def __init__(self, separator=\",\", *args, **kwargs):\n            self.separator = separator\n            super().__init__(*args, **kwargs)\n\n        def deconstruct(self):\n            name, path, args, kwargs = super().deconstruct()\n            # Only include kwarg if it's not the default\n            if self.separator != \",\":\n                kwargs['separator'] = self.separator\n            return name, path, args, kwargs\n\nMore complex examples are beyond the scope of this document, but remember -\nfor any configuration of your Field instance, ``deconstruct()`` must return\narguments that you can pass to ``__init__`` to reconstruct that state.\n\nPay extra attention if you set new default values for arguments in the\n``Field`` superclass; you want to make sure they're always included, rather\nthan disappearing if they take on the old default value.\n\nIn addition, try to avoid returning values as positional arguments; where\npossible, return values as keyword arguments for maximum future compatibility.\nIf you change the names of things more often than their position in the\nconstructor's argument list, you might prefer positional, but bear in mind that\npeople will be reconstructing your field from the serialized version for quite\na while (possibly years), depending how long your migrations live for.\n\nYou can see the results of deconstruction by looking in migrations that include\nthe field, and you can test deconstruction in unit tests by deconstructing and\nreconstructing the field::\n\n    name, path, args, kwargs = my_field_instance.deconstruct()\n    new_instance = MyField(*args, **kwargs)\n    self.assertEqual(my_field_instance.some_attribute, new_instance.some_attribute)\n\nChanging a custom field's base class\n------------------------------------\n\nYou can't change the base class of a custom field because Django won't detect\nthe change and make a migration for it. For example, if you start with::\n\n    class CustomCharField(models.CharField):\n        ...\n\nand then decide that you want to use ``TextField`` instead, you can't change\nthe subclass like this::\n\n    class CustomCharField(models.TextField):\n        ...\n\nInstead, you must create a new custom field class and update your models to\nreference it::\n\n    class CustomCharField(models.CharField):\n        ...\n\n    class CustomTextField(models.TextField):\n        ...\n\nAs discussed in :ref:`removing fields <migrations-removing-model-fields>`, you\nmust retain the original ``CustomCharField`` class as long as you have\nmigrations that reference it.\n\nDocumenting your custom field\n-----------------------------\n\nAs always, you should document your field type, so users will know what it is.\nIn addition to providing a docstring for it, which is useful for developers,\nyou can also allow users of the admin app to see a short description of the\nfield type via the :doc:`django.contrib.admindocs\n</ref/contrib/admin/admindocs>` application. To do this provide descriptive\ntext in a :attr:`~Field.description` class attribute of your custom field. In\nthe above example, the description displayed by the ``admindocs`` application\nfor a ``HandField`` will be 'A hand of cards (bridge style)'.\n\nIn the :mod:`django.contrib.admindocs` display, the field description is\ninterpolated with ``field.__dict__`` which allows the description to\nincorporate arguments of the field. For example, the description for\n:class:`~django.db.models.CharField` is::\n\n    description = _(\"String (up to %(max_length)s)\")\n\nUseful methods\n--------------\n\nOnce you've created your :class:`~django.db.models.Field` subclass, you might\nconsider overriding a few standard methods, depending on your field's behavior.\nThe list of methods below is in approximately decreasing order of importance,\nso start from the top.\n\n.. _custom-database-types:\n\nCustom database types\n~~~~~~~~~~~~~~~~~~~~~\n\nSay you've created a PostgreSQL custom type called ``mytype``. You can\nsubclass ``Field`` and implement the :meth:`~Field.db_type` method, like so::\n\n    from django.db import models\n\n    class MytypeField(models.Field):\n        def db_type(self, connection):\n            return 'mytype'\n\nOnce you have ``MytypeField``, you can use it in any model, just like any other\n``Field`` type::\n\n    class Person(models.Model):\n        name = models.CharField(max_length=80)\n        something_else = MytypeField()\n\nIf you aim to build a database-agnostic application, you should account for\ndifferences in database column types. For example, the date/time column type\nin PostgreSQL is called ``timestamp``, while the same column in MySQL is called\n``datetime``. You can handle this in a :meth:`~Field.db_type` method by\nchecking the ``connection.settings_dict['ENGINE']`` attribute.\n\nFor example::\n\n    class MyDateField(models.Field):\n        def db_type(self, connection):\n            if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql':\n                return 'datetime'\n            else:\n                return 'timestamp'\n\nThe :meth:`~Field.db_type` and :meth:`~Field.rel_db_type` methods are called by\nDjango when the framework constructs the ``CREATE TABLE`` statements for your\napplication -- that is, when you first create your tables. The methods are also\ncalled when constructing a ``WHERE`` clause that includes the model field --\nthat is, when you retrieve data using QuerySet methods like ``get()``,\n``filter()``, and ``exclude()`` and have the model field as an argument. They\nare not called at any other time, so it can afford to execute slightly complex\ncode, such as the ``connection.settings_dict`` check in the above example.\n\nSome database column types accept parameters, such as ``CHAR(25)``, where the\nparameter ``25`` represents the maximum column length. In cases like these,\nit's more flexible if the parameter is specified in the model rather than being\nhard-coded in the ``db_type()`` method. For example, it wouldn't make much\nsense to have a ``CharMaxlength25Field``, shown here::\n\n    # This is a silly example of hard-coded parameters.\n    class CharMaxlength25Field(models.Field):\n        def db_type(self, connection):\n            return 'char(25)'\n\n    # In the model:\n    class MyModel(models.Model):\n        # ...\n        my_field = CharMaxlength25Field()\n\nThe better way of doing this would be to make the parameter specifiable at run\ntime -- i.e., when the class is instantiated. To do that, implement\n``Field.__init__()``, like so::\n\n    # This is a much more flexible example.\n    class BetterCharField(models.Field):\n        def __init__(self, max_length, *args, **kwargs):\n            self.max_length = max_length\n            super().__init__(*args, **kwargs)\n\n        def db_type(self, connection):\n            return 'char(%s)' % self.max_length\n\n    # In the model:\n    class MyModel(models.Model):\n        # ...\n        my_field = BetterCharField(25)\n\nFinally, if your column requires truly complex SQL setup, return ``None`` from\n:meth:`.db_type`. This will cause Django's SQL creation code to skip\nover this field. You are then responsible for creating the column in the right\ntable in some other way, but this gives you a way to tell Django to get out of\nthe way.\n\nThe :meth:`~Field.rel_db_type` method is called by fields such as ``ForeignKey``\nand ``OneToOneField`` that point to another field to determine their database\ncolumn data types. For example, if you have an ``UnsignedAutoField``, you also\nneed the foreign keys that point to that field to use the same data type::\n\n    # MySQL unsigned integer (range 0 to 4294967295).\n    class UnsignedAutoField(models.AutoField):\n        def db_type(self, connection):\n            return 'integer UNSIGNED AUTO_INCREMENT'\n\n        def rel_db_type(self, connection):\n            return 'integer UNSIGNED'\n\n.. _converting-values-to-python-objects:\n\nConverting values to Python objects\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf your custom :class:`~Field` class deals with data structures that are more\ncomplex than strings, dates, integers, or floats, then you may need to override\n:meth:`~Field.from_db_value` and :meth:`~Field.to_python`.\n\nIf present for the field subclass, ``from_db_value()`` will be called in all\ncircumstances when the data is loaded from the database, including in\naggregates and :meth:`~django.db.models.query.QuerySet.values` calls.\n\n``to_python()`` is called by deserialization and during the\n:meth:`~django.db.models.Model.clean` method used from forms.\n\nAs a general rule, ``to_python()`` should deal gracefully with any of the\nfollowing arguments:\n\n* An instance of the correct type (e.g., ``Hand`` in our ongoing example).\n\n* A string\n\n* ``None`` (if the field allows ``null=True``)\n\nIn our ``HandField`` class, we're storing the data as a VARCHAR field in the\ndatabase, so we need to be able to process strings and ``None`` in the\n``from_db_value()``. In ``to_python()``, we need to also handle ``Hand``\ninstances::\n\n    import re\n\n    from django.core.exceptions import ValidationError\n    from django.db import models\n    from django.utils.translation import gettext_lazy as _\n\n    def parse_hand(hand_string):\n        \"\"\"Takes a string of cards and splits into a full hand.\"\"\"\n        p1 = re.compile('.{26}')\n        p2 = re.compile('..')\n        args = [p2.findall(x) for x in p1.findall(hand_string)]\n        if len(args) != 4:\n            raise ValidationError(_(\"Invalid input for a Hand instance\"))\n        return Hand(*args)\n\n    class HandField(models.Field):\n        # ...\n\n        def from_db_value(self, value, expression, connection):\n            if value is None:\n                return value\n            return parse_hand(value)\n\n        def to_python(self, value):\n            if isinstance(value, Hand):\n                return value\n\n            if value is None:\n                return value\n\n            return parse_hand(value)\n\nNotice that we always return a ``Hand`` instance from these methods. That's the\nPython object type we want to store in the model's attribute.\n\nFor ``to_python()``, if anything goes wrong during value conversion, you should\nraise a :exc:`~django.core.exceptions.ValidationError` exception.\n\n.. _converting-python-objects-to-query-values:\n\nConverting Python objects to query values\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nSince using a database requires conversion in both ways, if you override\n:meth:`~Field.to_python` you also have to override :meth:`~Field.get_prep_value`\nto convert Python objects back to query values.\n\nFor example::\n\n    class HandField(models.Field):\n        # ...\n\n        def get_prep_value(self, value):\n            return ''.join([''.join(l) for l in (value.north,\n                    value.east, value.south, value.west)])\n\n.. warning::\n\n    If your custom field uses the ``CHAR``, ``VARCHAR`` or ``TEXT``\n    types for MySQL, you must make sure that :meth:`.get_prep_value`\n    always returns a string type. MySQL performs flexible and unexpected\n    matching when a query is performed on these types and the provided\n    value is an integer, which can cause queries to include unexpected\n    objects in their results. This problem cannot occur if you always\n    return a string type from :meth:`.get_prep_value`.\n\n.. _converting-query-values-to-database-values:\n\nConverting query values to database values\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nSome data types (for example, dates) need to be in a specific format\nbefore they can be used by a database backend.\n:meth:`~Field.get_db_prep_value` is the method where those conversions should\nbe made. The specific connection that will be used for the query is\npassed as the ``connection`` parameter. This allows you to use\nbackend-specific conversion logic if it is required.\n\nFor example, Django uses the following method for its\n:class:`BinaryField`::\n\n    def get_db_prep_value(self, value, connection, prepared=False):\n        value = super().get_db_prep_value(value, connection, prepared)\n        if value is not None:\n            return connection.Database.Binary(value)\n        return value\n\nIn case your custom field needs a special conversion when being saved that is\nnot the same as the conversion used for normal query parameters, you can\noverride :meth:`~Field.get_db_prep_save`.\n\n.. _preprocessing-values-before-saving:\n\nPreprocessing values before saving\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf you want to preprocess the value just before saving, you can use\n:meth:`~Field.pre_save`. For example, Django's\n:class:`~django.db.models.DateTimeField` uses this method to set the attribute\ncorrectly in the case of :attr:`~django.db.models.DateField.auto_now` or\n:attr:`~django.db.models.DateField.auto_now_add`.\n\nIf you do override this method, you must return the value of the attribute at\nthe end. You should also update the model's attribute if you make any changes\nto the value so that code holding references to the model will always see the\ncorrect value.\n\n.. _specifying-form-field-for-model-field:\n\nSpecifying the form field for a model field\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nTo customize the form field used by :class:`~django.forms.ModelForm`, you can\noverride :meth:`~Field.formfield`.\n\nThe form field class can be specified via the ``form_class`` and\n``choices_form_class`` arguments; the latter is used if the field has choices\nspecified, the former otherwise. If these arguments are not provided,\n:class:`~django.forms.CharField` or :class:`~django.forms.TypedChoiceField`\nwill be used.\n\nAll of the ``kwargs`` dictionary is passed directly to the form field's\n``__init__()`` method. Normally, all you need to do is set up a good default\nfor the ``form_class`` (and maybe ``choices_form_class``) argument and then\ndelegate further handling to the parent class. This might require you to write\na custom form field (and even a form widget). See the :doc:`forms documentation\n</topics/forms/index>` for information about this.\n\nContinuing our ongoing example, we can write the :meth:`~Field.formfield` method\nas::\n\n    class HandField(models.Field):\n        # ...\n\n        def formfield(self, **kwargs):\n            # This is a fairly standard way to set up some defaults\n            # while letting the caller override them.\n            defaults = {'form_class': MyFormField}\n            defaults.update(kwargs)\n            return super().formfield(**defaults)\n\nThis assumes we've imported a ``MyFormField`` field class (which has its own\ndefault widget). This document doesn't cover the details of writing custom form\nfields.\n\n.. _helper functions: ../forms/#generating-forms-for-models\n.. _forms documentation: ../forms/\n\n.. _emulating-built-in-field-types:\n\nEmulating built-in field types\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf you have created a :meth:`.db_type` method, you don't need to worry about\n:meth:`.get_internal_type` -- it won't be used much. Sometimes, though, your\ndatabase storage is similar in type to some other field, so you can use that\nother field's logic to create the right column.\n\nFor example::\n\n    class HandField(models.Field):\n        # ...\n\n        def get_internal_type(self):\n            return 'CharField'\n\nNo matter which database backend we are using, this will mean that\n:djadmin:`migrate` and other SQL commands create the right column type for\nstoring a string.\n\nIf :meth:`.get_internal_type` returns a string that is not known to Django for\nthe database backend you are using -- that is, it doesn't appear in\n``django.db.backends.<db_name>.base.DatabaseWrapper.data_types`` -- the string\nwill still be used by the serializer, but the default :meth:`~Field.db_type`\nmethod will return ``None``. See the documentation of :meth:`~Field.db_type`\nfor reasons why this might be useful. Putting a descriptive string in as the\ntype of the field for the serializer is a useful idea if you're ever going to\nbe using the serializer output in some other place, outside of Django.\n\n.. _converting-model-field-to-serialization:\n\nConverting field data for serialization\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nTo customize how the values are serialized by a serializer, you can override\n:meth:`~Field.value_to_string`. Using :meth:`~Field.value_from_object` is the\nbest way to get the field's value prior to serialization. For example, since\n``HandField`` uses strings for its data storage anyway, we can reuse some\nexisting conversion code::\n\n    class HandField(models.Field):\n        # ...\n\n        def value_to_string(self, obj):\n            value = self.value_from_object(obj)\n            return self.get_prep_value(value)\n\nSome general advice\n-------------------\n\nWriting a custom field can be a tricky process, particularly if you're doing\ncomplex conversions between your Python types and your database and\nserialization formats. Here are a couple of tips to make things go more\nsmoothly:\n\n#. Look at the existing Django fields (in\n   :file:`django/db/models/fields/__init__.py`) for inspiration. Try to find\n   a field that's similar to what you want and extend it a little bit,\n   instead of creating an entirely new field from scratch.\n\n#. Put a ``__str__()`` method on the class you're wrapping up as a field. There\n   are a lot of places where the default behavior of the field code is to call\n   ``str()`` on the value. (In our examples in this document, ``value`` would\n   be a ``Hand`` instance, not a ``HandField``). So if your ``__str__()``\n   method automatically converts to the string form of your Python object, you\n   can save yourself a lot of work.\n\nWriting a ``FileField`` subclass\n================================\n\nIn addition to the above methods, fields that deal with files have a few other\nspecial requirements which must be taken into account. The majority of the\nmechanics provided by ``FileField``, such as controlling database storage and\nretrieval, can remain unchanged, leaving subclasses to deal with the challenge\nof supporting a particular type of file.\n\nDjango provides a ``File`` class, which is used as a proxy to the file's\ncontents and operations. This can be subclassed to customize how the file is\naccessed, and what methods are available. It lives at\n``django.db.models.fields.files``, and its default behavior is explained in the\n:doc:`file documentation </ref/files/file>`.\n\nOnce a subclass of ``File`` is created, the new ``FileField`` subclass must be\ntold to use it. To do so, assign the new ``File`` subclass to the special\n``attr_class`` attribute of the ``FileField`` subclass.\n\nA few suggestions\n-----------------\n\nIn addition to the above details, there are a few guidelines which can greatly\nimprove the efficiency and readability of the field's code.\n\n#. The source for Django's own ``ImageField`` (in\n   ``django/db/models/fields/files.py``) is a great example of how to\n   subclass ``FileField`` to support a particular type of file, as it\n   incorporates all of the techniques described above.\n\n#. Cache file attributes wherever possible. Since files may be stored in\n   remote storage systems, retrieving them may cost extra time, or even\n   money, that isn't always necessary. Once a file is retrieved to obtain\n   some data about its content, cache as much of that data as possible to\n   reduce the number of times the file must be retrieved on subsequent\n   calls for that information.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":211,"nodeType":"TextFile","repoName":null,"name":"gunicorn.txt","path":"docs/howto/deployment/wsgi","text":"===============================\nHow to use Django with Gunicorn\n===============================\n\n.. highlight:: bash\n\nGunicorn_ ('Green Unicorn') is a pure-Python WSGI server for UNIX. It has no\ndependencies and can be installed using ``pip``.\n\n.. _Gunicorn: https://gunicorn.org/\n\nInstalling Gunicorn\n===================\n\nInstall gunicorn by running ``python -m pip install gunicorn``. For more\ndetails, see the `gunicorn documentation`_.\n\n.. _gunicorn documentation: https://docs.gunicorn.org/en/latest/install.html\n\nRunning Django in Gunicorn as a generic WSGI application\n========================================================\n\nWhen Gunicorn is installed, a ``gunicorn`` command is available which starts\nthe Gunicorn server process. The simplest invocation of gunicorn is to pass the\nlocation of a module containing a WSGI application object named\n``application``, which for a typical Django project would look like::\n\n    gunicorn myproject.wsgi\n\nThis will start one process running one thread listening on ``127.0.0.1:8000``.\nIt requires that your project be on the Python path; the simplest way to ensure\nthat is to run this command from the same directory as your ``manage.py`` file.\n\nSee Gunicorn's `deployment documentation`_ for additional tips.\n\n.. _deployment documentation: https://docs.gunicorn.org/en/latest/deploy.html\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":212,"nodeType":"TextFile","repoName":null,"name":"uwsgi.txt","path":"docs/howto/deployment/wsgi","text":"============================\nHow to use Django with uWSGI\n============================\n\n.. highlight:: bash\n\nuWSGI_ is a fast, self-healing and developer/sysadmin-friendly application\ncontainer server coded in pure C.\n\n.. _uWSGI: https://uwsgi-docs.readthedocs.io/\n\n.. seealso::\n\n    The uWSGI docs offer a `tutorial`_ covering Django, nginx, and uWSGI (one\n    possible deployment setup of many). The docs below are focused on how to\n    integrate Django with uWSGI.\n\n    .. _tutorial: https://uwsgi.readthedocs.io/en/latest/tutorials/Django_and_nginx.html\n\nPrerequisite: uWSGI\n===================\n\nThe uWSGI wiki describes several `installation procedures`_. Using pip, the\nPython package manager, you can install any uWSGI version with a single\ncommand. For example:\n\n.. code-block:: console\n\n    # Install current stable version.\n    $ python -m pip install uwsgi\n\n    # Or install LTS (long term support).\n    $ python -m pip install https://projects.unbit.it/downloads/uwsgi-lts.tar.gz\n\n.. _installation procedures: https://uwsgi-docs.readthedocs.io/en/latest/Install.html\n\nuWSGI model\n-----------\n\nuWSGI operates on a client-server model. Your Web server (e.g., nginx, Apache)\ncommunicates with a ``django-uwsgi`` \"worker\" process to serve dynamic content.\n\nConfiguring and starting the uWSGI server for Django\n----------------------------------------------------\n\nuWSGI supports multiple ways to configure the process. See uWSGI's\n`configuration documentation`_.\n\n.. _configuration documentation: https://uwsgi.readthedocs.io/en/latest/Configuration.html\n\nHere's an example command to start a uWSGI server::\n\n    uwsgi --chdir=/path/to/your/project \\\n        --module=mysite.wsgi:application \\\n        --env DJANGO_SETTINGS_MODULE=mysite.settings \\\n        --master --pidfile=/tmp/project-master.pid \\\n        --socket=127.0.0.1:49152 \\      # can also be a file\n        --processes=5 \\                 # number of worker processes\n        --uid=1000 --gid=2000 \\         # if root, uwsgi can drop privileges\n        --harakiri=20 \\                 # respawn processes taking more than 20 seconds\n        --max-requests=5000 \\           # respawn processes after serving 5000 requests\n        --vacuum \\                      # clear environment on exit\n        --home=/path/to/virtual/env \\   # optional path to a virtualenv\n        --daemonize=/var/log/uwsgi/yourproject.log      # background the process\n\nThis assumes you have a top-level project package named ``mysite``, and\nwithin it a module :file:`mysite/wsgi.py` that contains a WSGI ``application``\nobject. This is the layout you'll have if you ran ``django-admin\nstartproject mysite`` (using your own project name in place of ``mysite``) with\na recent version of Django. If this file doesn't exist, you'll need to create\nit. See the :doc:`/howto/deployment/wsgi/index` documentation for the default\ncontents you should put in this file and what else you can add to it.\n\nThe Django-specific options here are:\n\n* ``chdir``: The path to the directory that needs to be on Python's import\n  path -- i.e., the directory containing the ``mysite`` package.\n* ``module``: The WSGI module to use -- probably the ``mysite.wsgi`` module\n  that :djadmin:`startproject` creates.\n* ``env``: Should probably contain at least :envvar:`DJANGO_SETTINGS_MODULE`.\n* ``home``: Optional path to your project virtualenv.\n\nExample ini configuration file::\n\n    [uwsgi]\n    chdir=/path/to/your/project\n    module=mysite.wsgi:application\n    master=True\n    pidfile=/tmp/project-master.pid\n    vacuum=True\n    max-requests=5000\n    daemonize=/var/log/uwsgi/yourproject.log\n\nExample ini configuration file usage::\n\n    uwsgi --ini uwsgi.ini\n\n.. admonition:: Fixing ``UnicodeEncodeError`` for file uploads\n\n    If you get a ``UnicodeEncodeError`` when uploading files with file names\n    that contain non-ASCII characters, make sure uWSGI is configured to accept\n    non-ASCII file names by adding this to your ``uwsgi.ini``::\n\n        env = LANG=en_US.UTF-8\n\n    See the :ref:`unicode-files` section of the Unicode reference guide for\n    details.\n\nSee the uWSGI docs on `managing the uWSGI process`_ for information on\nstarting, stopping and reloading the uWSGI workers.\n\n.. _managing the uWSGI process: https://uwsgi-docs.readthedocs.io/en/latest/Management.html\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":213,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/howto/deployment/wsgi","text":"=======================\nHow to deploy with WSGI\n=======================\n\nDjango's primary deployment platform is WSGI_, the Python standard for web\nservers and applications.\n\n.. _WSGI: https://wsgi.readthedocs.io/en/latest/\n\nDjango's :djadmin:`startproject` management command sets up a minimal default\nWSGI configuration for you, which you can tweak as needed for your project,\nand direct any WSGI-compliant application server to use.\n\nDjango includes getting-started documentation for the following WSGI servers:\n\n.. toctree::\n   :maxdepth: 1\n\n   gunicorn\n   uwsgi\n   modwsgi\n   apache-auth\n\nThe ``application`` object\n==========================\n\nThe key concept of deploying with WSGI is the ``application`` callable which\nthe application server uses to communicate with your code. It's commonly\nprovided as an object named ``application`` in a Python module accessible to\nthe server.\n\nThe :djadmin:`startproject` command creates a file\n:file:`<project_name>/wsgi.py` that contains such an ``application`` callable.\n\nIt's used both by Django's development server and in production WSGI\ndeployments.\n\nWSGI servers obtain the path to the ``application`` callable from their\nconfiguration. Django's built-in server, namely the :djadmin:`runserver`\ncommand, reads it from the :setting:`WSGI_APPLICATION` setting. By default, it's\nset to ``<project_name>.wsgi.application``, which points to the ``application``\ncallable in :file:`<project_name>/wsgi.py`.\n\nConfiguring the settings module\n===============================\n\nWhen the WSGI server loads your application, Django needs to import the\nsettings module — that's where your entire application is defined.\n\nDjango uses the :envvar:`DJANGO_SETTINGS_MODULE` environment variable to\nlocate the appropriate settings module. It must contain the dotted path to the\nsettings module. You can use a different value for development and production;\nit all depends on how you organize your settings.\n\nIf this variable isn't set, the default :file:`wsgi.py` sets it to\n``mysite.settings``, where ``mysite`` is the name of your project. That's how\n:djadmin:`runserver` discovers the default settings file by default.\n\n.. note::\n\n    Since environment variables are process-wide, this doesn't work when you\n    run multiple Django sites in the same process. This happens with mod_wsgi.\n\n    To avoid this problem, use mod_wsgi's daemon mode with each site in its\n    own daemon process, or override the value from the environment by\n    enforcing ``os.environ[\"DJANGO_SETTINGS_MODULE\"] = \"mysite.settings\"`` in\n    your :file:`wsgi.py`.\n\n\nApplying WSGI middleware\n========================\n\nTo apply :pep:`WSGI middleware\n<3333#middleware-components-that-play-both-sides>` you can wrap the application\nobject. For instance you could add these lines at the bottom of\n:file:`wsgi.py`::\n\n    from helloworld.wsgi import HelloWorldApplication\n    application = HelloWorldApplication(application)\n\nYou could also replace the Django WSGI application with a custom WSGI\napplication that later delegates to the Django WSGI application, if you want\nto combine a Django application with a WSGI application of another framework.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":214,"nodeType":"TextFile","repoName":null,"name":"apache-auth.txt","path":"docs/howto/deployment/wsgi","text":"=========================================================\nAuthenticating against Django's user database from Apache\n=========================================================\n\nSince keeping multiple authentication databases in sync is a common problem when\ndealing with Apache, you can configure Apache to authenticate against Django's\n:doc:`authentication system </topics/auth/index>` directly. This requires Apache\nversion >= 2.2 and mod_wsgi >= 2.0. For example, you could:\n\n* Serve static/media files directly from Apache only to authenticated users.\n\n* Authenticate access to a Subversion_ repository against Django users with\n  a certain permission.\n\n* Allow certain users to connect to a WebDAV share created with mod_dav_.\n\n.. note::\n    If you have installed a :ref:`custom user model <auth-custom-user>` and\n    want to use this default auth handler, it must support an ``is_active``\n    attribute. If you want to use group based authorization, your custom user\n    must have a relation named 'groups', referring to a related object that has\n    a 'name' field. You can also specify your own custom mod_wsgi\n    auth handler if your custom cannot conform to these requirements.\n\n.. _Subversion: https://subversion.apache.org/\n.. _mod_dav: https://httpd.apache.org/docs/2.2/mod/mod_dav.html\n\nAuthentication with ``mod_wsgi``\n================================\n\n.. note::\n\n    The use of ``WSGIApplicationGroup %{GLOBAL}`` in the configurations below\n    presumes that your Apache instance is running only one Django application.\n    If you are running more than one Django application, please refer to the\n    `Defining Application Groups`_ section of the mod_wsgi docs for more\n    information about this setting.\n\nMake sure that mod_wsgi is installed and activated and that you have\nfollowed the steps to setup :doc:`Apache with mod_wsgi\n</howto/deployment/wsgi/modwsgi>`.\n\nNext, edit your Apache configuration to add a location that you want\nonly authenticated users to be able to view:\n\n.. code-block:: apache\n\n    WSGIScriptAlias / /path/to/mysite.com/mysite/wsgi.py\n    WSGIPythonPath /path/to/mysite.com\n\n    WSGIProcessGroup %{GLOBAL}\n    WSGIApplicationGroup %{GLOBAL}\n\n    <Location \"/secret\">\n        AuthType Basic\n        AuthName \"Top Secret\"\n        Require valid-user\n        AuthBasicProvider wsgi\n        WSGIAuthUserScript /path/to/mysite.com/mysite/wsgi.py\n    </Location>\n\nThe ``WSGIAuthUserScript`` directive tells mod_wsgi to execute the\n``check_password`` function in specified wsgi script, passing the user name and\npassword that it receives from the prompt. In this example, the\n``WSGIAuthUserScript`` is the same as the ``WSGIScriptAlias`` that defines your\napplication :doc:`that is created by django-admin startproject\n</howto/deployment/wsgi/index>`.\n\n.. admonition:: Using Apache 2.2 with authentication\n\n    Make sure that ``mod_auth_basic`` and ``mod_authz_user`` are loaded.\n\n    These might be compiled statically into Apache, or you might need to use\n    LoadModule to load them dynamically in your ``httpd.conf``:\n\n    .. code-block:: apache\n\n        LoadModule auth_basic_module modules/mod_auth_basic.so\n        LoadModule authz_user_module modules/mod_authz_user.so\n\nFinally, edit your WSGI script ``mysite.wsgi`` to tie Apache's authentication\nto your site's authentication mechanisms by importing the ``check_password``\nfunction::\n\n    import os\n\n    os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'\n\n    from django.contrib.auth.handlers.modwsgi import check_password\n\n    from django.core.handlers.wsgi import WSGIHandler\n    application = WSGIHandler()\n\n\nRequests beginning with ``/secret/`` will now require a user to authenticate.\n\nThe mod_wsgi `access control mechanisms documentation`_ provides additional\ndetails and information about alternative methods of authentication.\n\n.. _Defining Application Groups: https://modwsgi.readthedocs.io/en/develop/user-guides/configuration-guidelines.html#defining-application-groups\n.. _access control mechanisms documentation: https://modwsgi.readthedocs.io/en/develop/user-guides/access-control-mechanisms.html\n\nAuthorization with ``mod_wsgi`` and Django groups\n-------------------------------------------------\n\nmod_wsgi also provides functionality to restrict a particular location to\nmembers of a group.\n\nIn this case, the Apache configuration should look like this:\n\n.. code-block:: apache\n\n    WSGIScriptAlias / /path/to/mysite.com/mysite/wsgi.py\n\n    WSGIProcessGroup %{GLOBAL}\n    WSGIApplicationGroup %{GLOBAL}\n\n    <Location \"/secret\">\n        AuthType Basic\n        AuthName \"Top Secret\"\n        AuthBasicProvider wsgi\n        WSGIAuthUserScript /path/to/mysite.com/mysite/wsgi.py\n        WSGIAuthGroupScript /path/to/mysite.com/mysite/wsgi.py\n        Require group secret-agents\n        Require valid-user\n    </Location>\n\nTo support the ``WSGIAuthGroupScript`` directive, the same WSGI script\n``mysite.wsgi`` must also import the ``groups_for_user`` function which\nreturns a list groups the given user belongs to.\n\n.. code-block:: python\n\n    from django.contrib.auth.handlers.modwsgi import check_password, groups_for_user\n\nRequests for ``/secret/`` will now also require user to be a member of the\n\"secret-agents\" group.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":215,"nodeType":"TextFile","repoName":null,"name":"daphne.txt","path":"docs/howto/deployment/asgi","text":"=============================\nHow to use Django with Daphne\n=============================\n\n.. highlight:: bash\n\nDaphne_ is a pure-Python ASGI server for UNIX, maintained by members of the\nDjango project. It acts as the reference server for ASGI.\n\n.. _Daphne: https://pypi.org/project/daphne/\n\nInstalling Daphne\n===================\n\nYou can install Daphne with ``pip``::\n\n    python -m pip install daphne\n\nRunning Django in Daphne\n========================\n\nWhen Daphne is installed, a ``daphne`` command is available which starts the\nDaphne server process. At its simplest, Daphne needs to be called with the\nlocation of a module containing an ASGI application object, followed by what\nthe application is called (separated by a colon).\n\nFor a typical Django project, invoking Daphne would look like::\n\n    daphne myproject.asgi:application\n\nThis will start one process listening on ``127.0.0.1:8000``. It requires that\nyour project be on the Python path; to ensure that run this command from the\nsame directory as your ``manage.py`` file.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":216,"nodeType":"TextFile","repoName":null,"name":"contributing.txt","path":"docs/intro","text":"===================================\nWriting your first patch for Django\n===================================\n\nIntroduction\n============\n\nInterested in giving back to the community a little? Maybe you've found a bug\nin Django that you'd like to see fixed, or maybe there's a small feature you\nwant added.\n\nContributing back to Django itself is the best way to see your own concerns\naddressed. This may seem daunting at first, but it's a well-traveled path with\ndocumentation, tooling, and a community to support you. We'll walk you through\nthe entire process, so you can learn by example.\n\nWho's this tutorial for?\n------------------------\n\n.. seealso::\n\n    If you are looking for a reference on how to submit patches, see the\n    :doc:`/internals/contributing/writing-code/submitting-patches`\n    documentation.\n\nFor this tutorial, we expect that you have at least a basic understanding of\nhow Django works. This means you should be comfortable going through the\nexisting tutorials on :doc:`writing your first Django app</intro/tutorial01>`.\nIn addition, you should have a good understanding of Python itself. But if you\ndon't, `Dive Into Python`__ is a fantastic (and free) online book for\nbeginning Python programmers.\n\nThose of you who are unfamiliar with version control systems and Trac will find\nthat this tutorial and its links include just enough information to get started.\nHowever, you'll probably want to read some more about these different tools if\nyou plan on contributing to Django regularly.\n\nFor the most part though, this tutorial tries to explain as much as possible,\nso that it can be of use to the widest audience.\n\n.. admonition:: Where to get help:\n\n    If you're having trouble going through this tutorial, please post a message\n    to |django-developers| or drop by `#django-dev on irc.freenode.net`__ to\n    chat with other Django users who might be able to help.\n\n__ https://diveinto.org/python3/table-of-contents.html\n__ https://webchat.freenode.net/#django-dev\n\nWhat does this tutorial cover?\n------------------------------\n\nWe'll be walking you through contributing a patch to Django for the first time.\nBy the end of this tutorial, you should have a basic understanding of both the\ntools and the processes involved. Specifically, we'll be covering the following:\n\n* Installing Git.\n* Downloading a copy of Django's development version.\n* Running Django's test suite.\n* Writing a test for your patch.\n* Writing the code for your patch.\n* Testing your patch.\n* Submitting a pull request.\n* Where to look for more information.\n\nOnce you're done with the tutorial, you can look through the rest of\n:doc:`Django's documentation on contributing</internals/contributing/index>`.\nIt contains lots of great information and is a must read for anyone who'd like\nto become a regular contributor to Django. If you've got questions, it's\nprobably got the answers.\n\n.. admonition:: Python 3 required!\n\n    The current version of Django doesn't support Python 2.7. Get Python 3 at\n    `Python's download page <https://www.python.org/downloads/>`_ or with your\n    operating system's package manager.\n\n.. admonition:: For Windows users\n\n    When installing Python on Windows, make sure you check the option \"Add\n    python.exe to Path\", so that it is always available on the command line.\n\nCode of Conduct\n===============\n\nAs a contributor, you can help us keep the Django community open and inclusive.\nPlease read and follow our `Code of Conduct <https://www.djangoproject.com/conduct/>`_.\n\nInstalling Git\n==============\n\nFor this tutorial, you'll need Git installed to download the current\ndevelopment version of Django and to generate patch files for the changes you\nmake.\n\nTo check whether or not you have Git installed, enter ``git`` into the command\nline. If you get messages saying that this command could not be found, you'll\nhave to download and install it, see `Git's download page`__.\n\nIf you're not that familiar with Git, you can always find out more about its\ncommands (once it's installed) by typing ``git help`` into the command line.\n\n__ https://git-scm.com/download\n\nGetting a copy of Django's development version\n==============================================\n\nThe first step to contributing to Django is to get a copy of the source code.\nFirst, `fork Django on GitHub <https://github.com/django/django/fork>`__. Then,\nfrom the command line, use the ``cd`` command to navigate to the directory\nwhere you'll want your local copy of Django to live.\n\nDownload the Django source code repository using the following command:\n\n.. console::\n\n    $ git clone https://github.com/YourGitHubName/django.git\n\n.. admonition:: Low bandwidth connection?\n\n    You can add the ``--depth 1`` argument to ``git clone`` to skip downloading\n    all of Django's commit history, which reduces data transfer from  ~250 MB\n    to ~70 MB.\n\nNow that you have a local copy of Django, you can install it just like you would\ninstall any package using ``pip``. The most convenient way to do so is by using\na *virtual environment*, which is a feature built into Python that allows you\nto keep a separate directory of installed packages for each of your projects so\nthat they don't interfere with each other.\n\nIt's a good idea to keep all your virtual environments in one place, for\nexample in ``.virtualenvs/`` in your home directory.\n\nCreate a new virtual environment by running:\n\n.. console::\n\n    $ python3 -m venv ~/.virtualenvs/djangodev\n\nThe path is where the new environment will be saved on your computer.\n\nThe final step in setting up your virtual environment is to activate it:\n\n.. code-block:: console\n\n    $ source ~/.virtualenvs/djangodev/bin/activate\n\nIf the ``source`` command is not available, you can try using a dot instead:\n\n.. code-block:: console\n\n    $ . ~/.virtualenvs/djangodev/bin/activate\n\nYou have to activate the virtual environment whenever you open a new\nterminal window. virtualenvwrapper__ is a useful tool for making this\nmore convenient.\n\n.. admonition:: For Windows users\n\n    To activate your virtual environment on Windows, run:\n\n    .. code-block:: doscon\n\n        ...\\> %HOMEPATH%\\.virtualenvs\\djangodev\\Scripts\\activate.bat\n\n    or you can install :ref:`a Windows version of virtualenvwrapper\n    <virtualenvwrapper-win>` and then use:\n\n    .. code-block:: doscon\n\n        ...\\> workon djangodev\n\n__ https://virtualenvwrapper.readthedocs.io/en/latest/\n\nThe name of the currently activated virtual environment is displayed on the\ncommand line to help you keep track of which one you are using. Anything you\ninstall through ``pip`` while this name is displayed will be installed in that\nvirtual environment, isolated from other environments and system-wide packages.\n\n.. _intro-contributing-install-local-copy:\n\nGo ahead and install the previously cloned copy of Django:\n\n.. console::\n\n    $ python -m pip install -e /path/to/your/local/clone/django/\n\nThe installed version of Django is now pointing at your local copy by installing\nin editable mode. You will immediately see any changes you make to it, which is\nof great help when writing your first patch.\n\nCreating projects with a local copy of Django\n---------------------------------------------\n\nIt may be helpful to test your local changes with a Django project. First you\nhave to create a new virtual environment, :ref:`install the previously cloned\nlocal copy of Django in editable mode <intro-contributing-install-local-copy>`,\nand create a new Django project outside of your local copy of Django. You will\nimmediately see any changes you make to Django in your new project, which is\nof great help when writing your first patch.\n\nRunning Django's test suite for the first time\n==============================================\n\nWhen contributing to Django it's very important that your code changes don't\nintroduce bugs into other areas of Django. One way to check that Django still\nworks after you make your changes is by running Django's test suite. If all\nthe tests still pass, then you can be reasonably sure that your changes\nwork and haven't broken other parts of Django. If you've never run Django's test\nsuite before, it's a good idea to run it once beforehand to get familiar with\nits output.\n\nBefore running the test suite, install its dependencies by ``cd``-ing into the\nDjango ``tests/`` directory and then running:\n\n.. console::\n\n    $ python -m pip install -r requirements/py3.txt\n\nIf you encounter an error during the installation, your system might be missing\na dependency for one or more of the Python packages. Consult the failing\npackage's documentation or search the Web with the error message that you\nencounter.\n\nNow we are ready to run the test suite. If you're using GNU/Linux, macOS, or\nsome other flavor of Unix, run:\n\n.. console::\n\n    $ ./runtests.py\n\nNow sit back and relax. Django's entire test suite has thousands of tests, and\nit takes at least a few minutes to run, depending on the speed of your\ncomputer.\n\nWhile Django's test suite is running, you'll see a stream of characters\nrepresenting the status of each test as it completes. ``E`` indicates that an\nerror was raised during a test, and ``F`` indicates that a test's assertions\nfailed. Both of these are considered to be test failures. Meanwhile, ``x`` and\n``s`` indicated expected failures and skipped tests, respectively. Dots indicate\npassing tests.\n\nSkipped tests are typically due to missing external libraries required to run\nthe test; see :ref:`running-unit-tests-dependencies` for a list of dependencies\nand be sure to install any for tests related to the changes you are making (we\nwon't need any for this tutorial). Some tests are specific to a particular\ndatabase backend and will be skipped if not testing with that backend. SQLite\nis the database backend for the default settings. To run the tests using a\ndifferent backend, see :ref:`running-unit-tests-settings`.\n\nOnce the tests complete, you should be greeted with a message informing you\nwhether the test suite passed or failed. Since you haven't yet made any changes\nto Django's code, the entire test suite **should** pass. If you get failures or\nerrors make sure you've followed all of the previous steps properly. See\n:ref:`running-unit-tests` for more information.\n\nNote that the latest Django master may not always be stable. When developing\nagainst master, you can check `Django's continuous integration builds`__ to\ndetermine if the failures are specific to your machine or if they are also\npresent in Django's official builds. If you click to view a particular build,\nyou can view the \"Configuration Matrix\" which shows failures broken down by\nPython version and database backend.\n\n__ https://djangoci.com\n\n.. note::\n\n    For this tutorial and the ticket we're working on, testing against SQLite\n    is sufficient, however, it's possible (and sometimes necessary) to\n    :ref:`run the tests using a different database\n    <running-unit-tests-settings>`.\n\nWorking on a feature\n====================\n\nFor this tutorial, we'll work on a \"fake ticket\" as a case study. Here are the\nimaginary details:\n\n.. admonition:: Ticket #99999 -- Allow making toast\n\n    Django should provide a function ``django.shortcuts.make_toast()`` that\n    returns ``'toast'``.\n\nWe'll now implement this feature and associated tests.\n\nCreating a branch for your patch\n================================\n\nBefore making any changes, create a new branch for the ticket:\n\n.. console::\n\n    $ git checkout -b ticket_99999\n\nYou can choose any name that you want for the branch, \"ticket_99999\" is an\nexample. All changes made in this branch will be specific to the ticket and\nwon't affect the main copy of the code that we cloned earlier.\n\nWriting some tests for your ticket\n==================================\n\nIn most cases, for a patch to be accepted into Django it has to include tests.\nFor bug fix patches, this means writing a regression test to ensure that the\nbug is never reintroduced into Django later on. A regression test should be\nwritten in such a way that it will fail while the bug still exists and pass\nonce the bug has been fixed. For patches containing new features, you'll need\nto include tests which ensure that the new features are working correctly.\nThey too should fail when the new feature is not present, and then pass once it\nhas been implemented.\n\nA good way to do this is to write your new tests first, before making any\nchanges to the code. This style of development is called\n`test-driven development`__ and can be applied to both entire projects and\nsingle patches. After writing your tests, you then run them to make sure that\nthey do indeed fail (since you haven't fixed that bug or added that feature\nyet). If your new tests don't fail, you'll need to fix them so that they do.\nAfter all, a regression test that passes regardless of whether a bug is present\nis not very helpful at preventing that bug from reoccurring down the road.\n\nNow for our hands-on example.\n\n__ https://en.wikipedia.org/wiki/Test-driven_development\n\nWriting a test for ticket #99999\n--------------------------------\n\nIn order to resolve this ticket, we'll add a ``make_toast()`` function to the\ntop-level ``django`` module. First we are going to write a test that tries to\nuse the function and check that its output looks correct.\n\nNavigate to Django's ``tests/shortcuts/`` folder and create a new file\n``test_make_toast.py``. Add the following code::\n\n    from django.shortcuts import make_toast\n    from django.test import SimpleTestCase\n\n\n    class MakeToastTests(SimpleTestCase):\n        def test_make_toast(self):\n            self.assertEqual(make_toast(), 'toast')\n\nThis test checks that the ``make_toast()`` returns ``'toast'``.\n\n.. admonition:: But this testing thing looks kinda hard...\n\n    If you've never had to deal with tests before, they can look a little hard\n    to write at first glance. Fortunately, testing is a *very* big subject in\n    computer programming, so there's lots of information out there:\n\n    * A good first look at writing tests for Django can be found in the\n      documentation on :doc:`/topics/testing/overview`.\n    * Dive Into Python (a free online book for beginning Python developers)\n      includes a great `introduction to Unit Testing`__.\n    * After reading those, if you want something a little meatier to sink\n      your teeth into, there's always the Python :mod:`unittest` documentation.\n\n__ https://www.diveinto.org/python3/unit-testing.html\n\nRunning your new test\n---------------------\n\nSince we haven't made any modifications to ``django.shortcuts`` yet, our test\nshould fail. Let's run all the tests in the ``shortcuts`` folder to make sure\nthat's really what happens. ``cd`` to the Django ``tests/`` directory and run:\n\n.. console::\n\n    $ ./runtests.py shortcuts\n\nIf the tests ran correctly, you should see one failure corresponding to the test\nmethod we added, with this error::\n\n    ImportError: cannot import name 'make_toast' from 'django.shortcuts'\n\nIf all of the tests passed, then you'll want to make sure that you added the\nnew test shown above to the appropriate folder and file name.\n\nWriting the code for your ticket\n================================\n\nNext we'll be adding the ``make_toast()`` function.\n\nNavigate to the ``django/`` folder and open the ``shortcuts.py`` file. At the\nbottom, add::\n\n    def make_toast():\n        return 'toast'\n\nNow we need to make sure that the test we wrote earlier passes, so we can see\nwhether the code we added is working correctly. Again, navigate to the Django\n``tests/`` directory and run:\n\n.. console::\n\n    $ ./runtests.py shortcuts\n\nEverything should pass. If it doesn't, make sure you correctly added the\nfunction to the correct file.\n\nRunning Django's test suite for the second time\n===============================================\n\nOnce you've verified that your patch and your test are working correctly, it's\na good idea to run the entire Django test suite to verify that your change\nhasn't introduced any bugs into other areas of Django. While successfully\npassing the entire test suite doesn't guarantee your code is bug free, it does\nhelp identify many bugs and regressions that might otherwise go unnoticed.\n\nTo run the entire Django test suite, ``cd`` into the Django ``tests/``\ndirectory and run:\n\n.. console::\n\n    $ ./runtests.py\n\nWriting Documentation\n=====================\n\nThis is a new feature, so it should be documented. Open the file\n``docs/topics/http/shortcuts.txt`` and add the following at the end of the\nfile::\n\n    ``make_toast()``\n    ================\n\n    .. versionadded:: 2.2\n\n    Returns ``'toast'``.\n\nSince this new feature will be in an upcoming release it is also added to the\nrelease notes for the next version of Django. Open the release notes for the\nlatest version in ``docs/releases/``, which at time of writing is ``2.2.txt``.\nAdd a note under the \"Minor Features\" header::\n\n    :mod:`django.shortcuts`\n    ~~~~~~~~~~~~~~~~~~~~~~~\n\n    * The new :func:`django.shortcuts.make_toast` function returns ``'toast'``.\n\nFor more information on writing documentation, including an explanation of what\nthe ``versionadded`` bit is all about, see\n:doc:`/internals/contributing/writing-documentation`. That page also includes\nan explanation of how to build a copy of the documentation locally, so you can\npreview the HTML that will be generated.\n\nPreviewing your changes\n=======================\n\nNow it's time to go through all the changes made in our patch. To stage all the\nchanges ready for commit, run:\n\n.. console::\n\n    $ git add --all\n\nThen display the differences between your current copy of Django (with your\nchanges) and the revision that you initially checked out earlier in the\ntutorial with:\n\n.. console::\n\n    $ git diff --cached\n\nUse the arrow keys to move up and down.\n\n.. code-block:: diff\n\n    diff --git a/django/shortcuts.py b/django/shortcuts.py\n    index 7ab1df0e9d..8dde9e28d9 100644\n    --- a/django/shortcuts.py\n    +++ b/django/shortcuts.py\n    @@ -156,3 +156,7 @@ def resolve_url(to, *args, **kwargs):\n\n         # Finally, fall back and assume it's a URL\n         return to\n    +\n    +\n    +def make_toast():\n    +    return 'toast'\n    diff --git a/docs/releases/2.2.txt b/docs/releases/2.2.txt\n    index 7d85d30c4a..81518187b3 100644\n    --- a/docs/releases/2.2.txt\n    +++ b/docs/releases/2.2.txt\n    @@ -40,6 +40,11 @@ database constraints. Constraints are added to models using the\n     Minor features\n     --------------\n\n    +:mod:`django.shortcuts`\n    +~~~~~~~~~~~~~~~~~~~~~~~\n    +\n    +* The new :func:`django.shortcuts.make_toast` function returns ``'toast'``.\n    +\n     :mod:`django.contrib.admin`\n     ~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n    diff --git a/docs/topics/http/shortcuts.txt b/docs/topics/http/shortcuts.txt\n    index 7b3a3a2c00..711bf6bb6d 100644\n    --- a/docs/topics/http/shortcuts.txt\n    +++ b/docs/topics/http/shortcuts.txt\n    @@ -271,3 +271,12 @@ This example is equivalent to::\n             my_objects = list(MyModel.objects.filter(published=True))\n             if not my_objects:\n                 raise Http404(\"No MyModel matches the given query.\")\n    +\n    +``make_toast()``\n    +================\n    +\n    +.. function:: make_toast()\n    +\n    +.. versionadded:: 2.2\n    +\n    +Returns ``'toast'``.\n    diff --git a/tests/shortcuts/test_make_toast.py b/tests/shortcuts/test_make_toast.py\n    new file mode 100644\n    index 0000000000..6f4c627b6e\n    --- /dev/null\n    +++ b/tests/shortcuts/test_make_toast.py\n    @@ -0,0 +1,7 @@\n    +from django.shortcuts import make_toast\n    +from django.test import SimpleTestCase\n    +\n    +\n    +class MakeToastTests(SimpleTestCase):\n    +    def test_make_toast(self):\n    +        self.assertEqual(make_toast(), 'toast')\n\nWhen you're done previewing the patch, hit the ``q`` key to return to the\ncommand line. If the patch's content looked okay, it's time to commit the\nchanges.\n\nCommitting the changes in the patch\n===================================\n\nTo commit the changes:\n\n.. console::\n\n    $ git commit\n\nThis opens up a text editor to type the commit message. Follow the :ref:`commit\nmessage guidelines <committing-guidelines>` and write a message like:\n\n.. code-block:: text\n\n    Fixed #99999 -- Added a shortcut function to make toast.\n\nPushing the commit and making a pull request\n============================================\n\nAfter committing the patch, send it to your fork on GitHub (substitute\n\"ticket_99999\" with the name of your branch if it's different):\n\n.. console::\n\n    $ git push origin ticket_99999\n\nYou can create a pull request by visiting the `Django GitHub page\n<https://github.com/django/django/>`_. You'll see your branch under \"Your\nrecently pushed branches\". Click \"Compare & pull request\" next to it.\n\nPlease don't do it for this tutorial, but on the next page that displays a\npreview of the patch, you would click \"Create pull request\".\n\nNext steps\n==========\n\nCongratulations, you've learned how to make a pull request to Django! Details\nof more advanced techniques you may need are in\n:doc:`/internals/contributing/writing-code/working-with-git`.\n\nNow you can put those skills to good use by helping to improve Django's\ncodebase.\n\nMore information for new contributors\n-------------------------------------\n\nBefore you get too into writing patches for Django, there's a little more\ninformation on contributing that you should probably take a look at:\n\n* You should make sure to read Django's documentation on\n  :doc:`claiming tickets and submitting patches\n  </internals/contributing/writing-code/submitting-patches>`.\n  It covers Trac etiquette, how to claim tickets for yourself, expected\n  coding style for patches, and many other important details.\n* First time contributors should also read Django's :doc:`documentation\n  for first time contributors</internals/contributing/new-contributors/>`.\n  It has lots of good advice for those of us who are new to helping out\n  with Django.\n* After those, if you're still hungry for more information about\n  contributing, you can always browse through the rest of\n  :doc:`Django's documentation on contributing</internals/contributing/index>`.\n  It contains a ton of useful information and should be your first source\n  for answering any questions you might have.\n\nFinding your first real ticket\n------------------------------\n\nOnce you've looked through some of that information, you'll be ready to go out\nand find a ticket of your own to write a patch for. Pay special attention to\ntickets with the \"easy pickings\" criterion. These tickets are often much\nsimpler in nature and are great for first time contributors. Once you're\nfamiliar with contributing to Django, you can move on to writing patches for\nmore difficult and complicated tickets.\n\nIf you just want to get started already (and nobody would blame you!), try\ntaking a look at the list of `easy tickets that need patches`__ and the\n`easy tickets that have patches which need improvement`__. If you're familiar\nwith writing tests, you can also look at the list of\n`easy tickets that need tests`__. Remember to follow the guidelines about\nclaiming tickets that were mentioned in the link to Django's documentation on\n:doc:`claiming tickets and submitting patches\n</internals/contributing/writing-code/submitting-patches>`.\n\n__ https://code.djangoproject.com/query?status=new&status=reopened&has_patch=0&easy=1&col=id&col=summary&col=status&col=owner&col=type&col=milestone&order=priority\n__ https://code.djangoproject.com/query?status=new&status=reopened&needs_better_patch=1&easy=1&col=id&col=summary&col=status&col=owner&col=type&col=milestone&order=priority\n__ https://code.djangoproject.com/query?status=new&status=reopened&needs_tests=1&easy=1&col=id&col=summary&col=status&col=owner&col=type&col=milestone&order=priority\n\nWhat's next after creating a pull request?\n------------------------------------------\n\nAfter a ticket has a patch, it needs to be reviewed by a second set of eyes.\nAfter submitting a pull request, update the ticket metadata by setting the\nflags on the ticket to say \"has patch\", \"doesn't need tests\", etc, so others\ncan find it for review. Contributing doesn't necessarily always mean writing a\npatch from scratch. Reviewing existing patches is also a very helpful\ncontribution. See :doc:`/internals/contributing/triaging-tickets` for details.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":217,"nodeType":"TextFile","repoName":null,"name":"tutorial04.txt","path":"docs/intro","text":"=====================================\nWriting your first Django app, part 4\n=====================================\n\nThis tutorial begins where :doc:`Tutorial 3 </intro/tutorial03>` left off. We're\ncontinuing the Web-poll application and will focus on form processing and\ncutting down our code.\n\n.. admonition:: Where to get help:\n\n    If you're having trouble going through this tutorial, please head over to\n    the :doc:`Getting Help</faq/help>` section of the FAQ.\n\nWrite a minimal form\n====================\n\nLet's update our poll detail template (\"polls/detail.html\") from the last\ntutorial, so that the template contains an HTML ``<form>`` element:\n\n.. code-block:: html+django\n    :caption: polls/templates/polls/detail.html\n\n    <h1>{{ question.question_text }}</h1>\n\n    {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}\n\n    <form action=\"{% url 'polls:vote' question.id %}\" method=\"post\">\n    {% csrf_token %}\n    {% for choice in question.choice_set.all %}\n        <input type=\"radio\" name=\"choice\" id=\"choice{{ forloop.counter }}\" value=\"{{ choice.id }}\">\n        <label for=\"choice{{ forloop.counter }}\">{{ choice.choice_text }}</label><br>\n    {% endfor %}\n    <input type=\"submit\" value=\"Vote\">\n    </form>\n\nA quick rundown:\n\n* The above template displays a radio button for each question choice. The\n  ``value`` of each radio button is the associated question choice's ID. The\n  ``name`` of each radio button is ``\"choice\"``. That means, when somebody\n  selects one of the radio buttons and submits the form, it'll send the\n  POST data ``choice=#`` where # is the ID of the selected choice. This is the\n  basic concept of HTML forms.\n\n* We set the form's ``action`` to ``{% url 'polls:vote' question.id %}``, and we\n  set ``method=\"post\"``. Using ``method=\"post\"`` (as opposed to\n  ``method=\"get\"``) is very important, because the act of submitting this\n  form will alter data server-side. Whenever you create a form that alters\n  data server-side, use ``method=\"post\"``. This tip isn't specific to\n  Django; it's good Web development practice in general.\n\n* ``forloop.counter`` indicates how many times the :ttag:`for` tag has gone\n  through its loop\n\n* Since we're creating a POST form (which can have the effect of modifying\n  data), we need to worry about Cross Site Request Forgeries.\n  Thankfully, you don't have to worry too hard, because Django comes with a\n  helpful system for protecting against it. In short, all POST forms that are\n  targeted at internal URLs should use the :ttag:`{% csrf_token %}<csrf_token>`\n  template tag.\n\nNow, let's create a Django view that handles the submitted data and does\nsomething with it. Remember, in :doc:`Tutorial 3 </intro/tutorial03>`, we\ncreated a URLconf for the polls application that includes this line:\n\n.. code-block:: python\n    :caption: polls/urls.py\n\n    path('<int:question_id>/vote/', views.vote, name='vote'),\n\nWe also created a dummy implementation of the ``vote()`` function. Let's\ncreate a real version. Add the following to ``polls/views.py``:\n\n.. code-block:: python\n    :caption: polls/views.py\n\n    from django.http import HttpResponse, HttpResponseRedirect\n    from django.shortcuts import get_object_or_404, render\n    from django.urls import reverse\n\n    from .models import Choice, Question\n    # ...\n    def vote(request, question_id):\n        question = get_object_or_404(Question, pk=question_id)\n        try:\n            selected_choice = question.choice_set.get(pk=request.POST['choice'])\n        except (KeyError, Choice.DoesNotExist):\n            # Redisplay the question voting form.\n            return render(request, 'polls/detail.html', {\n                'question': question,\n                'error_message': \"You didn't select a choice.\",\n            })\n        else:\n            selected_choice.votes += 1\n            selected_choice.save()\n            # Always return an HttpResponseRedirect after successfully dealing\n            # with POST data. This prevents data from being posted twice if a\n            # user hits the Back button.\n            return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))\n\nThis code includes a few things we haven't covered yet in this tutorial:\n\n* :attr:`request.POST <django.http.HttpRequest.POST>` is a dictionary-like\n  object that lets you access submitted data by key name. In this case,\n  ``request.POST['choice']`` returns the ID of the selected choice, as a\n  string. :attr:`request.POST <django.http.HttpRequest.POST>` values are\n  always strings.\n\n  Note that Django also provides :attr:`request.GET\n  <django.http.HttpRequest.GET>` for accessing GET data in the same way --\n  but we're explicitly using :attr:`request.POST\n  <django.http.HttpRequest.POST>` in our code, to ensure that data is only\n  altered via a POST call.\n\n* ``request.POST['choice']`` will raise :exc:`KeyError` if\n  ``choice`` wasn't provided in POST data. The above code checks for\n  :exc:`KeyError` and redisplays the question form with an error\n  message if ``choice`` isn't given.\n\n* After incrementing the choice count, the code returns an\n  :class:`~django.http.HttpResponseRedirect` rather than a normal\n  :class:`~django.http.HttpResponse`.\n  :class:`~django.http.HttpResponseRedirect` takes a single argument: the\n  URL to which the user will be redirected (see the following point for how\n  we construct the URL in this case).\n\n  As the Python comment above points out, you should always return an\n  :class:`~django.http.HttpResponseRedirect` after successfully dealing with\n  POST data. This tip isn't specific to Django; it's good Web development\n  practice in general.\n\n* We are using the :func:`~django.urls.reverse` function in the\n  :class:`~django.http.HttpResponseRedirect` constructor in this example.\n  This function helps avoid having to hardcode a URL in the view function.\n  It is given the name of the view that we want to pass control to and the\n  variable portion of the URL pattern that points to that view. In this\n  case, using the URLconf we set up in :doc:`Tutorial 3 </intro/tutorial03>`,\n  this :func:`~django.urls.reverse` call will return a string like\n  ::\n\n    '/polls/3/results/'\n\n  where the ``3`` is the value of ``question.id``. This redirected URL will\n  then call the ``'results'`` view to display the final page.\n\nAs mentioned in :doc:`Tutorial 3 </intro/tutorial03>`, ``request`` is an\n:class:`~django.http.HttpRequest` object. For more on\n:class:`~django.http.HttpRequest` objects, see the :doc:`request and\nresponse documentation </ref/request-response>`.\n\nAfter somebody votes in a question, the ``vote()`` view redirects to the results\npage for the question. Let's write that view:\n\n.. code-block:: python\n    :caption: polls/views.py\n\n    from django.shortcuts import get_object_or_404, render\n\n\n    def results(request, question_id):\n        question = get_object_or_404(Question, pk=question_id)\n        return render(request, 'polls/results.html', {'question': question})\n\nThis is almost exactly the same as the ``detail()`` view from :doc:`Tutorial 3\n</intro/tutorial03>`. The only difference is the template name. We'll fix this\nredundancy later.\n\nNow, create a ``polls/results.html`` template:\n\n.. code-block:: html+django\n    :caption: polls/templates/polls/results.html\n\n    <h1>{{ question.question_text }}</h1>\n\n    <ul>\n    {% for choice in question.choice_set.all %}\n        <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>\n    {% endfor %}\n    </ul>\n\n    <a href=\"{% url 'polls:detail' question.id %}\">Vote again?</a>\n\nNow, go to ``/polls/1/`` in your browser and vote in the question. You should see a\nresults page that gets updated each time you vote. If you submit the form\nwithout having chosen a choice, you should see the error message.\n\n.. note::\n    The code for our ``vote()`` view does have a small problem. It first gets\n    the ``selected_choice`` object from the database, then computes the new\n    value of ``votes``, and then saves it back to the database. If two users of\n    your website try to vote at *exactly the same time*, this might go wrong:\n    The same value, let's say 42, will be retrieved for ``votes``. Then, for\n    both users the new value of 43 is computed and saved, but 44 would be the\n    expected value.\n\n    This is called a *race condition*. If you are interested, you can read\n    :ref:`avoiding-race-conditions-using-f` to learn how you can solve this\n    issue.\n\nUse generic views: Less code is better\n======================================\n\nThe ``detail()`` (from :doc:`Tutorial 3 </intro/tutorial03>`) and ``results()``\nviews are very short -- and, as mentioned above, redundant. The ``index()``\nview, which displays a list of polls, is similar.\n\nThese views represent a common case of basic Web development: getting data from\nthe database according to a parameter passed in the URL, loading a template and\nreturning the rendered template. Because this is so common, Django provides a\nshortcut, called the \"generic views\" system.\n\nGeneric views abstract common patterns to the point where you don't even need\nto write Python code to write an app.\n\nLet's convert our poll app to use the generic views system, so we can delete a\nbunch of our own code. We'll have to take a few steps to make the conversion.\nWe will:\n\n#. Convert the URLconf.\n\n#. Delete some of the old, unneeded views.\n\n#. Introduce new views based on Django's generic views.\n\nRead on for details.\n\n.. admonition:: Why the code-shuffle?\n\n    Generally, when writing a Django app, you'll evaluate whether generic views\n    are a good fit for your problem, and you'll use them from the beginning,\n    rather than refactoring your code halfway through. But this tutorial\n    intentionally has focused on writing the views \"the hard way\" until now, to\n    focus on core concepts.\n\n    You should know basic math before you start using a calculator.\n\nAmend URLconf\n-------------\n\nFirst, open the ``polls/urls.py`` URLconf and change it like so:\n\n.. code-block:: python\n    :caption: polls/urls.py\n\n    from django.urls import path\n\n    from . import views\n\n    app_name = 'polls'\n    urlpatterns = [\n        path('', views.IndexView.as_view(), name='index'),\n        path('<int:pk>/', views.DetailView.as_view(), name='detail'),\n        path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),\n        path('<int:question_id>/vote/', views.vote, name='vote'),\n    ]\n\nNote that the name of the matched pattern in the path strings of the second and\nthird patterns has changed from ``<question_id>`` to ``<pk>``.\n\nAmend views\n-----------\n\nNext, we're going to remove our old ``index``, ``detail``, and ``results``\nviews and use Django's generic views instead. To do so, open the\n``polls/views.py`` file and change it like so:\n\n.. code-block:: python\n    :caption: polls/views.py\n\n    from django.http import HttpResponseRedirect\n    from django.shortcuts import get_object_or_404, render\n    from django.urls import reverse\n    from django.views import generic\n\n    from .models import Choice, Question\n\n\n    class IndexView(generic.ListView):\n        template_name = 'polls/index.html'\n        context_object_name = 'latest_question_list'\n\n        def get_queryset(self):\n            \"\"\"Return the last five published questions.\"\"\"\n            return Question.objects.order_by('-pub_date')[:5]\n\n\n    class DetailView(generic.DetailView):\n        model = Question\n        template_name = 'polls/detail.html'\n\n\n    class ResultsView(generic.DetailView):\n        model = Question\n        template_name = 'polls/results.html'\n\n\n    def vote(request, question_id):\n        ... # same as above, no changes needed.\n\nWe're using two generic views here:\n:class:`~django.views.generic.list.ListView` and\n:class:`~django.views.generic.detail.DetailView`. Respectively, those\ntwo views abstract the concepts of \"display a list of objects\" and\n\"display a detail page for a particular type of object.\"\n\n* Each generic view needs to know what model it will be acting\n  upon. This is provided using the ``model`` attribute.\n\n* The :class:`~django.views.generic.detail.DetailView` generic view\n  expects the primary key value captured from the URL to be called\n  ``\"pk\"``, so we've changed ``question_id`` to ``pk`` for the generic\n  views.\n\nBy default, the :class:`~django.views.generic.detail.DetailView` generic\nview uses a template called ``<app name>/<model name>_detail.html``.\nIn our case, it would use the template ``\"polls/question_detail.html\"``. The\n``template_name`` attribute is used to tell Django to use a specific\ntemplate name instead of the autogenerated default template name. We\nalso specify the ``template_name`` for the ``results`` list view --\nthis ensures that the results view and the detail view have a\ndifferent appearance when rendered, even though they're both a\n:class:`~django.views.generic.detail.DetailView` behind the scenes.\n\nSimilarly, the :class:`~django.views.generic.list.ListView` generic\nview uses a default template called ``<app name>/<model\nname>_list.html``; we use ``template_name`` to tell\n:class:`~django.views.generic.list.ListView` to use our existing\n``\"polls/index.html\"`` template.\n\nIn previous parts of the tutorial, the templates have been provided\nwith a context that contains the ``question`` and ``latest_question_list``\ncontext variables. For ``DetailView`` the ``question`` variable is provided\nautomatically -- since we're using a Django model (``Question``), Django\nis able to determine an appropriate name for the context variable.\nHowever, for ListView, the automatically generated context variable is\n``question_list``. To override this we provide the ``context_object_name``\nattribute, specifying that we want to use ``latest_question_list`` instead.\nAs an alternative approach, you could change your templates to match\nthe new default context variables -- but it's a lot easier to tell Django to\nuse the variable you want.\n\nRun the server, and use your new polling app based on generic views.\n\nFor full details on generic views, see the :doc:`generic views documentation\n</topics/class-based-views/index>`.\n\nWhen you're comfortable with forms and generic views, read :doc:`part 5 of this\ntutorial</intro/tutorial05>` to learn about testing our polls app.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":218,"nodeType":"Package","repoName":null,"name":"docs/_theme/djangodocs/static","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":219,"nodeType":"TextFile","repoName":null,"name":"reset-fonts-grids.css","path":"docs/_theme/djangodocs/static","text":"/*\nCopyright (c) 2008, Yahoo! Inc. All rights reserved.\nCode licensed under the BSD License:\nhttp://developer.yahoo.net/yui/license.txt\nversion: 2.5.1\n*/\nhtml{color:#000;background:#FFF;}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td{margin:0;padding:0;}table{border-collapse:collapse;border-spacing:0;}fieldset,img{border:0;}address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal;}li{list-style:none;}caption,th{text-align:left;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym {border:0;font-variant:normal;}sup {vertical-align:text-top;}sub {vertical-align:text-bottom;}input,textarea,select{font-family:inherit;font-size:inherit;font-weight:inherit;}input,textarea,select{*font-size:100%;}legend{color:#000;}body {font:13px/1.231 arial,helvetica,clean,sans-serif;*font-size:small;*font:x-small;}table {font-size:inherit;font:100%;}pre,code,kbd,samp,tt{font-family:monospace;*font-size:108%;line-height:100%;}\nbody{text-align:center;}#ft{clear:both;}#doc,#doc2,#doc3,#doc4,.yui-t1,.yui-t2,.yui-t3,.yui-t4,.yui-t5,.yui-t6,.yui-t7{margin:auto;text-align:left;width:57.69em;*width:56.25em;min-width:750px;}#doc2{width:73.076em;*width:71.25em;}#doc3{margin:auto 10px;width:auto;}#doc4{width:74.923em;*width:73.05em;}.yui-b{position:relative;}.yui-b{_position:static;}#yui-main .yui-b{position:static;}#yui-main{width:100%;}.yui-t1 #yui-main,.yui-t2 #yui-main,.yui-t3 #yui-main{float:right;margin-left:-25em;}.yui-t4 #yui-main,.yui-t5 #yui-main,.yui-t6 #yui-main{float:left;margin-right:-25em;}.yui-t1 .yui-b{float:left;width:12.30769em;*width:12.00em;}.yui-t1 #yui-main .yui-b{margin-left:13.30769em;*margin-left:13.05em;}.yui-t2 .yui-b{float:left;width:13.8461em;*width:13.50em;}.yui-t2 #yui-main .yui-b{margin-left:14.8461em;*margin-left:14.55em;}.yui-t3 .yui-b{float:left;width:23.0769em;*width:22.50em;}.yui-t3 #yui-main .yui-b{margin-left:24.0769em;*margin-left:23.62em;}.yui-t4 .yui-b{float:right;width:13.8456em;*width:13.50em;}.yui-t4 #yui-main .yui-b{margin-right:14.8456em;*margin-right:14.55em;}.yui-t5 .yui-b{float:right;width:18.4615em;*width:18.00em;}.yui-t5 #yui-main .yui-b{margin-right:19.4615em;*margin-right:19.125em;}.yui-t6 .yui-b{float:right;width:23.0769em;*width:22.50em;}.yui-t6 #yui-main .yui-b{margin-right:24.0769em;*margin-right:23.62em;}.yui-t7 #yui-main .yui-b{display:block;margin:0 0 1em 0;}#yui-main .yui-b{float:none;width:auto;}.yui-gb .yui-u,.yui-g .yui-gb .yui-u,.yui-gb .yui-g,.yui-gb .yui-gb,.yui-gb .yui-gc,.yui-gb .yui-gd,.yui-gb .yui-ge,.yui-gb .yui-gf,.yui-gc .yui-u,.yui-gc .yui-g,.yui-gd .yui-u{float:left;}.yui-g .yui-u,.yui-g .yui-g,.yui-g .yui-gb,.yui-g .yui-gc,.yui-g .yui-gd,.yui-g .yui-ge,.yui-g .yui-gf,.yui-gc .yui-u,.yui-gd .yui-g,.yui-g .yui-gc .yui-u,.yui-ge .yui-u,.yui-ge .yui-g,.yui-gf .yui-g,.yui-gf .yui-u{float:right;}.yui-g div.first,.yui-gb div.first,.yui-gc div.first,.yui-gd div.first,.yui-ge div.first,.yui-gf div.first,.yui-g .yui-gc div.first,.yui-g .yui-ge div.first,.yui-gc div.first div.first{float:left;}.yui-g .yui-u,.yui-g .yui-g,.yui-g .yui-gb,.yui-g .yui-gc,.yui-g .yui-gd,.yui-g .yui-ge,.yui-g .yui-gf{width:49.1%;}.yui-gb .yui-u,.yui-g .yui-gb .yui-u,.yui-gb .yui-g,.yui-gb .yui-gb,.yui-gb .yui-gc,.yui-gb .yui-gd,.yui-gb .yui-ge,.yui-gb .yui-gf,.yui-gc .yui-u,.yui-gc .yui-g,.yui-gd .yui-u{width:32%;margin-left:1.99%;}.yui-gb .yui-u{*margin-left:1.9%;*width:31.9%;}.yui-gc div.first,.yui-gd .yui-u{width:66%;}.yui-gd div.first{width:32%;}.yui-ge div.first,.yui-gf .yui-u{width:74.2%;}.yui-ge .yui-u,.yui-gf div.first{width:24%;}.yui-g .yui-gb div.first,.yui-gb div.first,.yui-gc div.first,.yui-gd div.first{margin-left:0;}.yui-g .yui-g .yui-u,.yui-gb .yui-g .yui-u,.yui-gc .yui-g .yui-u,.yui-gd .yui-g .yui-u,.yui-ge .yui-g .yui-u,.yui-gf .yui-g .yui-u{width:49%;*width:48.1%;*margin-left:0;}.yui-g .yui-gb div.first,.yui-gb .yui-gb div.first{*margin-right:0;*width:32%;_width:31.7%;}.yui-g .yui-gc div.first,.yui-gd .yui-g{width:66%;}.yui-gb .yui-g div.first{*margin-right:4%;_margin-right:1.3%;}.yui-gb .yui-gc div.first,.yui-gb .yui-gd div.first{*margin-right:0;}.yui-gb .yui-gb .yui-u,.yui-gb .yui-gc .yui-u{*margin-left:1.8%;_margin-left:4%;}.yui-g .yui-gb .yui-u{_margin-left:1.0%;}.yui-gb .yui-gd .yui-u{*width:66%;_width:61.2%;}.yui-gb .yui-gd div.first{*width:31%;_width:29.5%;}.yui-g .yui-gc .yui-u,.yui-gb .yui-gc .yui-u{width:32%;_float:right;margin-right:0;_margin-left:0;}.yui-gb .yui-gc div.first{width:66%;*float:left;*margin-left:0;}.yui-gb .yui-ge .yui-u,.yui-gb .yui-gf .yui-u{margin:0;}.yui-gb .yui-gb .yui-u{_margin-left:.7%;}.yui-gb .yui-g div.first,.yui-gb .yui-gb div.first{*margin-left:0;}.yui-gc .yui-g .yui-u,.yui-gd .yui-g .yui-u{*width:48.1%;*margin-left:0;}s .yui-gb .yui-gd div.first{width:32%;}.yui-g .yui-gd div.first{_width:29.9%;}.yui-ge .yui-g{width:24%;}.yui-gf .yui-g{width:74.2%;}.yui-gb .yui-ge div.yui-u,.yui-gb .yui-gf div.yui-u{float:right;}.yui-gb .yui-ge div.first,.yui-gb .yui-gf div.first{float:left;}.yui-gb .yui-ge .yui-u,.yui-gb .yui-gf div.first{*width:24%;_width:20%;}.yui-gb .yui-ge div.first,.yui-gb .yui-gf .yui-u{*width:73.5%;_width:65.5%;}.yui-ge div.first .yui-gd .yui-u{width:65%;}.yui-ge div.first .yui-gd div.first{width:32%;}#bd:after,.yui-g:after,.yui-gb:after,.yui-gc:after,.yui-gd:after,.yui-ge:after,.yui-gf:after{content:\".\";display:block;height:0;clear:both;visibility:hidden;}#bd,.yui-g,.yui-gb,.yui-gc,.yui-gd,.yui-ge,.yui-gf{zoom:1;}","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":220,"nodeType":"TextFile","repoName":null,"name":"tutorial05.txt","path":"docs/intro","text":"=====================================\nWriting your first Django app, part 5\n=====================================\n\nThis tutorial begins where :doc:`Tutorial 4 </intro/tutorial04>` left off.\nWe've built a Web-poll application, and we'll now create some automated tests\nfor it.\n\n.. admonition:: Where to get help:\n\n    If you're having trouble going through this tutorial, please head over to\n    the :doc:`Getting Help</faq/help>` section of the FAQ.\n\nIntroducing automated testing\n=============================\n\nWhat are automated tests?\n-------------------------\n\nTests are routines that check the operation of your code.\n\nTesting operates at different levels. Some tests might apply to a tiny detail\n(*does a particular model method return values as expected?*) while others\nexamine the overall operation of the software (*does a sequence of user inputs\non the site produce the desired result?*). That's no different from the kind of\ntesting you did earlier in :doc:`Tutorial 2 </intro/tutorial02>`, using the\n:djadmin:`shell` to examine the behavior of a method, or running the\napplication and entering data to check how it behaves.\n\nWhat's different in *automated* tests is that the testing work is done for\nyou by the system. You create a set of tests once, and then as you make changes\nto your app, you can check that your code still works as you originally\nintended, without having to perform time consuming manual testing.\n\nWhy you need to create tests\n----------------------------\n\nSo why create tests, and why now?\n\nYou may feel that you have quite enough on your plate just learning\nPython/Django, and having yet another thing to learn and do may seem\noverwhelming and perhaps unnecessary. After all, our polls application is\nworking quite happily now; going through the trouble of creating automated\ntests is not going to make it work any better. If creating the polls\napplication is the last bit of Django programming you will ever do, then true,\nyou don't need to know how to create automated tests. But, if that's not the\ncase, now is an excellent time to learn.\n\nTests will save you time\n~~~~~~~~~~~~~~~~~~~~~~~~\n\nUp to a certain point, 'checking that it seems to work' will be a satisfactory\ntest. In a more sophisticated application, you might have dozens of complex\ninteractions between components.\n\nA change in any of those components could have unexpected consequences on the\napplication's behavior. Checking that it still 'seems to work' could mean\nrunning through your code's functionality with twenty different variations of\nyour test data to make sure you haven't broken something - not a good use\nof your time.\n\nThat's especially true when automated tests could do this for you in seconds.\nIf something's gone wrong, tests will also assist in identifying the code\nthat's causing the unexpected behavior.\n\nSometimes it may seem a chore to tear yourself away from your productive,\ncreative programming work to face the unglamorous and unexciting business\nof writing tests, particularly when you know your code is working properly.\n\nHowever, the task of writing tests is a lot more fulfilling than spending hours\ntesting your application manually or trying to identify the cause of a\nnewly-introduced problem.\n\nTests don't just identify problems, they prevent them\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIt's a mistake to think of tests merely as a negative aspect of development.\n\nWithout tests, the purpose or intended behavior of an application might be\nrather opaque. Even when it's your own code, you will sometimes find yourself\npoking around in it trying to find out what exactly it's doing.\n\nTests change that; they light up your code from the inside, and when something\ngoes wrong, they focus light on the part that has gone wrong - *even if you\nhadn't even realized it had gone wrong*.\n\nTests make your code more attractive\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nYou might have created a brilliant piece of software, but you will find that\nmany other developers will refuse to look at it because it lacks tests; without\ntests, they won't trust it. Jacob Kaplan-Moss, one of Django's original\ndevelopers, says \"Code without tests is broken by design.\"\n\nThat other developers want to see tests in your software before they take it\nseriously is yet another reason for you to start writing tests.\n\nTests help teams work together\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe previous points are written from the point of view of a single developer\nmaintaining an application. Complex applications will be maintained by teams.\nTests guarantee that colleagues don't inadvertently break your code (and that\nyou don't break theirs without knowing). If you want to make a living as a\nDjango programmer, you must be good at writing tests!\n\nBasic testing strategies\n========================\n\nThere are many ways to approach writing tests.\n\nSome programmers follow a discipline called \"`test-driven development`_\"; they\nactually write their tests before they write their code. This might seem\ncounter-intuitive, but in fact it's similar to what most people will often do\nanyway: they describe a problem, then create some code to solve it. Test-driven\ndevelopment formalizes the problem in a Python test case.\n\nMore often, a newcomer to testing will create some code and later decide that\nit should have some tests. Perhaps it would have been better to write some\ntests earlier, but it's never too late to get started.\n\nSometimes it's difficult to figure out where to get started with writing tests.\nIf you have written several thousand lines of Python, choosing something to\ntest might not be easy. In such a case, it's fruitful to write your first test\nthe next time you make a change, either when you add a new feature or fix a bug.\n\nSo let's do that right away.\n\n.. _test-driven development: https://en.wikipedia.org/wiki/Test-driven_development\n\nWriting our first test\n======================\n\nWe identify a bug\n-----------------\n\nFortunately, there's a little bug in the ``polls`` application for us to fix\nright away: the ``Question.was_published_recently()`` method returns ``True`` if\nthe ``Question`` was published within the last day (which is correct) but also if\nthe ``Question``’s ``pub_date`` field is in the future (which certainly isn't).\n\nConfirm the bug by using the :djadmin:`shell` to check the method on a question\nwhose date lies in the future:\n\n.. console::\n\n    $ python manage.py shell\n\n.. code-block:: pycon\n\n    >>> import datetime\n    >>> from django.utils import timezone\n    >>> from polls.models import Question\n    >>> # create a Question instance with pub_date 30 days in the future\n    >>> future_question = Question(pub_date=timezone.now() + datetime.timedelta(days=30))\n    >>> # was it published recently?\n    >>> future_question.was_published_recently()\n    True\n\nSince things in the future are not 'recent', this is clearly wrong.\n\nCreate a test to expose the bug\n-------------------------------\n\nWhat we've just done in the :djadmin:`shell` to test for the problem is exactly\nwhat we can do in an automated test, so let's turn that into an automated test.\n\nA conventional place for an application's tests is in the application's\n``tests.py`` file; the testing system will automatically find tests in any file\nwhose name begins with ``test``.\n\nPut the following in the ``tests.py`` file in the ``polls`` application:\n\n.. code-block:: python\n    :caption: polls/tests.py\n\n    import datetime\n\n    from django.test import TestCase\n    from django.utils import timezone\n\n    from .models import Question\n\n\n    class QuestionModelTests(TestCase):\n\n        def test_was_published_recently_with_future_question(self):\n            \"\"\"\n            was_published_recently() returns False for questions whose pub_date\n            is in the future.\n            \"\"\"\n            time = timezone.now() + datetime.timedelta(days=30)\n            future_question = Question(pub_date=time)\n            self.assertIs(future_question.was_published_recently(), False)\n\nHere we have created a :class:`django.test.TestCase` subclass with a method that\ncreates a ``Question`` instance with a ``pub_date`` in the future. We then check\nthe output of ``was_published_recently()`` - which *ought* to be False.\n\nRunning tests\n-------------\n\nIn the terminal, we can run our test:\n\n.. console::\n\n    $ python manage.py test polls\n\nand you'll see something like::\n\n    Creating test database for alias 'default'...\n    System check identified no issues (0 silenced).\n    F\n    ======================================================================\n    FAIL: test_was_published_recently_with_future_question (polls.tests.QuestionModelTests)\n    ----------------------------------------------------------------------\n    Traceback (most recent call last):\n      File \"/path/to/mysite/polls/tests.py\", line 16, in test_was_published_recently_with_future_question\n        self.assertIs(future_question.was_published_recently(), False)\n    AssertionError: True is not False\n\n    ----------------------------------------------------------------------\n    Ran 1 test in 0.001s\n\n    FAILED (failures=1)\n    Destroying test database for alias 'default'...\n\n.. admonition:: Different error?\n\n    If instead you're getting a ``NameError`` here, you may have missed a step\n    in :ref:`Part 2 <tutorial02-import-timezone>` where we added imports of\n    ``datetime`` and ``timezone`` to ``polls/models.py``. Copy the imports from\n    that section, and try running your tests again.\n\nWhat happened is this:\n\n* ``manage.py test polls`` looked for tests in the ``polls`` application\n\n* it found a subclass of the :class:`django.test.TestCase` class\n\n* it created a special database for the purpose of testing\n\n* it looked for test methods - ones whose names begin with ``test``\n\n* in ``test_was_published_recently_with_future_question`` it created a ``Question``\n  instance whose ``pub_date`` field is 30 days in the future\n\n* ... and using the ``assertIs()`` method, it discovered that its\n  ``was_published_recently()`` returns ``True``, though we wanted it to return\n  ``False``\n\nThe test informs us which test failed and even the line on which the failure\noccurred.\n\nFixing the bug\n--------------\n\nWe already know what the problem is: ``Question.was_published_recently()`` should\nreturn ``False`` if its ``pub_date`` is in the future. Amend the method in\n``models.py``, so that it will only return ``True`` if the date is also in the\npast:\n\n.. code-block:: python\n    :caption: polls/models.py\n\n    def was_published_recently(self):\n        now = timezone.now()\n        return now - datetime.timedelta(days=1) <= self.pub_date <= now\n\nand run the test again::\n\n    Creating test database for alias 'default'...\n    System check identified no issues (0 silenced).\n    .\n    ----------------------------------------------------------------------\n    Ran 1 test in 0.001s\n\n    OK\n    Destroying test database for alias 'default'...\n\nAfter identifying a bug, we wrote a test that exposes it and corrected the bug\nin the code so our test passes.\n\nMany other things might go wrong with our application in the future, but we can\nbe sure that we won't inadvertently reintroduce this bug, because running the\ntest will warn us immediately. We can consider this little portion of the\napplication pinned down safely forever.\n\nMore comprehensive tests\n------------------------\n\nWhile we're here, we can further pin down the ``was_published_recently()``\nmethod; in fact, it would be positively embarrassing if in fixing one bug we had\nintroduced another.\n\nAdd two more test methods to the same class, to test the behavior of the method\nmore comprehensively:\n\n.. code-block:: python\n    :caption: polls/tests.py\n\n    def test_was_published_recently_with_old_question(self):\n        \"\"\"\n        was_published_recently() returns False for questions whose pub_date\n        is older than 1 day.\n        \"\"\"\n        time = timezone.now() - datetime.timedelta(days=1, seconds=1)\n        old_question = Question(pub_date=time)\n        self.assertIs(old_question.was_published_recently(), False)\n\n    def test_was_published_recently_with_recent_question(self):\n        \"\"\"\n        was_published_recently() returns True for questions whose pub_date\n        is within the last day.\n        \"\"\"\n        time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59)\n        recent_question = Question(pub_date=time)\n        self.assertIs(recent_question.was_published_recently(), True)\n\nAnd now we have three tests that confirm that ``Question.was_published_recently()``\nreturns sensible values for past, recent, and future questions.\n\nAgain, ``polls`` is a minimal application, but however complex it grows in the\nfuture and whatever other code it interacts with, we now have some guarantee\nthat the method we have written tests for will behave in expected ways.\n\nTest a view\n===========\n\nThe polls application is fairly undiscriminating: it will publish any question,\nincluding ones whose ``pub_date`` field lies in the future. We should improve\nthis. Setting a ``pub_date`` in the future should mean that the Question is\npublished at that moment, but invisible until then.\n\nA test for a view\n-----------------\n\nWhen we fixed the bug above, we wrote the test first and then the code to fix\nit. In fact that was an example of test-driven development, but it doesn't\nreally matter in which order we do the work.\n\nIn our first test, we focused closely on the internal behavior of the code. For\nthis test, we want to check its behavior as it would be experienced by a user\nthrough a web browser.\n\nBefore we try to fix anything, let's have a look at the tools at our disposal.\n\nThe Django test client\n----------------------\n\nDjango provides a test :class:`~django.test.Client` to simulate a user\ninteracting with the code at the view level.  We can use it in ``tests.py``\nor even in the :djadmin:`shell`.\n\nWe will start again with the :djadmin:`shell`, where we need to do a couple of\nthings that won't be necessary in ``tests.py``. The first is to set up the test\nenvironment in the :djadmin:`shell`:\n\n.. console::\n\n    $ python manage.py shell\n\n.. code-block:: pycon\n\n    >>> from django.test.utils import setup_test_environment\n    >>> setup_test_environment()\n\n:meth:`~django.test.utils.setup_test_environment` installs a template renderer\nwhich will allow us to examine some additional attributes on responses such as\n``response.context`` that otherwise wouldn't be available. Note that this\nmethod *does not* setup a test database, so the following will be run against\nthe existing database and the output may differ slightly depending on what\nquestions you already created. You might get unexpected results if your\n``TIME_ZONE`` in ``settings.py`` isn't correct. If you don't remember setting\nit earlier, check it before continuing.\n\nNext we need to import the test client class (later in ``tests.py`` we will use\nthe :class:`django.test.TestCase` class, which comes with its own client, so\nthis won't be required)::\n\n    >>> from django.test import Client\n    >>> # create an instance of the client for our use\n    >>> client = Client()\n\nWith that ready, we can ask the client to do some work for us::\n\n    >>> # get a response from '/'\n    >>> response = client.get('/')\n    Not Found: /\n    >>> # we should expect a 404 from that address; if you instead see an\n    >>> # \"Invalid HTTP_HOST header\" error and a 400 response, you probably\n    >>> # omitted the setup_test_environment() call described earlier.\n    >>> response.status_code\n    404\n    >>> # on the other hand we should expect to find something at '/polls/'\n    >>> # we'll use 'reverse()' rather than a hardcoded URL\n    >>> from django.urls import reverse\n    >>> response = client.get(reverse('polls:index'))\n    >>> response.status_code\n    200\n    >>> response.content\n    b'\\n    <ul>\\n    \\n        <li><a href=\"/polls/1/\">What&#x27;s up?</a></li>\\n    \\n    </ul>\\n\\n'\n    >>> response.context['latest_question_list']\n    <QuerySet [<Question: What's up?>]>\n\nImproving our view\n------------------\n\nThe list of polls shows polls that aren't published yet (i.e. those that have a\n``pub_date`` in the future). Let's fix that.\n\nIn :doc:`Tutorial 4 </intro/tutorial04>` we introduced a class-based view,\nbased on :class:`~django.views.generic.list.ListView`:\n\n.. code-block:: python\n    :caption: polls/views.py\n\n    class IndexView(generic.ListView):\n        template_name = 'polls/index.html'\n        context_object_name = 'latest_question_list'\n\n        def get_queryset(self):\n            \"\"\"Return the last five published questions.\"\"\"\n            return Question.objects.order_by('-pub_date')[:5]\n\nWe need to amend the ``get_queryset()`` method and change it so that it also\nchecks the date by comparing it with ``timezone.now()``. First we need to add\nan import:\n\n.. code-block:: python\n    :caption: polls/views.py\n\n    from django.utils import timezone\n\nand then we must amend the ``get_queryset`` method like so:\n\n.. code-block:: python\n    :caption: polls/views.py\n\n    def get_queryset(self):\n        \"\"\"\n        Return the last five published questions (not including those set to be\n        published in the future).\n        \"\"\"\n        return Question.objects.filter(\n            pub_date__lte=timezone.now()\n        ).order_by('-pub_date')[:5]\n\n``Question.objects.filter(pub_date__lte=timezone.now())`` returns a queryset\ncontaining ``Question``\\s whose ``pub_date`` is less than or equal to - that\nis, earlier than or equal to - ``timezone.now``.\n\nTesting our new view\n--------------------\n\nNow you can satisfy yourself that this behaves as expected by firing up\n``runserver``, loading the site in your browser, creating ``Questions`` with\ndates in the past and future, and checking that only those that have been\npublished are listed. You don't want to have to do that *every single time you\nmake any change that might affect this* - so let's also create a test, based on\nour :djadmin:`shell` session above.\n\nAdd the following to ``polls/tests.py``:\n\n.. code-block:: python\n    :caption: polls/tests.py\n\n    from django.urls import reverse\n\nand we'll create a shortcut function to create questions as well as a new test\nclass:\n\n.. code-block:: python\n    :caption: polls/tests.py\n\n    def create_question(question_text, days):\n        \"\"\"\n        Create a question with the given `question_text` and published the\n        given number of `days` offset to now (negative for questions published\n        in the past, positive for questions that have yet to be published).\n        \"\"\"\n        time = timezone.now() + datetime.timedelta(days=days)\n        return Question.objects.create(question_text=question_text, pub_date=time)\n\n\n    class QuestionIndexViewTests(TestCase):\n        def test_no_questions(self):\n            \"\"\"\n            If no questions exist, an appropriate message is displayed.\n            \"\"\"\n            response = self.client.get(reverse('polls:index'))\n            self.assertEqual(response.status_code, 200)\n            self.assertContains(response, \"No polls are available.\")\n            self.assertQuerysetEqual(response.context['latest_question_list'], [])\n\n        def test_past_question(self):\n            \"\"\"\n            Questions with a pub_date in the past are displayed on the\n            index page.\n            \"\"\"\n            create_question(question_text=\"Past question.\", days=-30)\n            response = self.client.get(reverse('polls:index'))\n            self.assertQuerysetEqual(\n                response.context['latest_question_list'],\n                ['<Question: Past question.>']\n            )\n\n        def test_future_question(self):\n            \"\"\"\n            Questions with a pub_date in the future aren't displayed on\n            the index page.\n            \"\"\"\n            create_question(question_text=\"Future question.\", days=30)\n            response = self.client.get(reverse('polls:index'))\n            self.assertContains(response, \"No polls are available.\")\n            self.assertQuerysetEqual(response.context['latest_question_list'], [])\n\n        def test_future_question_and_past_question(self):\n            \"\"\"\n            Even if both past and future questions exist, only past questions\n            are displayed.\n            \"\"\"\n            create_question(question_text=\"Past question.\", days=-30)\n            create_question(question_text=\"Future question.\", days=30)\n            response = self.client.get(reverse('polls:index'))\n            self.assertQuerysetEqual(\n                response.context['latest_question_list'],\n                ['<Question: Past question.>']\n            )\n\n        def test_two_past_questions(self):\n            \"\"\"\n            The questions index page may display multiple questions.\n            \"\"\"\n            create_question(question_text=\"Past question 1.\", days=-30)\n            create_question(question_text=\"Past question 2.\", days=-5)\n            response = self.client.get(reverse('polls:index'))\n            self.assertQuerysetEqual(\n                response.context['latest_question_list'],\n                ['<Question: Past question 2.>', '<Question: Past question 1.>']\n            )\n\n\nLet's look at some of these more closely.\n\nFirst is a question shortcut function, ``create_question``, to take some\nrepetition out of the process of creating questions.\n\n``test_no_questions`` doesn't create any questions, but checks the message:\n\"No polls are available.\" and verifies the ``latest_question_list`` is empty.\nNote that the :class:`django.test.TestCase` class provides some additional\nassertion methods. In these examples, we use\n:meth:`~django.test.SimpleTestCase.assertContains()` and\n:meth:`~django.test.TransactionTestCase.assertQuerysetEqual()`.\n\nIn ``test_past_question``, we create a question and verify that it appears in\nthe list.\n\nIn ``test_future_question``, we create a question with a ``pub_date`` in the\nfuture. The database is reset for each test method, so the first question is no\nlonger there, and so again the index shouldn't have any questions in it.\n\nAnd so on. In effect, we are using the tests to tell a story of admin input\nand user experience on the site, and checking that at every state and for every\nnew change in the state of the system, the expected results are published.\n\nTesting the ``DetailView``\n--------------------------\n\nWhat we have works well; however, even though future questions don't appear in\nthe *index*, users can still reach them if they know or guess the right URL. So\nwe need to add a similar  constraint to ``DetailView``:\n\n.. code-block:: python\n    :caption: polls/views.py\n\n    class DetailView(generic.DetailView):\n        ...\n        def get_queryset(self):\n            \"\"\"\n            Excludes any questions that aren't published yet.\n            \"\"\"\n            return Question.objects.filter(pub_date__lte=timezone.now())\n\nWe should then add some tests, to check that a ``Question`` whose ``pub_date``\nis in the past can be displayed, and that one with a ``pub_date`` in the future\nis not:\n\n.. code-block:: python\n    :caption: polls/tests.py\n\n    class QuestionDetailViewTests(TestCase):\n        def test_future_question(self):\n            \"\"\"\n            The detail view of a question with a pub_date in the future\n            returns a 404 not found.\n            \"\"\"\n            future_question = create_question(question_text='Future question.', days=5)\n            url = reverse('polls:detail', args=(future_question.id,))\n            response = self.client.get(url)\n            self.assertEqual(response.status_code, 404)\n\n        def test_past_question(self):\n            \"\"\"\n            The detail view of a question with a pub_date in the past\n            displays the question's text.\n            \"\"\"\n            past_question = create_question(question_text='Past Question.', days=-5)\n            url = reverse('polls:detail', args=(past_question.id,))\n            response = self.client.get(url)\n            self.assertContains(response, past_question.question_text)\n\nIdeas for more tests\n--------------------\n\nWe ought to add a similar ``get_queryset`` method to ``ResultsView`` and\ncreate a new test class for that view. It'll be very similar to what we have\njust created; in fact there will be a lot of repetition.\n\nWe could also improve our application in other ways, adding tests along the\nway. For example, it's silly that ``Questions`` can be published on the site\nthat have no ``Choices``. So, our views could check for this, and exclude such\n``Questions``. Our tests would create a ``Question`` without ``Choices`` and\nthen test that it's not published, as well as create a similar ``Question``\n*with* ``Choices``, and test that it *is* published.\n\nPerhaps logged-in admin users should be allowed to see unpublished\n``Questions``, but not ordinary visitors. Again: whatever needs to be added to\nthe software to accomplish this should be accompanied by a test, whether you\nwrite the test first and then make the code pass the test, or work out the\nlogic in your code first and then write a test to prove it.\n\nAt a certain point you are bound to look at your tests and wonder whether your\ncode is suffering from test bloat, which brings us to:\n\nWhen testing, more is better\n============================\n\nIt might seem that our tests are growing out of control. At this rate there will\nsoon be more code in our tests than in our application, and the repetition\nis unaesthetic, compared to the elegant conciseness of the rest of our code.\n\n**It doesn't matter**. Let them grow. For the most part, you can write a test\nonce and then forget about it. It will continue performing its useful function\nas you continue to develop your program.\n\nSometimes tests will need to be updated. Suppose that we amend our views so that\nonly ``Questions`` with ``Choices`` are published. In that case, many of our\nexisting tests will fail - *telling us exactly which tests need to be amended to\nbring them up to date*, so to that extent tests help look after themselves.\n\nAt worst, as you continue developing, you might find that you have some tests\nthat are now redundant. Even that's not a problem; in testing redundancy is\na *good* thing.\n\nAs long as your tests are sensibly arranged, they won't become unmanageable.\nGood rules-of-thumb include having:\n\n* a separate ``TestClass`` for each model or view\n* a separate test method for each set of conditions you want to test\n* test method names that describe their function\n\nFurther testing\n===============\n\nThis tutorial only introduces some of the basics of testing. There's a great\ndeal more you can do, and a number of very useful tools at your disposal to\nachieve some very clever things.\n\nFor example, while our tests here have covered some of the internal logic of a\nmodel and the way our views publish information, you can use an \"in-browser\"\nframework such as Selenium_ to test the way your HTML actually renders in a\nbrowser. These tools allow you to check not just the behavior of your Django\ncode, but also, for example, of your JavaScript. It's quite something to see\nthe tests launch a browser, and start interacting with your site, as if a human\nbeing were driving it! Django includes :class:`~django.test.LiveServerTestCase`\nto facilitate integration with tools like Selenium.\n\nIf you have a complex application, you may want to run tests automatically\nwith every commit for the purposes of `continuous integration`_, so that\nquality control is itself - at least partially - automated.\n\nA good way to spot untested parts of your application is to check code\ncoverage. This also helps identify fragile or even dead code. If you can't test\na piece of code, it usually means that code should be refactored or removed.\nCoverage will help to identify dead code. See\n:ref:`topics-testing-code-coverage` for details.\n\n:doc:`Testing in Django </topics/testing/index>` has comprehensive\ninformation about testing.\n\n.. _Selenium: http://seleniumhq.org/\n.. _continuous integration: https://en.wikipedia.org/wiki/Continuous_integration\n\nWhat's next?\n============\n\nFor full details on testing, see :doc:`Testing in Django\n</topics/testing/index>`.\n\nWhen you're comfortable with testing Django views, read\n:doc:`part 6 of this tutorial</intro/tutorial06>` to learn about\nstatic files management.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":221,"nodeType":"TextFile","repoName":null,"name":"tutorial06.txt","path":"docs/intro","text":"=====================================\nWriting your first Django app, part 6\n=====================================\n\nThis tutorial begins where :doc:`Tutorial 5 </intro/tutorial05>` left off.\nWe've built a tested Web-poll application, and we'll now add a stylesheet and\nan image.\n\nAside from the HTML generated by the server, web applications generally need\nto serve additional files — such as images, JavaScript, or CSS — necessary to\nrender the complete web page. In Django, we refer to these files as \"static\nfiles\".\n\nFor small projects, this isn't a big deal, because you can keep the static\nfiles somewhere your web server can find it. However, in bigger projects --\nespecially those comprised of multiple apps -- dealing with the multiple sets\nof static files provided by each application starts to get tricky.\n\nThat's what ``django.contrib.staticfiles`` is for: it collects static files\nfrom each of your applications (and any other places you specify) into a\nsingle location that can easily be served in production.\n\n.. admonition:: Where to get help:\n\n    If you're having trouble going through this tutorial, please head over to\n    the :doc:`Getting Help</faq/help>` section of the FAQ.\n\nCustomize your *app's* look and feel\n====================================\n\nFirst, create a directory called ``static`` in your ``polls`` directory. Django\nwill look for static files there, similarly to how Django finds templates\ninside ``polls/templates/``.\n\nDjango's :setting:`STATICFILES_FINDERS` setting contains a list\nof finders that know how to discover static files from various\nsources. One of the defaults is ``AppDirectoriesFinder`` which\nlooks for a \"static\" subdirectory in each of the\n:setting:`INSTALLED_APPS`, like the one in ``polls`` we just created. The admin\nsite uses the same directory structure for its static files.\n\nWithin the ``static`` directory you have just created, create another directory\ncalled ``polls`` and within that create a file called ``style.css``. In other\nwords, your stylesheet should be at ``polls/static/polls/style.css``. Because\nof how the ``AppDirectoriesFinder`` staticfile finder works, you can refer to\nthis static file in Django as ``polls/style.css``, similar to how you reference\nthe path for templates.\n\n.. admonition:: Static file namespacing\n\n    Just like templates, we *might* be able to get away with putting our static\n    files directly in ``polls/static`` (rather than creating another ``polls``\n    subdirectory), but it would actually be a bad idea. Django will choose the\n    first static file it finds whose name matches, and if you had a static file\n    with the same name in a *different* application, Django would be unable to\n    distinguish between them. We need to be able to point Django at the right\n    one, and the best way to ensure this is by *namespacing* them. That is, by\n    putting those static files inside *another* directory named for the\n    application itself.\n\nPut the following code in that stylesheet (``polls/static/polls/style.css``):\n\n.. code-block:: css\n    :caption: polls/static/polls/style.css\n\n    li a {\n        color: green;\n    }\n\nNext, add the following at the top of ``polls/templates/polls/index.html``:\n\n.. code-block:: html+django\n    :caption: polls/templates/polls/index.html\n\n    {% load static %}\n\n    <link rel=\"stylesheet\" type=\"text/css\" href=\"{% static 'polls/style.css' %}\">\n\nThe ``{% static %}`` template tag generates the absolute URL of static files.\n\nThat's all you need to do for development.\n\nStart the server (or restart it if it's already running):\n\n.. console::\n\n    $ python manage.py runserver\n\nReload ``http://localhost:8000/polls/`` and you should see that the question\nlinks are green (Django style!) which means that your stylesheet was properly\nloaded.\n\nAdding a background-image\n=========================\n\nNext, we'll create a subdirectory for images. Create an ``images`` subdirectory\nin the ``polls/static/polls/`` directory. Inside this directory, put an image\ncalled ``background.gif``. In other words, put your image in\n``polls/static/polls/images/background.gif``.\n\nThen, add to your stylesheet (``polls/static/polls/style.css``):\n\n.. code-block:: css\n    :caption: polls/static/polls/style.css\n\n    body {\n        background: white url(\"images/background.gif\") no-repeat;\n    }\n\nReload ``http://localhost:8000/polls/`` and you should see the background\nloaded in the top left of the screen.\n\n.. warning::\n\n    The ``{% static %}`` template tag is not available for use in static files\n    which aren't generated by Django, like your stylesheet. You should always\n    use **relative paths** to link your static files between each other,\n    because then you can change :setting:`STATIC_URL` (used by the\n    :ttag:`static` template tag to generate its URLs) without having to modify\n    a bunch of paths in your static files as well.\n\nThese are the **basics**. For more details on settings and other bits included\nwith the framework see\n:doc:`the static files howto </howto/static-files/index>` and\n:doc:`the staticfiles reference </ref/contrib/staticfiles>`. :doc:`Deploying\nstatic files </howto/static-files/deployment>` discusses how to use static\nfiles on a real server.\n\nWhen you're comfortable with the static files, read :doc:`part 7 of this\ntutorial </intro/tutorial07>` to learn how to customize Django's\nautomatically-generated admin site.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":222,"nodeType":"TextFile","repoName":null,"name":"tutorial01.txt","path":"docs/intro","text":"=====================================\nWriting your first Django app, part 1\n=====================================\n\nLet's learn by example.\n\nThroughout this tutorial, we'll walk you through the creation of a basic\npoll application.\n\nIt'll consist of two parts:\n\n* A public site that lets people view polls and vote in them.\n* An admin site that lets you add, change, and delete polls.\n\nWe'll assume you have :doc:`Django installed </intro/install>` already. You can\ntell Django is installed and which version by running the following command\nin a shell prompt (indicated by the $ prefix):\n\n.. console::\n\n    $ python -m django --version\n\nIf Django is installed, you should see the version of your installation. If it\nisn't, you'll get an error telling \"No module named django\".\n\nThis tutorial is written for Django |version|, which supports Python 3.6 and\nlater. If the Django version doesn't match, you can refer to the tutorial for\nyour version of Django by using the version switcher at the bottom right corner\nof this page, or update Django to the newest version. If you're using an older\nversion of Python, check :ref:`faq-python-version-support` to find a compatible\nversion of Django.\n\nSee :doc:`How to install Django </topics/install>` for advice on how to remove\nolder versions of Django and install a newer one.\n\n.. admonition:: Where to get help:\n\n    If you're having trouble going through this tutorial, please head over to\n    the :doc:`Getting Help</faq/help>` section of the FAQ.\n\nCreating a project\n==================\n\nIf this is your first time using Django, you'll have to take care of some\ninitial setup. Namely, you'll need to auto-generate some code that establishes a\nDjango :term:`project` -- a collection of settings for an instance of Django,\nincluding database configuration, Django-specific options and\napplication-specific settings.\n\nFrom the command line, ``cd`` into a directory where you'd like to store your\ncode, then run the following command:\n\n.. console::\n\n   $ django-admin startproject mysite\n\nThis will create a ``mysite`` directory in your current directory. If it didn't\nwork, see :ref:`troubleshooting-django-admin`.\n\n.. note::\n\n    You'll need to avoid naming projects after built-in Python or Django\n    components. In particular, this means you should avoid using names like\n    ``django`` (which will conflict with Django itself) or ``test`` (which\n    conflicts with a built-in Python package).\n\n.. admonition:: Where should this code live?\n\n    If your background is in plain old PHP (with no use of modern frameworks),\n    you're probably used to putting code under the Web server's document root\n    (in a place such as ``/var/www``). With Django, you don't do that. It's\n    not a good idea to put any of this Python code within your Web server's\n    document root, because it risks the possibility that people may be able\n    to view your code over the Web. That's not good for security.\n\n    Put your code in some directory **outside** of the document root, such as\n    :file:`/home/mycode`.\n\nLet's look at what :djadmin:`startproject` created::\n\n    mysite/\n        manage.py\n        mysite/\n            __init__.py\n            settings.py\n            urls.py\n            asgi.py\n            wsgi.py\n\nThese files are:\n\n* The outer :file:`mysite/` root directory is a container for your project. Its\n  name doesn't matter to Django; you can rename it to anything you like.\n\n* :file:`manage.py`: A command-line utility that lets you interact with this\n  Django project in various ways. You can read all the details about\n  :file:`manage.py` in :doc:`/ref/django-admin`.\n\n* The inner :file:`mysite/` directory is the actual Python package for your\n  project. Its name is the Python package name you'll need to use to import\n  anything inside it (e.g. ``mysite.urls``).\n\n* :file:`mysite/__init__.py`: An empty file that tells Python that this\n  directory should be considered a Python package. If you're a Python beginner,\n  read :ref:`more about packages <tut-packages>` in the official Python docs.\n\n* :file:`mysite/settings.py`: Settings/configuration for this Django\n  project.  :doc:`/topics/settings` will tell you all about how settings\n  work.\n\n* :file:`mysite/urls.py`: The URL declarations for this Django project; a\n  \"table of contents\" of your Django-powered site. You can read more about\n  URLs in :doc:`/topics/http/urls`.\n\n* :file:`mysite/asgi.py`: An entry-point for ASGI-compatible web servers to\n  serve your project. See :doc:`/howto/deployment/asgi/index` for more details.\n\n* :file:`mysite/wsgi.py`: An entry-point for WSGI-compatible web servers to\n  serve your project. See :doc:`/howto/deployment/wsgi/index` for more details.\n\nThe development server\n======================\n\nLet's verify your Django project works. Change into the outer :file:`mysite` directory, if\nyou haven't already, and run the following commands:\n\n.. console::\n\n   $ python manage.py runserver\n\nYou'll see the following output on the command line:\n\n.. parsed-literal::\n\n    Performing system checks...\n\n    System check identified no issues (0 silenced).\n\n    You have unapplied migrations; your app may not work properly until they are applied.\n    Run 'python manage.py migrate' to apply them.\n\n    |today| - 15:50:53\n    Django version |version|, using settings 'mysite.settings'\n    Starting development server at http://127.0.0.1:8000/\n    Quit the server with CONTROL-C.\n\n.. note::\n    Ignore the warning about unapplied database migrations for now; we'll deal\n    with the database shortly.\n\nYou've started the Django development server, a lightweight Web server written\npurely in Python. We've included this with Django so you can develop things\nrapidly, without having to deal with configuring a production server -- such as\nApache -- until you're ready for production.\n\nNow's a good time to note: **don't** use this server in anything resembling a\nproduction environment. It's intended only for use while developing. (We're in\nthe business of making Web frameworks, not Web servers.)\n\nNow that the server's running, visit http://127.0.0.1:8000/ with your Web\nbrowser. You'll see a \"Congratulations!\" page, with a rocket taking off.\nIt worked!\n\n.. admonition:: Changing the port\n\n    By default, the :djadmin:`runserver` command starts the development server\n    on the internal IP at port 8000.\n\n    If you want to change the server's port, pass\n    it as a command-line argument. For instance, this command starts the server\n    on port 8080:\n\n    .. console::\n\n        $ python manage.py runserver 8080\n\n    If you want to change the server's IP, pass it along with the port. For\n    example, to listen on all available public IPs (which is useful if you are\n    running Vagrant or want to show off your work on other computers on the\n    network), use:\n\n    .. console::\n\n        $ python manage.py runserver 0:8000\n\n    **0** is a shortcut for **0.0.0.0**. Full docs for the development server\n    can be found in the :djadmin:`runserver` reference.\n\n.. admonition:: Automatic reloading of :djadmin:`runserver`\n\n    The development server automatically reloads Python code for each request\n    as needed. You don't need to restart the server for code changes to take\n    effect. However, some actions like adding files don't trigger a restart,\n    so you'll have to restart the server in these cases.\n\nCreating the Polls app\n======================\n\nNow that your environment -- a \"project\" -- is set up, you're set to start\ndoing work.\n\nEach application you write in Django consists of a Python package that follows\na certain convention. Django comes with a utility that automatically generates\nthe basic directory structure of an app, so you can focus on writing code\nrather than creating directories.\n\n.. admonition:: Projects vs. apps\n\n    What's the difference between a project and an app? An app is a Web\n    application that does something -- e.g., a Weblog system, a database of\n    public records or a small poll app. A project is a collection of\n    configuration and apps for a particular website. A project can contain\n    multiple apps. An app can be in multiple projects.\n\nYour apps can live anywhere on your :ref:`Python path <tut-searchpath>`. In\nthis tutorial, we'll create our poll app in the same directory as your\n:file:`manage.py` file so that it can be imported as its own top-level module,\nrather than a submodule of ``mysite``.\n\nTo create your app, make sure you're in the same directory as :file:`manage.py`\nand type this command:\n\n.. console::\n\n    $ python manage.py startapp polls\n\nThat'll create a directory :file:`polls`, which is laid out like this::\n\n    polls/\n        __init__.py\n        admin.py\n        apps.py\n        migrations/\n            __init__.py\n        models.py\n        tests.py\n        views.py\n\nThis directory structure will house the poll application.\n\nWrite your first view\n=====================\n\nLet's write the first view. Open the file ``polls/views.py``\nand put the following Python code in it:\n\n.. code-block:: python\n    :caption: polls/views.py\n\n    from django.http import HttpResponse\n\n\n    def index(request):\n        return HttpResponse(\"Hello, world. You're at the polls index.\")\n\nThis is the simplest view possible in Django. To call the view, we need to map\nit to a URL - and for this we need a URLconf.\n\nTo create a URLconf in the polls directory, create a file called ``urls.py``.\nYour app directory should now look like::\n\n    polls/\n        __init__.py\n        admin.py\n        apps.py\n        migrations/\n            __init__.py\n        models.py\n        tests.py\n        urls.py\n        views.py\n\nIn the ``polls/urls.py`` file include the following code:\n\n.. code-block:: python\n    :caption: polls/urls.py\n\n    from django.urls import path\n\n    from . import views\n\n    urlpatterns = [\n        path('', views.index, name='index'),\n    ]\n\nThe next step is to point the root URLconf at the ``polls.urls`` module. In\n``mysite/urls.py``, add an import for ``django.urls.include`` and insert an\n:func:`~django.urls.include` in the ``urlpatterns`` list, so you have:\n\n.. code-block:: python\n    :caption: mysite/urls.py\n\n    from django.contrib import admin\n    from django.urls import include, path\n\n    urlpatterns = [\n        path('polls/', include('polls.urls')),\n        path('admin/', admin.site.urls),\n    ]\n\nThe :func:`~django.urls.include` function allows referencing other URLconfs.\nWhenever Django encounters :func:`~django.urls.include`, it chops off whatever\npart of the URL matched up to that point and sends the remaining string to the\nincluded URLconf for further processing.\n\nThe idea behind :func:`~django.urls.include` is to make it easy to\nplug-and-play URLs. Since polls are in their own URLconf\n(``polls/urls.py``), they can be placed under \"/polls/\", or under\n\"/fun_polls/\", or under \"/content/polls/\", or any other path root, and the\napp will still work.\n\n.. admonition:: When to use :func:`~django.urls.include()`\n\n    You should always use ``include()`` when you include other URL patterns.\n    ``admin.site.urls`` is the only exception to this.\n\nYou have now wired an ``index`` view into the URLconf. Verify it's working with\nthe following command:\n\n.. console::\n\n   $ python manage.py runserver\n\nGo to http://localhost:8000/polls/ in your browser, and you should see the\ntext \"*Hello, world. You're at the polls index.*\", which you defined in the\n``index`` view.\n\n.. admonition:: Page not found?\n\n    If you get an error page here, check that you're going to\n    http://localhost:8000/polls/ and not http://localhost:8000/.\n\nThe :func:`~django.urls.path` function is passed four arguments, two required:\n``route`` and ``view``, and two optional: ``kwargs``, and ``name``.\nAt this point, it's worth reviewing what these arguments are for.\n\n:func:`~django.urls.path` argument: ``route``\n---------------------------------------------\n\n``route`` is a string that contains a URL pattern. When processing a request,\nDjango starts at the first pattern in ``urlpatterns`` and makes its way down\nthe list, comparing the requested URL against each pattern until it finds one\nthat matches.\n\nPatterns don't search GET and POST parameters, or the domain name. For example,\nin a request to ``https://www.example.com/myapp/``, the URLconf will look for\n``myapp/``. In a request to ``https://www.example.com/myapp/?page=3``, the\nURLconf will also look for ``myapp/``.\n\n:func:`~django.urls.path` argument: ``view``\n--------------------------------------------\n\nWhen Django finds a matching pattern, it calls the specified view function with\nan :class:`~django.http.HttpRequest` object as the first argument and any\n\"captured\" values from the route as keyword arguments. We'll give an example\nof this in a bit.\n\n:func:`~django.urls.path` argument: ``kwargs``\n----------------------------------------------\n\nArbitrary keyword arguments can be passed in a dictionary to the target view. We\naren't going to use this feature of Django in the tutorial.\n\n:func:`~django.urls.path` argument: ``name``\n--------------------------------------------\n\nNaming your URL lets you refer to it unambiguously from elsewhere in Django,\nespecially from within templates. This powerful feature allows you to make\nglobal changes to the URL patterns of your project while only touching a single\nfile.\n\nWhen you're comfortable with the basic request and response flow, read\n:doc:`part 2 of this tutorial </intro/tutorial02>` to start working with the\ndatabase.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":223,"nodeType":"TextFile","repoName":null,"name":"tutorial03.txt","path":"docs/intro","text":"=====================================\nWriting your first Django app, part 3\n=====================================\n\nThis tutorial begins where :doc:`Tutorial 2 </intro/tutorial02>` left off. We're\ncontinuing the Web-poll application and will focus on creating the public\ninterface -- \"views.\"\n\n.. admonition:: Where to get help:\n\n    If you're having trouble going through this tutorial, please head over to\n    the :doc:`Getting Help</faq/help>` section of the FAQ.\n\nOverview\n========\n\nA view is a \"type\" of Web page in your Django application that generally serves\na specific function and has a specific template. For example, in a blog\napplication, you might have the following views:\n\n* Blog homepage -- displays the latest few entries.\n\n* Entry \"detail\" page -- permalink page for a single entry.\n\n* Year-based archive page -- displays all months with entries in the\n  given year.\n\n* Month-based archive page -- displays all days with entries in the\n  given month.\n\n* Day-based archive page -- displays all entries in the given day.\n\n* Comment action -- handles posting comments to a given entry.\n\nIn our poll application, we'll have the following four views:\n\n* Question \"index\" page -- displays the latest few questions.\n\n* Question \"detail\" page -- displays a question text, with no results but\n  with a form to vote.\n\n* Question \"results\" page -- displays results for a particular question.\n\n* Vote action -- handles voting for a particular choice in a particular\n  question.\n\nIn Django, web pages and other content are delivered by views. Each view is\nrepresented by a Python function (or method, in the case of class-based views).\nDjango will choose a view by examining the URL that's requested (to be precise,\nthe part of the URL after the domain name).\n\nNow in your time on the web you may have come across such beauties as\n\"ME2/Sites/dirmod.asp?sid=&type=gen&mod=Core+Pages&gid=A6CD4967199A42D9B65B1B\".\nYou will be pleased to know that Django allows us much more elegant\n*URL patterns* than that.\n\nA URL pattern is the general form of a URL - for example:\n``/newsarchive/<year>/<month>/``.\n\nTo get from a URL to a view, Django uses what are known as 'URLconfs'. A\nURLconf maps URL patterns to views.\n\nThis tutorial provides basic instruction in the use of URLconfs, and you can\nrefer to :doc:`/topics/http/urls` for more information.\n\nWriting more views\n==================\n\nNow let's add a few more views to ``polls/views.py``. These views are\nslightly different, because they take an argument:\n\n.. code-block:: python\n    :caption: polls/views.py\n\n    def detail(request, question_id):\n        return HttpResponse(\"You're looking at question %s.\" % question_id)\n\n    def results(request, question_id):\n        response = \"You're looking at the results of question %s.\"\n        return HttpResponse(response % question_id)\n\n    def vote(request, question_id):\n        return HttpResponse(\"You're voting on question %s.\" % question_id)\n\nWire these new views into the ``polls.urls`` module by adding the following\n:func:`~django.urls.path` calls:\n\n.. code-block:: python\n    :caption: polls/urls.py\n\n    from django.urls import path\n\n    from . import views\n\n    urlpatterns = [\n        # ex: /polls/\n        path('', views.index, name='index'),\n        # ex: /polls/5/\n        path('<int:question_id>/', views.detail, name='detail'),\n        # ex: /polls/5/results/\n        path('<int:question_id>/results/', views.results, name='results'),\n        # ex: /polls/5/vote/\n        path('<int:question_id>/vote/', views.vote, name='vote'),\n    ]\n\nTake a look in your browser, at \"/polls/34/\". It'll run the ``detail()``\nmethod and display whatever ID you provide in the URL. Try\n\"/polls/34/results/\" and \"/polls/34/vote/\" too -- these will display the\nplaceholder results and voting pages.\n\nWhen somebody requests a page from your website -- say, \"/polls/34/\", Django\nwill load the ``mysite.urls`` Python module because it's pointed to by the\n:setting:`ROOT_URLCONF` setting. It finds the variable named ``urlpatterns``\nand traverses the patterns in order. After finding the match at ``'polls/'``,\nit strips off the matching text (``\"polls/\"``) and sends the remaining text --\n``\"34/\"`` -- to the 'polls.urls' URLconf for further processing. There it\nmatches ``'<int:question_id>/'``, resulting in a call to the ``detail()`` view\nlike so::\n\n    detail(request=<HttpRequest object>, question_id=34)\n\nThe ``question_id=34`` part comes from ``<int:question_id>``. Using angle\nbrackets \"captures\" part of the URL and sends it as a keyword argument to the\nview function. The ``:question_id>`` part of the string defines the name that\nwill be used to identify the matched pattern, and the ``<int:`` part is a\nconverter that determines what patterns should match this part of the URL path.\n\nWrite views that actually do something\n======================================\n\nEach view is responsible for doing one of two things: returning an\n:class:`~django.http.HttpResponse` object containing the content for the\nrequested page, or raising an exception such as :exc:`~django.http.Http404`. The\nrest is up to you.\n\nYour view can read records from a database, or not. It can use a template\nsystem such as Django's -- or a third-party Python template system -- or not.\nIt can generate a PDF file, output XML, create a ZIP file on the fly, anything\nyou want, using whatever Python libraries you want.\n\nAll Django wants is that :class:`~django.http.HttpResponse`. Or an exception.\n\nBecause it's convenient, let's use Django's own database API, which we covered\nin :doc:`Tutorial 2 </intro/tutorial02>`. Here's one stab at a new ``index()``\nview, which displays the latest 5 poll questions in the system, separated by\ncommas, according to publication date:\n\n.. code-block:: python\n    :caption: polls/views.py\n\n    from django.http import HttpResponse\n\n    from .models import Question\n\n\n    def index(request):\n        latest_question_list = Question.objects.order_by('-pub_date')[:5]\n        output = ', '.join([q.question_text for q in latest_question_list])\n        return HttpResponse(output)\n\n    # Leave the rest of the views (detail, results, vote) unchanged\n\nThere's a problem here, though: the page's design is hard-coded in the view. If\nyou want to change the way the page looks, you'll have to edit this Python code.\nSo let's use Django's template system to separate the design from Python by\ncreating a template that the view can use.\n\nFirst, create a directory called ``templates`` in your ``polls`` directory.\nDjango will look for templates in there.\n\nYour project's :setting:`TEMPLATES` setting describes how Django will load and\nrender templates. The default settings file configures a ``DjangoTemplates``\nbackend whose :setting:`APP_DIRS <TEMPLATES-APP_DIRS>` option is set to\n``True``. By convention ``DjangoTemplates`` looks for a \"templates\"\nsubdirectory in each of the :setting:`INSTALLED_APPS`.\n\nWithin the ``templates`` directory you have just created, create another\ndirectory called ``polls``, and within that create a file called\n``index.html``. In other words, your template should be at\n``polls/templates/polls/index.html``. Because of how the ``app_directories``\ntemplate loader works as described above, you can refer to this template within\nDjango as ``polls/index.html``.\n\n.. admonition:: Template namespacing\n\n    Now we *might* be able to get away with putting our templates directly in\n    ``polls/templates`` (rather than creating another ``polls`` subdirectory),\n    but it would actually be a bad idea. Django will choose the first template\n    it finds whose name matches, and if you had a template with the same name\n    in a *different* application, Django would be unable to distinguish between\n    them. We need to be able to point Django at the right one, and the best\n    way to ensure this is by *namespacing* them. That is, by putting those\n    templates inside *another* directory named for the application itself.\n\nPut the following code in that template:\n\n.. code-block:: html+django\n    :caption: polls/templates/polls/index.html\n\n    {% if latest_question_list %}\n        <ul>\n        {% for question in latest_question_list %}\n            <li><a href=\"/polls/{{ question.id }}/\">{{ question.question_text }}</a></li>\n        {% endfor %}\n        </ul>\n    {% else %}\n        <p>No polls are available.</p>\n    {% endif %}\n\n.. note::\n\n    To make the tutorial shorter, all template examples use incomplete HTML. In\n    your own projects you should use `complete HTML documents`__.\n\n__ https://developer.mozilla.org/en-US/docs/Learn/HTML/Introduction_to_HTML/Getting_started#Anatomy_of_an_HTML_document\n\nNow let's update our ``index`` view in ``polls/views.py`` to use the template:\n\n.. code-block:: python\n    :caption: polls/views.py\n\n    from django.http import HttpResponse\n    from django.template import loader\n\n    from .models import Question\n\n\n    def index(request):\n        latest_question_list = Question.objects.order_by('-pub_date')[:5]\n        template = loader.get_template('polls/index.html')\n        context = {\n            'latest_question_list': latest_question_list,\n        }\n        return HttpResponse(template.render(context, request))\n\nThat code loads the template called  ``polls/index.html`` and passes it a\ncontext. The context is a dictionary mapping template variable names to Python\nobjects.\n\nLoad the page by pointing your browser at \"/polls/\", and you should see a\nbulleted-list containing the \"What's up\" question from :doc:`Tutorial 2\n</intro/tutorial02>`. The link points to the question's detail page.\n\nA shortcut: :func:`~django.shortcuts.render`\n--------------------------------------------\n\nIt's a very common idiom to load a template, fill a context and return an\n:class:`~django.http.HttpResponse` object with the result of the rendered\ntemplate. Django provides a shortcut. Here's the full ``index()`` view,\nrewritten:\n\n.. code-block:: python\n    :caption: polls/views.py\n\n    from django.shortcuts import render\n\n    from .models import Question\n\n\n    def index(request):\n        latest_question_list = Question.objects.order_by('-pub_date')[:5]\n        context = {'latest_question_list': latest_question_list}\n        return render(request, 'polls/index.html', context)\n\nNote that once we've done this in all these views, we no longer need to import\n:mod:`~django.template.loader` and :class:`~django.http.HttpResponse` (you'll\nwant to keep ``HttpResponse`` if you still have the stub methods for ``detail``,\n``results``, and ``vote``).\n\nThe :func:`~django.shortcuts.render` function takes the request object as its\nfirst argument, a template name as its second argument and a dictionary as its\noptional third argument. It returns an :class:`~django.http.HttpResponse`\nobject of the given template rendered with the given context.\n\nRaising a 404 error\n===================\n\nNow, let's tackle the question detail view -- the page that displays the question text\nfor a given poll. Here's the view:\n\n.. code-block:: python\n    :caption: polls/views.py\n\n    from django.http import Http404\n    from django.shortcuts import render\n\n    from .models import Question\n    # ...\n    def detail(request, question_id):\n        try:\n            question = Question.objects.get(pk=question_id)\n        except Question.DoesNotExist:\n            raise Http404(\"Question does not exist\")\n        return render(request, 'polls/detail.html', {'question': question})\n\nThe new concept here: The view raises the :exc:`~django.http.Http404` exception\nif a question with the requested ID doesn't exist.\n\nWe'll discuss what you could put in that ``polls/detail.html`` template a bit\nlater, but if you'd like to quickly get the above example working, a file\ncontaining just:\n\n.. code-block:: html+django\n    :caption: polls/templates/polls/detail.html\n\n    {{ question }}\n\nwill get you started for now.\n\nA shortcut: :func:`~django.shortcuts.get_object_or_404`\n-------------------------------------------------------\n\nIt's a very common idiom to use :meth:`~django.db.models.query.QuerySet.get`\nand raise :exc:`~django.http.Http404` if the object doesn't exist. Django\nprovides a shortcut. Here's the ``detail()`` view, rewritten:\n\n.. code-block:: python\n    :caption: polls/views.py\n\n    from django.shortcuts import get_object_or_404, render\n\n    from .models import Question\n    # ...\n    def detail(request, question_id):\n        question = get_object_or_404(Question, pk=question_id)\n        return render(request, 'polls/detail.html', {'question': question})\n\nThe :func:`~django.shortcuts.get_object_or_404` function takes a Django model\nas its first argument and an arbitrary number of keyword arguments, which it\npasses to the :meth:`~django.db.models.query.QuerySet.get` function of the\nmodel's manager. It raises :exc:`~django.http.Http404` if the object doesn't\nexist.\n\n.. admonition:: Philosophy\n\n    Why do we use a helper function :func:`~django.shortcuts.get_object_or_404`\n    instead of automatically catching the\n    :exc:`~django.core.exceptions.ObjectDoesNotExist` exceptions at a higher\n    level, or having the model API raise :exc:`~django.http.Http404` instead of\n    :exc:`~django.core.exceptions.ObjectDoesNotExist`?\n\n    Because that would couple the model layer to the view layer. One of the\n    foremost design goals of Django is to maintain loose coupling. Some\n    controlled coupling is introduced in the :mod:`django.shortcuts` module.\n\nThere's also a :func:`~django.shortcuts.get_list_or_404` function, which works\njust as :func:`~django.shortcuts.get_object_or_404` -- except using\n:meth:`~django.db.models.query.QuerySet.filter` instead of\n:meth:`~django.db.models.query.QuerySet.get`. It raises\n:exc:`~django.http.Http404` if the list is empty.\n\nUse the template system\n=======================\n\nBack to the ``detail()`` view for our poll application. Given the context\nvariable ``question``, here's what the ``polls/detail.html`` template might look\nlike:\n\n.. code-block:: html+django\n    :caption: polls/templates/polls/detail.html\n\n    <h1>{{ question.question_text }}</h1>\n    <ul>\n    {% for choice in question.choice_set.all %}\n        <li>{{ choice.choice_text }}</li>\n    {% endfor %}\n    </ul>\n\nThe template system uses dot-lookup syntax to access variable attributes. In\nthe example of ``{{ question.question_text }}``, first Django does a dictionary lookup\non the object ``question``. Failing that, it tries an attribute lookup -- which\nworks, in this case. If attribute lookup had failed, it would've tried a\nlist-index lookup.\n\nMethod-calling happens in the :ttag:`{% for %}<for>` loop:\n``question.choice_set.all`` is interpreted as the Python code\n``question.choice_set.all()``, which returns an iterable of ``Choice`` objects and is\nsuitable for use in the :ttag:`{% for %}<for>` tag.\n\nSee the :doc:`template guide </topics/templates>` for more about templates.\n\nRemoving hardcoded URLs in templates\n====================================\n\nRemember, when we wrote the link to a question in the ``polls/index.html``\ntemplate, the link was partially hardcoded like this:\n\n.. code-block:: html+django\n\n    <li><a href=\"/polls/{{ question.id }}/\">{{ question.question_text }}</a></li>\n\nThe problem with this hardcoded, tightly-coupled approach is that it becomes\nchallenging to change URLs on projects with a lot of templates. However, since\nyou defined the name argument in the :func:`~django.urls.path` functions in\nthe ``polls.urls`` module, you can remove a reliance on specific URL paths\ndefined in your url configurations by using the ``{% url %}`` template tag:\n\n.. code-block:: html+django\n\n    <li><a href=\"{% url 'detail' question.id %}\">{{ question.question_text }}</a></li>\n\nThe way this works is by looking up the URL definition as specified in the\n``polls.urls`` module. You can see exactly where the URL name of 'detail' is\ndefined below::\n\n    ...\n    # the 'name' value as called by the {% url %} template tag\n    path('<int:question_id>/', views.detail, name='detail'),\n    ...\n\nIf you want to change the URL of the polls detail view to something else,\nperhaps to something like ``polls/specifics/12/`` instead of doing it in the\ntemplate (or templates) you would change it in ``polls/urls.py``::\n\n    ...\n    # added the word 'specifics'\n    path('specifics/<int:question_id>/', views.detail, name='detail'),\n    ...\n\nNamespacing URL names\n=====================\n\nThe tutorial project has just one app, ``polls``. In real Django projects,\nthere might be five, ten, twenty apps or more. How does Django differentiate\nthe URL names between them? For example, the ``polls`` app has a ``detail``\nview, and so might an app on the same project that is for a blog. How does one\nmake it so that Django knows which app view to create for a url when using the\n``{% url %}`` template tag?\n\nThe answer is to add namespaces to your  URLconf. In the ``polls/urls.py``\nfile, go ahead and add an ``app_name`` to set the application namespace:\n\n.. code-block:: python\n    :caption: polls/urls.py\n\n    from django.urls import path\n\n    from . import views\n\n    app_name = 'polls'\n    urlpatterns = [\n        path('', views.index, name='index'),\n        path('<int:question_id>/', views.detail, name='detail'),\n        path('<int:question_id>/results/', views.results, name='results'),\n        path('<int:question_id>/vote/', views.vote, name='vote'),\n    ]\n\nNow change your ``polls/index.html`` template from:\n\n.. code-block:: html+django\n    :caption: polls/templates/polls/index.html\n\n    <li><a href=\"{% url 'detail' question.id %}\">{{ question.question_text }}</a></li>\n\nto point at the namespaced detail view:\n\n.. code-block:: html+django\n    :caption: polls/templates/polls/index.html\n\n    <li><a href=\"{% url 'polls:detail' question.id %}\">{{ question.question_text }}</a></li>\n\nWhen you're comfortable with writing views, read :doc:`part 4 of this tutorial\n</intro/tutorial04>` to learn the basics about form processing and generic\nviews.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":224,"nodeType":"TextFile","repoName":null,"name":"whatsnext.txt","path":"docs/intro","text":"=================\nWhat to read next\n=================\n\nSo you've read all the :doc:`introductory material </intro/index>` and have\ndecided you'd like to keep using Django. We've only just scratched the surface\nwith this intro (in fact, if you've read every single word, you've read about\n5% of the overall documentation).\n\nSo what's next?\n\nWell, we've always been big fans of learning by doing. At this point you should\nknow enough to start a project of your own and start fooling around. As you need\nto learn new tricks, come back to the documentation.\n\nWe've put a lot of effort into making Django's documentation useful, clear and\nas complete as possible. The rest of this document explains more about how the\ndocumentation works so that you can get the most out of it.\n\n(Yes, this is documentation about documentation. Rest assured we have no plans\nto write a document about how to read the document about documentation.)\n\nFinding documentation\n=====================\n\nDjango's got a *lot* of documentation -- almost 450,000 words and counting --\nso finding what you need can sometimes be tricky. A good place to start\nis the :ref:`genindex`. We also recommend using the builtin search feature.\n\nOr you can just browse around!\n\nHow the documentation is organized\n==================================\n\nDjango's main documentation is broken up into \"chunks\" designed to fill\ndifferent needs:\n\n* The :doc:`introductory material </intro/index>` is designed for people new\n  to Django -- or to Web development in general. It doesn't cover anything\n  in depth, but instead gives a high-level overview of how developing in\n  Django \"feels\".\n\n* The :doc:`topic guides </topics/index>`, on the other hand, dive deep into\n  individual parts of Django. There are complete guides to Django's\n  :doc:`model system </topics/db/index>`, :doc:`template engine\n  </topics/templates>`, :doc:`forms framework </topics/forms/index>`, and much\n  more.\n\n  This is probably where you'll want to spend most of your time; if you work\n  your way through these guides you should come out knowing pretty much\n  everything there is to know about Django.\n\n* Web development is often broad, not deep -- problems span many domains.\n  We've written a set of :doc:`how-to guides </howto/index>` that answer\n  common \"How do I ...?\" questions. Here you'll find information about\n  :doc:`generating PDFs with Django </howto/outputting-pdf>`, :doc:`writing\n  custom template tags </howto/custom-template-tags>`, and more.\n\n  Answers to really common questions can also be found in the :doc:`FAQ\n  </faq/index>`.\n\n* The guides and how-to's don't cover every single class, function, and\n  method available in Django -- that would be overwhelming when you're\n  trying to learn. Instead, details about individual classes, functions,\n  methods, and modules are kept in the :doc:`reference </ref/index>`. This is\n  where you'll turn to find the details of a particular function or\n  whatever you need.\n\n* If you are interested in deploying a project for public use, our docs have\n  :doc:`several guides</howto/deployment/index>` for various deployment\n  setups as well as a :doc:`deployment checklist</howto/deployment/checklist>`\n  for some things you'll need to think about.\n\n* Finally, there's some \"specialized\" documentation not usually relevant to\n  most developers. This includes the :doc:`release notes </releases/index>` and\n  :doc:`internals documentation </internals/index>` for those who want to add\n  code to Django itself, and a :doc:`few other things that don't fit elsewhere\n  </misc/index>`.\n\n\nHow documentation is updated\n============================\n\nJust as the Django code base is developed and improved on a daily basis, our\ndocumentation is consistently improving. We improve documentation for several\nreasons:\n\n* To make content fixes, such as grammar/typo corrections.\n\n* To add information and/or examples to existing sections that need to be\n  expanded.\n\n* To document Django features that aren't yet documented. (The list of\n  such features is shrinking but exists nonetheless.)\n\n* To add documentation for new features as new features get added, or as\n  Django APIs or behaviors change.\n\nDjango's documentation is kept in the same source control system as its code. It\nlives in the :source:`docs` directory of our Git repository. Each document\nonline is a separate text file in the repository.\n\nWhere to get it\n===============\n\nYou can read Django documentation in several ways. They are, in order of\npreference:\n\nOn the Web\n----------\n\nThe most recent version of the Django documentation lives at\nhttps://docs.djangoproject.com/en/dev/. These HTML pages are generated\nautomatically from the text files in source control. That means they reflect the\n\"latest and greatest\" in Django -- they include the very latest corrections and\nadditions, and they discuss the latest Django features, which may only be\navailable to users of the Django development version. (See\n:ref:`differences-between-doc-versions` below.)\n\nWe encourage you to help improve the docs by submitting changes, corrections and\nsuggestions in the `ticket system`_. The Django developers actively monitor the\nticket system and use your feedback to improve the documentation for everybody.\n\nNote, however, that tickets should explicitly relate to the documentation,\nrather than asking broad tech-support questions. If you need help with your\nparticular Django setup, try the |django-users| mailing list or the `#django\nIRC channel`_ instead.\n\n.. _ticket system: https://code.djangoproject.com/\n.. _#django IRC channel: https://webchat.freenode.net/#django\n\nIn plain text\n-------------\n\nFor offline reading, or just for convenience, you can read the Django\ndocumentation in plain text.\n\nIf you're using an official release of Django, the zipped package (tarball) of\nthe code includes a ``docs/`` directory, which contains all the documentation\nfor that release.\n\nIf you're using the development version of Django (aka the master branch), the\n``docs/`` directory contains all of the documentation. You can update your\nGit checkout to get the latest changes.\n\nOne low-tech way of taking advantage of the text documentation is by using the\nUnix ``grep`` utility to search for a phrase in all of the documentation. For\nexample, this will show you each mention of the phrase \"max_length\" in any\nDjango document:\n\n.. console::\n\n    $ grep -r max_length /path/to/django/docs/\n\nAs HTML, locally\n----------------\n\nYou can get a local copy of the HTML documentation following a few steps:\n\n* Django's documentation uses a system called Sphinx__ to convert from\n  plain text to HTML. You'll need to install Sphinx by either downloading\n  and installing the package from the Sphinx website, or with ``pip``:\n\n  .. console::\n\n        $ python -m pip install Sphinx\n\n* Then, use the included ``Makefile`` to turn the documentation into HTML:\n\n  .. code-block:: console\n\n        $ cd path/to/django/docs\n        $ make html\n\n  You'll need `GNU Make`__ installed for this.\n\n  If you're on Windows you can alternatively use the included batch file:\n\n  .. code-block:: bat\n\n        cd path\\to\\django\\docs\n        make.bat html\n\n* The HTML documentation will be placed in ``docs/_build/html``.\n\n__ https://www.sphinx-doc.org/\n__ https://www.gnu.org/software/make/\n\n.. _differences-between-doc-versions:\n\nDifferences between versions\n============================\n\nThe text documentation in the master branch of the Git repository contains the\n\"latest and greatest\" changes and additions. These changes include\ndocumentation of new features targeted for Django's next :term:`feature\nrelease <Feature release>`. For that reason, it's worth pointing out our policy\nto highlight recent changes and additions to Django.\n\nWe follow this policy:\n\n* The development documentation at https://docs.djangoproject.com/en/dev/ is\n  from the master branch. These docs correspond to the latest feature release,\n  plus whatever features have been added/changed in the framework since then.\n\n* As we add features to Django's development version, we update the\n  documentation in the same Git commit transaction.\n\n* To distinguish feature changes/additions in the docs, we use the phrase:\n  \"New in Django Development version\" for the version of Django that hasn't\n  been released yet, or \"New in version X.Y\" for released versions.\n\n* Documentation fixes and improvements may be backported to the last release\n  branch, at the discretion of the committer, however, once a version of\n  Django is :ref:`no longer supported<supported-versions-policy>`, that version\n  of the docs won't get any further updates.\n\n* The `main documentation Web page`_ includes links to documentation for\n  previous versions. Be sure you are using the version of the docs\n  corresponding to the version of Django you are using!\n\n.. _main documentation Web page: https://docs.djangoproject.com/en/dev/\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":225,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/intro","text":"===============\nGetting started\n===============\n\nNew to Django? Or to Web development in general? Well, you came to the right\nplace: read this material to quickly get up and running.\n\n.. toctree::\n   :maxdepth: 1\n\n   overview\n   install\n   tutorial01\n   tutorial02\n   tutorial03\n   tutorial04\n   tutorial05\n   tutorial06\n   tutorial07\n   reusable-apps\n   whatsnext\n   contributing\n\n.. seealso::\n\n    If you're new to Python_, you might want to start by getting an idea of what\n    the language is like. Django is 100% Python, so if you've got minimal\n    comfort with Python you'll probably get a lot more out of Django.\n\n    If you're new to programming entirely, you might want to start with this\n    `list of Python resources for non-programmers`_\n\n    If you already know a few other languages and want to get up to speed with\n    Python quickly, we recommend `Dive Into Python`_. If that's not quite your\n    style, there are many other `books about Python`_.\n\n    .. _python: https://python.org/\n    .. _list of Python resources for non-programmers: https://wiki.python.org/moin/BeginnersGuide/NonProgrammers\n    .. _Dive Into Python: https://diveinto.org/python3/table-of-contents.html\n    .. _books about Python: https://wiki.python.org/moin/PythonBooks\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":226,"nodeType":"TextFile","repoName":null,"name":"tutorial07.txt","path":"docs/intro","text":"=====================================\nWriting your first Django app, part 7\n=====================================\n\nThis tutorial begins where :doc:`Tutorial 6 </intro/tutorial06>` left off. We're\ncontinuing the Web-poll application and will focus on customizing Django's\nautomatically-generated admin site that we first explored in :doc:`Tutorial 2\n</intro/tutorial02>`.\n\n.. admonition:: Where to get help:\n\n    If you're having trouble going through this tutorial, please head over to\n    the :doc:`Getting Help</faq/help>` section of the FAQ.\n\nCustomize the admin form\n========================\n\nBy registering the ``Question`` model with ``admin.site.register(Question)``,\nDjango was able to construct a default form representation. Often, you'll want\nto customize how the admin form looks and works. You'll do this by telling\nDjango the options you want when you register the object.\n\nLet's see how this works by reordering the fields on the edit form. Replace\nthe ``admin.site.register(Question)`` line with:\n\n.. code-block:: python\n    :caption: polls/admin.py\n\n    from django.contrib import admin\n\n    from .models import Question\n\n\n    class QuestionAdmin(admin.ModelAdmin):\n        fields = ['pub_date', 'question_text']\n\n    admin.site.register(Question, QuestionAdmin)\n\nYou'll follow this pattern -- create a model admin class, then pass it as the\nsecond argument to ``admin.site.register()`` -- any time you need to change the\nadmin options for a model.\n\nThis particular change above makes the \"Publication date\" come before the\n\"Question\" field:\n\n.. image:: _images/admin07.png\n   :alt: Fields have been reordered\n\nThis isn't impressive with only two fields, but for admin forms with dozens\nof fields, choosing an intuitive order is an important usability detail.\n\nAnd speaking of forms with dozens of fields, you might want to split the form\nup into fieldsets:\n\n.. code-block:: python\n    :caption: polls/admin.py\n\n    from django.contrib import admin\n\n    from .models import Question\n\n\n    class QuestionAdmin(admin.ModelAdmin):\n        fieldsets = [\n            (None,               {'fields': ['question_text']}),\n            ('Date information', {'fields': ['pub_date']}),\n        ]\n\n    admin.site.register(Question, QuestionAdmin)\n\nThe first element of each tuple in\n:attr:`~django.contrib.admin.ModelAdmin.fieldsets` is the title of the fieldset.\nHere's what our form looks like now:\n\n.. image:: _images/admin08t.png\n   :alt: Form has fieldsets now\n\nAdding related objects\n======================\n\nOK, we have our Question admin page, but a ``Question`` has multiple\n``Choice``\\s, and the admin page doesn't display choices.\n\nYet.\n\nThere are two ways to solve this problem. The first is to register ``Choice``\nwith the admin just as we did with ``Question``:\n\n.. code-block:: python\n    :caption: polls/admin.py\n\n    from django.contrib import admin\n\n    from .models import Choice, Question\n    # ...\n    admin.site.register(Choice)\n\nNow \"Choices\" is an available option in the Django admin. The \"Add choice\" form\nlooks like this:\n\n.. image:: _images/admin09.png\n   :alt: Choice admin page\n\nIn that form, the \"Question\" field is a select box containing every question in the\ndatabase. Django knows that a :class:`~django.db.models.ForeignKey` should be\nrepresented in the admin as a ``<select>`` box. In our case, only one question\nexists at this point.\n\nAlso note the \"Add Another\" link next to \"Question.\" Every object with a\n``ForeignKey`` relationship to another gets this for free. When you click \"Add\nAnother\", you'll get a popup window with the \"Add question\" form. If you add a question\nin that window and click \"Save\", Django will save the question to the database and\ndynamically add it as the selected choice on the \"Add choice\" form you're\nlooking at.\n\nBut, really, this is an inefficient way of adding ``Choice`` objects to the system.\nIt'd be better if you could add a bunch of Choices directly when you create the\n``Question`` object. Let's make that happen.\n\nRemove the ``register()`` call for the ``Choice`` model. Then, edit the ``Question``\nregistration code to read:\n\n.. code-block:: python\n    :caption: polls/admin.py\n\n    from django.contrib import admin\n\n    from .models import Choice, Question\n\n\n    class ChoiceInline(admin.StackedInline):\n        model = Choice\n        extra = 3\n\n\n    class QuestionAdmin(admin.ModelAdmin):\n        fieldsets = [\n            (None,               {'fields': ['question_text']}),\n            ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),\n        ]\n        inlines = [ChoiceInline]\n\n    admin.site.register(Question, QuestionAdmin)\n\nThis tells Django: \"``Choice`` objects are edited on the ``Question`` admin page. By\ndefault, provide enough fields for 3 choices.\"\n\nLoad the \"Add question\" page to see how that looks:\n\n.. image:: _images/admin10t.png\n   :alt: Add question page now has choices on it\n\nIt works like this: There are three slots for related Choices -- as specified\nby ``extra`` -- and each time you come back to the \"Change\" page for an\nalready-created object, you get another three extra slots.\n\nAt the end of the three current slots you will find an \"Add another Choice\"\nlink.  If you click on it, a new slot will be added. If you want to remove the\nadded slot, you can click on the X to the top right of the added slot. Note\nthat you can't remove the original three slots. This image shows an added slot:\n\n.. image:: _images/admin14t.png\n   :alt: Additional slot added dynamically\n\nOne small problem, though. It takes a lot of screen space to display all the\nfields for entering related ``Choice`` objects. For that reason, Django offers a\ntabular way of displaying inline related objects. To use it, change the\n``ChoiceInline`` declaration to read:\n\n.. code-block:: python\n    :caption: polls/admin.py\n\n    class ChoiceInline(admin.TabularInline):\n        #...\n\nWith that ``TabularInline`` (instead of ``StackedInline``), the\nrelated objects are displayed in a more compact, table-based format:\n\n.. image:: _images/admin11t.png\n   :alt: Add question page now has more compact choices\n\nNote that there is an extra \"Delete?\" column that allows removing rows added\nusing the \"Add Another Choice\" button and rows that have already been saved.\n\nCustomize the admin change list\n===============================\n\nNow that the Question admin page is looking good, let's make some tweaks to the\n\"change list\" page -- the one that displays all the questions in the system.\n\nHere's what it looks like at this point:\n\n.. image:: _images/admin04t.png\n   :alt: Polls change list page\n\nBy default, Django displays the ``str()`` of each object. But sometimes it'd be\nmore helpful if we could display individual fields. To do that, use the\n:attr:`~django.contrib.admin.ModelAdmin.list_display` admin option, which is a\ntuple of field names to display, as columns, on the change list page for the\nobject:\n\n.. code-block:: python\n    :caption: polls/admin.py\n\n    class QuestionAdmin(admin.ModelAdmin):\n        # ...\n        list_display = ('question_text', 'pub_date')\n\nFor good measure, let's also include the ``was_published_recently()`` method\nfrom :doc:`Tutorial 2 </intro/tutorial02>`:\n\n.. code-block:: python\n    :caption: polls/admin.py\n\n    class QuestionAdmin(admin.ModelAdmin):\n        # ...\n        list_display = ('question_text', 'pub_date', 'was_published_recently')\n\nNow the question change list page looks like this:\n\n.. image:: _images/admin12t.png\n   :alt: Polls change list page, updated\n\nYou can click on the column headers to sort by those values -- except in the\ncase of the ``was_published_recently`` header, because sorting by the output\nof an arbitrary method is not supported. Also note that the column header for\n``was_published_recently`` is, by default, the name of the method (with\nunderscores replaced with spaces), and that each line contains the string\nrepresentation of the output.\n\nYou can improve that by giving that method (in :file:`polls/models.py`) a few\nattributes, as follows:\n\n.. code-block:: python\n    :caption: polls/models.py\n\n    class Question(models.Model):\n        # ...\n        def was_published_recently(self):\n            now = timezone.now()\n            return now - datetime.timedelta(days=1) <= self.pub_date <= now\n        was_published_recently.admin_order_field = 'pub_date'\n        was_published_recently.boolean = True\n        was_published_recently.short_description = 'Published recently?'\n\nFor more information on these method properties, see\n:attr:`~django.contrib.admin.ModelAdmin.list_display`.\n\nEdit your :file:`polls/admin.py` file again and add an improvement to the\n``Question`` change list page: filters using the\n:attr:`~django.contrib.admin.ModelAdmin.list_filter`. Add the following line to\n``QuestionAdmin``::\n\n    list_filter = ['pub_date']\n\nThat adds a \"Filter\" sidebar that lets people filter the change list by the\n``pub_date`` field:\n\n.. image:: _images/admin13t.png\n   :alt: Polls change list page, updated\n\nThe type of filter displayed depends on the type of field you're filtering on.\nBecause ``pub_date`` is a :class:`~django.db.models.DateTimeField`, Django\nknows to give appropriate filter options: \"Any date\", \"Today\", \"Past 7 days\",\n\"This month\", \"This year\".\n\nThis is shaping up well. Let's add some search capability::\n\n    search_fields = ['question_text']\n\nThat adds a search box at the top of the change list. When somebody enters\nsearch terms, Django will search the ``question_text`` field. You can use as many\nfields as you'd like -- although because it uses a ``LIKE`` query behind the\nscenes, limiting the number of search fields to a reasonable number will make\nit easier for your database to do the search.\n\nNow's also a good time to note that change lists give you free pagination. The\ndefault is to display 100 items per page. :attr:`Change list pagination\n<django.contrib.admin.ModelAdmin.list_per_page>`, :attr:`search boxes\n<django.contrib.admin.ModelAdmin.search_fields>`, :attr:`filters\n<django.contrib.admin.ModelAdmin.list_filter>`, :attr:`date-hierarchies\n<django.contrib.admin.ModelAdmin.date_hierarchy>`, and\n:attr:`column-header-ordering <django.contrib.admin.ModelAdmin.list_display>`\nall work together like you think they should.\n\nCustomize the admin look and feel\n=================================\n\nClearly, having \"Django administration\" at the top of each admin page is\nridiculous. It's just placeholder text.\n\nYou can change it, though, using Django's template system. The Django admin is\npowered by Django itself, and its interfaces use Django's own template system.\n\n.. _ref-customizing-your-projects-templates:\n\nCustomizing your *project's* templates\n--------------------------------------\n\nCreate a ``templates`` directory in your project directory (the one that\ncontains ``manage.py``). Templates can live anywhere on your filesystem that\nDjango can access. (Django runs as whatever user your server runs.) However,\nkeeping your templates within the project is a good convention to follow.\n\nOpen your settings file (:file:`mysite/settings.py`, remember) and add a\n:setting:`DIRS <TEMPLATES-DIRS>` option in the :setting:`TEMPLATES` setting:\n\n.. code-block:: python\n    :caption: mysite/settings.py\n\n    TEMPLATES = [\n        {\n            'BACKEND': 'django.template.backends.django.DjangoTemplates',\n            'DIRS': [BASE_DIR / 'templates'],\n            'APP_DIRS': True,\n            'OPTIONS': {\n                'context_processors': [\n                    'django.template.context_processors.debug',\n                    'django.template.context_processors.request',\n                    'django.contrib.auth.context_processors.auth',\n                    'django.contrib.messages.context_processors.messages',\n                ],\n            },\n        },\n    ]\n\n:setting:`DIRS <TEMPLATES-DIRS>` is a list of filesystem directories to check\nwhen loading Django templates; it's a search path.\n\n.. admonition:: Organizing templates\n\n    Just like the static files, we *could* have all our templates together, in\n    one big templates directory, and it would work perfectly well. However,\n    templates that belong to a particular application should be placed in that\n    application's template directory (e.g. ``polls/templates``) rather than the\n    project's (``templates``). We'll discuss in more detail in the\n    :doc:`reusable apps tutorial </intro/reusable-apps>` *why* we do this.\n\nNow create a directory called ``admin`` inside ``templates``, and copy the\ntemplate ``admin/base_site.html`` from within the default Django admin\ntemplate directory in the source code of Django itself\n(``django/contrib/admin/templates``) into that directory.\n\n.. admonition:: Where are the Django source files?\n\n    If you have difficulty finding where the Django source files are located\n    on your system, run the following command:\n\n    .. console::\n\n        $ python -c \"import django; print(django.__path__)\"\n\nThen, edit the file and replace\n``{{ site_header|default:_('Django administration') }}`` (including the curly\nbraces) with your own site's name as you see fit. You should end up with\na section of code like:\n\n.. code-block:: html+django\n\n    {% block branding %}\n    <h1 id=\"site-name\"><a href=\"{% url 'admin:index' %}\">Polls Administration</a></h1>\n    {% endblock %}\n\nWe use this approach to teach you how to override templates. In an actual\nproject, you would probably use\nthe :attr:`django.contrib.admin.AdminSite.site_header` attribute to more easily\nmake this particular customization.\n\nThis template file contains lots of text like ``{% block branding %}``\nand ``{{ title }}``. The ``{%`` and ``{{`` tags are part of Django's\ntemplate language. When Django renders ``admin/base_site.html``, this\ntemplate language will be evaluated to produce the final HTML page, just like\nwe saw in :doc:`Tutorial 3 </intro/tutorial03>`.\n\nNote that any of Django's default admin templates can be overridden. To\noverride a template, do the same thing you did with ``base_site.html`` -- copy\nit from the default directory into your custom directory, and make changes.\n\nCustomizing your *application's* templates\n------------------------------------------\n\nAstute readers will ask: But if :setting:`DIRS <TEMPLATES-DIRS>` was empty by\ndefault, how was Django finding the default admin templates? The answer is\nthat, since :setting:`APP_DIRS <TEMPLATES-APP_DIRS>` is set to ``True``,\nDjango automatically looks for a ``templates/`` subdirectory within each\napplication package, for use as a fallback (don't forget that\n``django.contrib.admin`` is an application).\n\nOur poll application is not very complex and doesn't need custom admin\ntemplates. But if it grew more sophisticated and required modification of\nDjango's standard admin templates for some of its functionality, it would be\nmore sensible to modify the *application's* templates, rather than those in the\n*project*. That way, you could include the polls application in any new project\nand be assured that it would find the custom templates it needed.\n\nSee the :ref:`template loading documentation <template-loading>` for more\ninformation about how Django finds its templates.\n\nCustomize the admin index page\n==============================\n\nOn a similar note, you might want to customize the look and feel of the Django\nadmin index page.\n\nBy default, it displays all the apps in :setting:`INSTALLED_APPS` that have been\nregistered with the admin application, in alphabetical order. You may want to\nmake significant changes to the layout. After all, the index is probably the\nmost important page of the admin, and it should be easy to use.\n\nThe template to customize is ``admin/index.html``. (Do the same as with\n``admin/base_site.html`` in the previous section -- copy it from the default\ndirectory to your custom template directory). Edit the file, and you'll see it\nuses a template variable called ``app_list``. That variable contains every\ninstalled Django app. Instead of using that, you can hard-code links to\nobject-specific admin pages in whatever way you think is best.\n\nWhat's next?\n============\n\nThe beginner tutorial ends here. In the meantime, you might want to check out\nsome pointers on :doc:`where to go from here </intro/whatsnext>`.\n\nIf you are familiar with Python packaging and interested in learning how to\nturn polls into a \"reusable app\", check out :doc:`Advanced tutorial: How to\nwrite reusable apps</intro/reusable-apps>`.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":227,"nodeType":"TextFile","repoName":null,"name":"reusable-apps.txt","path":"docs/intro","text":"=============================================\nAdvanced tutorial: How to write reusable apps\n=============================================\n\nThis advanced tutorial begins where :doc:`Tutorial 7 </intro/tutorial07>`\nleft off. We'll be turning our Web-poll into a standalone Python package\nyou can reuse in new projects and share with other people.\n\nIf you haven't recently completed Tutorials 1–7, we encourage you to review\nthese so that your example project matches the one described below.\n\nReusability matters\n===================\n\nIt's a lot of work to design, build, test and maintain a web application. Many\nPython and Django projects share common problems. Wouldn't it be great if we\ncould save some of this repeated work?\n\nReusability is the way of life in Python. `The Python Package Index (PyPI)\n<https://pypi.org/>`_ has a vast range of packages you can use in your own\nPython programs. Check out `Django Packages <https://djangopackages.org>`_ for\nexisting reusable apps you could incorporate in your project. Django itself is\nalso a normal Python package. This means that you can take existing Python\npackages or Django apps and compose them into your own web project. You only\nneed to write the parts that make your project unique.\n\nLet's say you were starting a new project that needed a polls app like the one\nwe've been working on. How do you make this app reusable? Luckily, you're well\non the way already. In :doc:`Tutorial 1 </intro/tutorial01>`, we saw how we\ncould decouple polls from the project-level URLconf using an ``include``.\nIn this tutorial, we'll take further steps to make the app easy to use in new\nprojects and ready to publish for others to install and use.\n\n.. admonition:: Package? App?\n\n    A Python :term:`package` provides a way of grouping related Python code for\n    easy reuse. A package contains one or more files of Python code (also known\n    as \"modules\").\n\n    A package can be imported with ``import foo.bar`` or ``from foo import\n    bar``. For a directory (like ``polls``) to form a package, it must contain\n    a special file ``__init__.py``, even if this file is empty.\n\n    A Django *application* is a Python package that is specifically intended\n    for use in a Django project. An application may use common Django\n    conventions, such as having ``models``, ``tests``, ``urls``, and ``views``\n    submodules.\n\n    Later on we use the term *packaging* to describe the process of making a\n    Python package easy for others to install. It can be a little confusing, we\n    know.\n\nYour project and your reusable app\n==================================\n\nAfter the previous tutorials, our project should look like this::\n\n    mysite/\n        manage.py\n        mysite/\n            __init__.py\n            settings.py\n            urls.py\n            asgi.py\n            wsgi.py\n        polls/\n            __init__.py\n            admin.py\n            apps.py\n            migrations/\n                __init__.py\n                0001_initial.py\n            models.py\n            static/\n                polls/\n                    images/\n                        background.gif\n                    style.css\n            templates/\n                polls/\n                    detail.html\n                    index.html\n                    results.html\n            tests.py\n            urls.py\n            views.py\n        templates/\n            admin/\n                base_site.html\n\nYou created ``mysite/templates`` in :doc:`Tutorial 7 </intro/tutorial07>`,\nand ``polls/templates`` in :doc:`Tutorial 3 </intro/tutorial03>`. Now perhaps\nit is clearer why we chose to have separate template directories for the\nproject and application: everything that is part of the polls application is in\n``polls``. It makes the application self-contained and easier to drop into a\nnew project.\n\nThe ``polls`` directory could now be copied into a new Django project and\nimmediately reused. It's not quite ready to be published though. For that, we\nneed to package the app to make it easy for others to install.\n\n.. _installing-reusable-apps-prerequisites:\n\nInstalling some prerequisites\n=============================\n\nThe current state of Python packaging is a bit muddled with various tools. For\nthis tutorial, we're going to use setuptools_ to build our package. It's the\nrecommended packaging tool (merged with the ``distribute`` fork). We'll also be\nusing `pip`_ to install and uninstall it. You should install these\ntwo packages now. If you need help, you can refer to :ref:`how to install\nDjango with pip<installing-official-release>`. You can install ``setuptools``\nthe same way.\n\n.. _setuptools: https://pypi.org/project/setuptools/\n.. _pip: https://pypi.org/project/pip/\n\nPackaging your app\n==================\n\nPython *packaging* refers to preparing your app in a specific format that can\nbe easily installed and used. Django itself is packaged very much like\nthis. For a small app like polls, this process isn't too difficult.\n\n#. First, create a parent directory for ``polls``, outside of your Django\n   project. Call this directory ``django-polls``.\n\n   .. admonition::  Choosing a name for your app\n\n       When choosing a name for your package, check resources like PyPI to avoid\n       naming conflicts with existing packages. It's often useful to prepend\n       ``django-`` to your module name when creating a package to distribute.\n       This helps others looking for Django apps identify your app as Django\n       specific.\n\n       Application labels (that is, the final part of the dotted path to\n       application packages) *must* be unique in :setting:`INSTALLED_APPS`.\n       Avoid using the same label as any of the Django :doc:`contrib packages\n       </ref/contrib/index>`, for example ``auth``, ``admin``, or\n       ``messages``.\n\n#. Move the ``polls`` directory into the ``django-polls`` directory.\n\n#. Create a file ``django-polls/README.rst`` with the following contents:\n\n   .. code-block:: rst\n       :caption: django-polls/README.rst\n\n       =====\n       Polls\n       =====\n\n       Polls is a Django app to conduct Web-based polls. For each question,\n       visitors can choose between a fixed number of answers.\n\n       Detailed documentation is in the \"docs\" directory.\n\n       Quick start\n       -----------\n\n       1. Add \"polls\" to your INSTALLED_APPS setting like this::\n\n           INSTALLED_APPS = [\n               ...\n               'polls',\n           ]\n\n       2. Include the polls URLconf in your project urls.py like this::\n\n           path('polls/', include('polls.urls')),\n\n       3. Run ``python manage.py migrate`` to create the polls models.\n\n       4. Start the development server and visit http://127.0.0.1:8000/admin/\n          to create a poll (you'll need the Admin app enabled).\n\n       5. Visit http://127.0.0.1:8000/polls/ to participate in the poll.\n\n#. Create a ``django-polls/LICENSE`` file. Choosing a license is beyond the\n   scope of this tutorial, but suffice it to say that code released publicly\n   without a license is *useless*. Django and many Django-compatible apps are\n   distributed under the BSD license; however, you're free to pick your own\n   license. Just be aware that your licensing choice will affect who is able\n   to use your code.\n\n#. Next we'll create ``setup.cfg`` and ``setup.py`` files which detail how to\n   build and install the app. A full explanation of these files is beyond the\n   scope of this tutorial, but the `setuptools documentation\n   <https://setuptools.readthedocs.io/en/latest/>`_ has a good explanation.\n   Create the files ``django-polls/setup.cfg`` and ``django-polls/setup.py``\n   with the following contents:\n\n   .. code-block:: ini\n        :caption: django-polls/setup.cfg\n\n        [metadata]\n        name = django-polls\n        version = 0.1\n        description = A Django app to conduct Web-based polls.\n        long_description = file: README.rst\n        url = https://www.example.com/\n        author = Your Name\n        author_email = yourname@example.com\n        license = BSD-3-Clause  # Example license\n        classifiers =\n            Environment :: Web Environment\n            Framework :: Django\n            Framework :: Django :: X.Y  # Replace \"X.Y\" as appropriate\n            Intended Audience :: Developers\n            License :: OSI Approved :: BSD License\n            Operating System :: OS Independent\n            Programming Language :: Python\n            Programming Language :: Python :: 3\n            Programming Language :: Python :: 3 :: Only\n            Programming Language :: Python :: 3.6\n            Programming Language :: Python :: 3.7\n            Programming Language :: Python :: 3.8\n            Topic :: Internet :: WWW/HTTP\n            Topic :: Internet :: WWW/HTTP :: Dynamic Content\n\n        [options]\n        include_package_data = true\n        packages = find:\n\n   .. code-block:: python\n        :caption: django-polls/setup.py\n\n        from setuptools import setup\n\n        setup()\n\n#. Only Python modules and packages are included in the package by default. To\n   include additional files, we'll need to create a ``MANIFEST.in`` file. The\n   setuptools docs referred to in the previous step discuss this file in more\n   details. To include the templates, the ``README.rst`` and our ``LICENSE``\n   file, create a file ``django-polls/MANIFEST.in`` with the following\n   contents:\n\n   .. code-block:: text\n       :caption: django-polls/MANIFEST.in\n\n       include LICENSE\n       include README.rst\n       recursive-include polls/static *\n       recursive-include polls/templates *\n\n#. It's optional, but recommended, to include detailed documentation with your\n   app. Create an empty directory ``django-polls/docs`` for future\n   documentation. Add an additional line to ``django-polls/MANIFEST.in``::\n\n    recursive-include docs *\n\n   Note that the ``docs`` directory won't be included in your package unless\n   you add some files to it. Many Django apps also provide their documentation\n   online through sites like `readthedocs.org <https://readthedocs.org>`_.\n\n#. Try building your package with ``python setup.py sdist`` (run from inside\n   ``django-polls``). This creates a directory called ``dist`` and builds your\n   new package, ``django-polls-0.1.tar.gz``.\n\nFor more information on packaging, see Python's `Tutorial on Packaging and\nDistributing Projects\n<https://packaging.python.org/tutorials/packaging-projects/>`_.\n\nUsing your own package\n======================\n\nSince we moved the ``polls`` directory out of the project, it's no longer\nworking. We'll now fix this by installing our new ``django-polls`` package.\n\n.. admonition:: Installing as a user library\n\n   The following steps install ``django-polls`` as a user library. Per-user\n   installs have a lot of advantages over installing the package system-wide,\n   such as being usable on systems where you don't have administrator access\n   as well as preventing the package from affecting system services and other\n   users of the machine.\n\n   Note that per-user installations can still affect the behavior of system\n   tools that run as that user, so ``virtualenv`` is a more robust solution\n   (see below).\n\n#. To install the package, use pip (you already :ref:`installed it\n   <installing-reusable-apps-prerequisites>`, right?)::\n\n    python -m pip install --user django-polls/dist/django-polls-0.1.tar.gz\n\n#. With luck, your Django project should now work correctly again. Run the\n   server again to confirm this.\n\n#. To uninstall the package, use pip::\n\n    python -m pip uninstall django-polls\n\nPublishing your app\n===================\n\nNow that we've packaged and tested ``django-polls``, it's ready to share with\nthe world! If this wasn't just an example, you could now:\n\n* Email the package to a friend.\n\n* Upload the package on your website.\n\n* Post the package on a public repository, such as `the Python Package Index\n  (PyPI)`_. `packaging.python.org <https://packaging.python.org>`_ has `a good\n  tutorial <https://packaging.python.org/tutorials/packaging-projects/#uploading-the-distribution-archives>`_\n  for doing this.\n\nInstalling Python packages with virtualenv\n==========================================\n\nEarlier, we installed the polls app as a user library. This has some\ndisadvantages:\n\n* Modifying the user libraries can affect other Python software on your system.\n\n* You won't be able to run multiple versions of this package (or others with\n  the same name).\n\nTypically, these situations only arise once you're maintaining several Django\nprojects. When they do, the best solution is to use `virtualenv\n<https://virtualenv.pypa.io/>`_. This tool allows you to maintain multiple\nisolated Python environments, each with its own copy of the libraries and\npackage namespace.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":228,"nodeType":"Package","repoName":null,"name":"docs/_theme/djangodocs","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":229,"nodeType":"TextFile","repoName":null,"name":"modindex.html","path":"docs/_theme/djangodocs","text":"{% extends \"basic/modindex.html\" %}\n{% block bodyclass %}{% endblock %}\n{% block sidebarwrapper %}{% endblock %}\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":230,"nodeType":"TextFile","repoName":null,"name":"search.html","path":"docs/_theme/djangodocs","text":"{% extends \"basic/search.html\" %}\n{% block bodyclass %}{% endblock %}\n{% block sidebarwrapper %}{% endblock %}\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":231,"nodeType":"TextFile","repoName":null,"name":"genindex.html","path":"docs/_theme/djangodocs","text":"{% extends \"basic/genindex.html\" %}\n\n{% block bodyclass %}{% endblock %}\n{% block sidebarwrapper %}{% endblock %}\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":232,"nodeType":"Package","repoName":null,"name":"docs/_theme/djangodocs/static/fontawesome/css","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":233,"nodeType":"TextFile","repoName":null,"name":"fa-brands.min.css","path":"docs/_theme/djangodocs/static/fontawesome/css","text":"/*!\n * Font Awesome Free 5.0.4 by @fontawesome - http://fontawesome.com\n * License - http://fontawesome.com/license (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)\n */\n@font-face{font-family:Font Awesome\\ 5 Brands;font-style:normal;font-weight:400;src:url(../webfonts/fa-brands-400.eot);src:url(../webfonts/fa-brands-400.eot?#iefix) format(\"embedded-opentype\"),url(../webfonts/fa-brands-400.woff2) format(\"woff2\"),url(../webfonts/fa-brands-400.woff) format(\"woff\"),url(../webfonts/fa-brands-400.ttf) format(\"truetype\"),url(../webfonts/fa-brands-400.svg#fontawesome) format(\"svg\")}.fab{font-family:Font Awesome\\ 5 Brands}","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":234,"nodeType":"Package","repoName":null,"name":"docs/_theme/djangodocs/static/fontawesome","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":235,"nodeType":"TextFile","repoName":null,"name":"LICENSE.txt","path":"docs/_theme/djangodocs/static/fontawesome","text":"Font Awesome Free License\n-------------------------\n\nFont Awesome Free is free, open source, and GPL friendly. You can use it for\ncommercial projects, open source projects, or really almost whatever you want.\nFull Font Awesome Free license: https://fontawesome.com/license.\n\n# Icons: CC BY 4.0 License (https://creativecommons.org/licenses/by/4.0/)\nIn the Font Awesome Free download, the CC BY 4.0 license applies to all icons\npackaged as SVG and JS file types.\n\n# Fonts: SIL OFL 1.1 License (https://scripts.sil.org/OFL)\nIn the Font Awesome Free download, the SIL OLF license applies to all icons\npackaged as web and desktop font files.\n\n# Code: MIT License (https://opensource.org/licenses/MIT)\nIn the Font Awesome Free download, the MIT license applies to all non-font and\nnon-icon files.\n\n# Attribution\nAttribution is required by MIT, SIL OLF, and CC BY licenses. Downloaded Font\nAwesome Free files already contain embedded comments with sufficient\nattribution, so you shouldn't need to do anything additional when using these\nfiles normally.\n\nWe've kept attribution comments terse, so we ask that you do not actively work\nto remove them from files, especially code. They're a great way for folks to \nlearn about Font Awesome.\n\n# Brand Icons\nAll brand icons are trademarks of their respective owners. The use of these\ntrademarks does not indicate endorsement of the trademark holder by Font\nAwesome, nor vice versa. **Please do not use brand logos for any purpose except\nto represent the company, product, or service to which they refer.**\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":236,"nodeType":"TextFile","repoName":null,"name":"djangodocs.css","path":"docs/_theme/djangodocs/static","text":"/*** setup ***/\nhtml { background:#092e20;}\nbody { font:12px/1.5 Verdana,sans-serif; background:#092e20; color: white;}\n#custom-doc { width:76.54em;*width:74.69em;min-width:995px; max-width:100em; margin:auto; text-align:left; padding-top:16px; margin-top:0;}\n#hd { padding: 4px 0 12px 0; }\n#bd { background:#234F32; }\n#ft { color:#487858; font-size:90%; padding-bottom: 2em; }\n\n/*** links ***/\na {text-decoration: none;}\na img {border: none;}\na:link, a:visited { color:#ffc757; }\n#bd a:link, #bd a:visited { color:#ab5603; text-decoration:underline; }\n#bd #sidebar a:link, #bd #sidebar a:visited { color:#ffc757; text-decoration:none; }\na:hover { color:#ffe761; }\n#bd a:hover { background-color:#E0FFB8; color:#234f32; text-decoration:none; }\n#bd #sidebar a:hover { color:#ffe761; background:none; }\nh2 a, h3 a, h4 a { text-decoration:none !important; }\na.reference em { font-style: normal; }\n\n/*** sidebar ***/\n#sidebar div.sphinxsidebarwrapper { font-size:92%; margin-right: 14px; }\n#sidebar h3, #sidebar h4 { color: white; font-size: 125%; }\n#sidebar a { color: white; }\n#sidebar ul ul { margin-top:0; margin-bottom:0; }\n#sidebar li { margin-top: 0.2em; margin-bottom: 0.2em; }\n\n/*** nav ***/\ndiv.nav { margin: 0; font-size: 11px; text-align: right; color: #487858;}\n#hd div.nav { margin-top: -27px; }\n#ft div.nav { margin-bottom: -18px; }\n#hd h1 a { color: white; }\n#global-nav { position:absolute; top:5px; margin-left: -5px; padding:7px 0; color:#263E2B; }\n#global-nav a:link, #global-nav a:visited {color:#487858;}\n#global-nav a {padding:0 4px;}\n#global-nav a.about {padding-left:0;}\n#global-nav:hover {color:#fff;}\n#global-nav:hover a:link, #global-nav:hover a:visited  { color:#ffc757; }\n\n/*** content ***/\n#yui-main div.yui-b { position: relative; }\n#yui-main div.yui-b { margin: 0 0 0 20px; background: white; color: black; padding: 0.3em 2em 1em 2em; }\n\n/*** basic styles ***/\ndd { margin-left:15px; }\nh1,h2,h3,h4,h5 { margin-top:1em; font-family:\"Trebuchet MS\",sans-serif; font-weight:normal; }\nh1 { font-size:218%; margin-top:0.6em; margin-bottom:.4em; line-height:1.1em; }\nh2 { font-size:175%; margin-bottom:.6em; line-height:1.2em; color:#092e20; }\nh3 { font-size:150%; font-weight:bold; margin-bottom:.2em; color:#487858; }\nh4 { font-size:125%; font-weight:bold; margin-top:1.5em; margin-bottom:3px; }\nh5 { font-size:110%; font-weight:bold; margin-top:1em; margin-bottom:3px; }\ndiv.figure { text-align: center; }\ndiv.figure p.caption { font-size:1em; margin-top:0; margin-bottom:1.5em; color: #555;}\nhr { color:#ccc; background-color:#ccc; height:1px; border:0; }\np, ul, dl { margin-top:.6em; margin-bottom:1em; padding-bottom: 0.1em;}\n#yui-main div.yui-b img { max-width: 50em; margin-left: auto; margin-right: auto; display: block; }\ncaption { font-size:1em; font-weight:bold; margin-top:0.5em; margin-bottom:0.5em; margin-left: 2px; text-align: center; }\nblockquote { padding: 0 1em; margin: 1em 0; font:125%/1.2em \"Trebuchet MS\", sans-serif; color:#234f32; border-left:2px solid #94da3a; }\nstrong { font-weight: bold; }\nem { font-style: italic; }\nins { font-weight: bold; text-decoration: none; }\n\n/*** lists ***/\nul { padding-left:30px; }\nol { padding-left:30px; }\nol.arabic li { list-style-type: decimal; }\nul li { list-style-type:square; margin-bottom:.4em; }\nul ul li { list-style-type:disc; }\nul ul ul li { list-style-type:circle; }\nol li { margin-bottom: .4em; }\nul ul { padding-left:1.2em; }\nul ul ul { padding-left:1em; }\nul.linklist, ul.toc { padding-left:0; }\nul.toc ul { margin-left:.6em; }\nul.toc ul li { list-style-type:square; }\nul.toc ul ul li { list-style-type:disc; }\nul.linklist li, ul.toc li { list-style-type:none; }\ndt { font-weight:bold; margin-top:.5em; font-size:1.1em; }\ndd { margin-bottom:.8em; }\nol.toc { margin-bottom: 2em; }\nol.toc li { font-size:125%; padding: .5em; line-height:1.2em; clear: right; }\nol.toc li.b { background-color: #E0FFB8; }\nol.toc li a:hover { background-color: transparent !important; text-decoration: underline !important; }\nol.toc span.release-date { color:#487858; float: right; font-size: 85%; padding-right: .5em; }\nol.toc span.comment-count { font-size: 75%; color: #999; }\n\n/*** tables ***/\ntable { color:#000; margin-bottom: 1em; width: 100%; }\ntable.docutils td p { margin-top:0; margin-bottom:.5em; }\ntable.docutils td, table.docutils th { border-bottom:1px solid #dfdfdf; padding:4px 2px;}\ntable.docutils thead th { border-bottom:2px solid #dfdfdf; text-align:left; font-weight: bold; white-space: nowrap; }\ntable.docutils thead th p { margin: 0; padding: 0; }\ntable.docutils { border-collapse:collapse; }\n\n/*** code blocks ***/\n.literal { color:#234f32; white-space:nowrap; }\ndt > tt.literal { white-space: normal; }\n#sidebar .literal { color:white; background:transparent; font-size:11px; }\nh4 .literal { color: #234f32; font-size: 13px; }\npre { font-size:small; background:#E0FFB8; border:1px solid #94da3a; border-width:1px 0; margin: 1em 0; padding: .3em .4em; overflow: hidden; line-height: 1.3em; white-space: pre-wrap;}\ndt .literal, table .literal { background:none; }\n#bd a.reference { text-decoration: none; }\n#bd a.reference tt.literal { border-bottom: 1px #234f32 dotted; }\ndiv.code-block-caption { color: white; background-color: #234F32; margin: 0; padding: 2px 5px; width: 100%; font-family: monospace; font-size: small; line-height: 1.3em; }\ndiv.literal-block-wrapper pre { margin-top: 0; }\n\n/* Restore colors of pygments hyperlinked code */\n#bd .highlight .k a:link, #bd .highlight .k a:visited { color: #000000; text-decoration: none; border-bottom: 1px dotted #000000; }\n#bd .highlight .nf a:link, #bd .highlight .nf a:visited { color: #990000; text-decoration: none; border-bottom: 1px dotted #990000; }\n\n\n/*** notes & admonitions ***/\n.note, .admonition { padding:.8em 1em .8em; margin: 1em 0; border:1px solid #94da3a; }\n.admonition-title { font-weight:bold; margin-top:0 !important; margin-bottom:0 !important;}\n.admonition .last { margin-bottom:0 !important; }\n.note, .admonition { padding-left:65px; background:url(docicons-note.png) .8em .8em no-repeat;}\ndiv.admonition-philosophy { padding-left:65px; background:url(docicons-philosophy.png) .8em .8em no-repeat;}\ndiv.admonition-behind-the-scenes { padding-left:65px; background:url(docicons-behindscenes.png) .8em .8em no-repeat;}\n.admonition.warning { background:url(docicons-warning.png) .8em .8em no-repeat; border:1px solid #ffc83c;}\n\n/*** versionadded/changes ***/\ndiv.versionadded, div.versionchanged {  }\ndiv.versionadded span.title, div.versionchanged span.title, span.versionmodified { font-weight: bold; }\ndiv.versionadded, div.versionchanged, div.deprecated { color:#555; }\n\n/*** p-links ***/\na.headerlink { color: #c60f0f; font-size: 0.8em; padding: 0 4px 0 4px; text-decoration: none; visibility: hidden; }\nh1:hover > a.headerlink, h2:hover > a.headerlink, h3:hover > a.headerlink, h4:hover > a.headerlink, h5:hover > a.headerlink, h6:hover > a.headerlink, dt:hover > a.headerlink { visibility: visible; }\n\n/*** index ***/\ntable.indextable td { text-align: left; vertical-align: top;}\ntable.indextable dl, table.indextable dd { margin-top: 0; margin-bottom: 0; }\ntable.indextable tr.pcap { height: 10px; }\ntable.indextable tr.cap { margin-top: 10px; background-color: #f2f2f2;}\n\n/*** page-specific overrides ***/\ndiv#contents ul { margin-bottom: 0;}\ndiv#contents ul li { margin-bottom: 0;}\ndiv#contents ul ul li { margin-top: 0.3em;}\n\n/*** IE hacks ***/\n* pre { width: 100%; }\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":237,"nodeType":"TextFile","repoName":null,"name":"console-tabs.css","path":"docs/_theme/djangodocs/static","text":"@import url(\"{{ pathto('_static/fontawesome/css/fa-brands.min.css', 1) }}\");\n\n.console-block {\n  text-align: right;\n}\n\n.console-block *:before,\n.console-block *:after {\n  box-sizing: border-box;\n}\n\n.console-block > section {\n  display: none;\n  text-align: left;\n}\n\n.console-block > input.c-tab-unix,\n.console-block > input.c-tab-win {\n  display: none;\n}\n\n.console-block > label {\n  display: inline-block;\n  padding: 4px 8px;\n  font-weight: normal;\n  text-align: center;\n  color: #bbb;\n  border: 1px solid transparent;\n  font-family: fontawesome;\n}\n\n.console-block > input:checked + label {\n  color: #555;\n  border: 1px solid #ddd;\n  border-top: 2px solid #ab5603;\n  border-bottom: 1px solid #fff;\n}\n\n.console-block > .c-tab-unix:checked ~ .c-content-unix,\n.console-block > .c-tab-win:checked  ~ .c-content-win {\n  display: block;\n}\n\n.console-block pre {\n  margin-top: 0px;\n}\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":238,"nodeType":"TextFile","repoName":null,"name":"default.css","path":"docs/_theme/djangodocs/static","text":"@import url(reset-fonts-grids.css);\n@import url(djangodocs.css);\n@import url(homepage.css);\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":239,"nodeType":"TextFile","repoName":null,"name":"homepage.css","path":"docs/_theme/djangodocs/static","text":"#index p.rubric { font-size:150%; font-weight:normal; margin-bottom:.2em; color:#487858; }\n\n#index div.section dt { font-weight: normal; }\n\n#index #s-getting-help { float: right; width: 35em; background: #E1ECE2; padding: 1em; margin: 2em 0 2em 2em; }\n#index #s-getting-help h2 { margin: 0; }\n\n#index #s-django-documentation div.section div.section h3 { margin: 0; }\n#index #s-django-documentation div.section div.section { background: #E1ECE2; padding: 1em; margin: 2em 0 2em 40.3em; }\n#index #s-django-documentation div.section div.section a.reference { white-space: nowrap; }\n\n#index #s-using-django dl,\n#index #s-add-on-contrib-applications dl,\n#index #s-solving-specific-problems dl,\n#index #s-reference dl\n    { float: left; width: 41em; }\n\n#index #s-add-on-contrib-applications,\n#index #s-solving-specific-problems,\n#index #s-reference,\n#index #s-and-all-the-rest\n    { clear: left; }\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":240,"nodeType":"TextFile","repoName":null,"name":"theme.conf","path":"docs/_theme/djangodocs","text":"[theme]\ninherit = basic\nstylesheet = default.css\npygments_style = trac\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":241,"nodeType":"Package","repoName":null,"name":"docs/_theme/djangodocs-epub","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":242,"nodeType":"TextFile","repoName":null,"name":"theme.conf","path":"docs/_theme/djangodocs-epub","text":"[theme]\ninherit = epub\nstylesheet = epub.css\npygments_style = trac\n\n[options]\nrelbar1 = false\nfooter = false\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":243,"nodeType":"Package","repoName":null,"name":"docs/_theme/djangodocs-epub/static","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":244,"nodeType":"TextFile","repoName":null,"name":"epub.css","path":"docs/_theme/djangodocs-epub/static","text":"h1 { margin-top: 0; }\n\n/* Keep lists a bit narrow to maximize page estate regarding width. */\nol, ul {\n    margin: 0;\n    padding: 0 0 0 1.3em;\n}\n\n/* Images should never exceed the width of the page. */\nimg { max-width: 100%; }\n\n/* Don't display URL after links, this is not print. */\n.link-target { display: none; }\n\n/* This is the front cover page of the book. */\n.epub-cover { text-align: center; }\n.epub-cover h1 { margin: 4em 0 0 0; }\n.epub-cover h2 { margin: 1em 0; }\n.epub-cover h3 { margin: 3em 0 2em 0; }\n\n/* Code examples should never exceed the width of the page, so wrap instead. */\npre, span.pre { white-space: pre-wrap; }\n\npre {\n    background-color: #f6f6f6;\n    border: 0;\n    padding: 0.5em;\n    font-size: 90%;\n}\n\n/* Header for some code blocks. */\n.code-block-caption {\n    background-color: #393939;\n    color: white;\n    margin: 0;\n    padding: 0.5em;\n    font: bold 90% monospace;\n}\n.literal-block-wrapper pre {\n    margin-top: 0;\n}\n\na:link, a:visited { color: #396623; }\na:hover { color: #1d3311; }\n\n/* Use special styled note boxes from the default theme, but with the left side\nfitted after the icon, to allow text resizing with breaking. */\n.note, .admonition {\n    background-position: 9px 0.8em;\n    background-repeat: no-repeat;\n    padding: 0.8em 1em 0.8em 65px;\n    margin: 1em 0;\n    border: 0.01em solid black;\n}\n\n.note, .admonition { background-image: url(docicons-note.png); }\ndiv.admonition-philosophy { background-image: url(docicons-philosophy.png); }\ndiv.admonition-behind-the-scenes { background-image: url(docicons-behindscenes.png); }\n.admonition.warning { background-image: url(docicons-warning.png); }\n\n.admonition-title {\n    font-weight: bold;\n    margin: 0;\n}\n\n.admonition .last { margin-bottom: 0; }\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":245,"nodeType":"Package","repoName":null,"name":"docs/topics","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":246,"nodeType":"TextFile","repoName":null,"name":"pagination.txt","path":"docs/topics","text":"==========\nPagination\n==========\n\nDjango provides high-level and low-level ways to help you manage paginated data\n-- that is, data that's split across several pages, with \"Previous/Next\" links.\n\nThe ``Paginator`` class\n=======================\n\nUnder the hood, all methods of pagination use the\n:class:`~django.core.paginator.Paginator` class. It does all the heavy lifting\nof actually splitting a ``QuerySet`` into :class:`~django.core.paginator.Page`\nobjects.\n\nExample\n=======\n\nGive :class:`~django.core.paginator.Paginator` a list of objects, plus the\nnumber of items you'd like to have on each page, and it gives you methods for\naccessing the items for each page::\n\n    >>> from django.core.paginator import Paginator\n    >>> objects = ['john', 'paul', 'george', 'ringo']\n    >>> p = Paginator(objects, 2)\n\n    >>> p.count\n    4\n    >>> p.num_pages\n    2\n    >>> type(p.page_range)\n    <class 'range_iterator'>\n    >>> p.page_range\n    range(1, 3)\n\n    >>> page1 = p.page(1)\n    >>> page1\n    <Page 1 of 2>\n    >>> page1.object_list\n    ['john', 'paul']\n\n    >>> page2 = p.page(2)\n    >>> page2.object_list\n    ['george', 'ringo']\n    >>> page2.has_next()\n    False\n    >>> page2.has_previous()\n    True\n    >>> page2.has_other_pages()\n    True\n    >>> page2.next_page_number()\n    Traceback (most recent call last):\n    ...\n    EmptyPage: That page contains no results\n    >>> page2.previous_page_number()\n    1\n    >>> page2.start_index() # The 1-based index of the first item on this page\n    3\n    >>> page2.end_index() # The 1-based index of the last item on this page\n    4\n\n    >>> p.page(0)\n    Traceback (most recent call last):\n    ...\n    EmptyPage: That page number is less than 1\n    >>> p.page(3)\n    Traceback (most recent call last):\n    ...\n    EmptyPage: That page contains no results\n\n.. note::\n\n    Note that you can give ``Paginator`` a list/tuple, a Django ``QuerySet``,\n    or any other object with a ``count()`` or ``__len__()`` method. When\n    determining the number of objects contained in the passed object,\n    ``Paginator`` will first try calling ``count()``, then fallback to using\n    ``len()`` if the passed object has no ``count()`` method. This allows\n    objects such as Django's ``QuerySet`` to use a more efficient ``count()``\n    method when available.\n\nPaginating a ``ListView``\n=========================\n\n:class:`django.views.generic.list.ListView` provides a builtin way to paginate\nthe displayed list. You can do this by adding a\n:attr:`~django.views.generic.list.MultipleObjectMixin.paginate_by` attribute to\nyour view class, for example::\n\n    from django.views.generic import ListView\n\n    from myapp.models import Contact\n\n    class ContactList(ListView):\n        paginate_by = 2\n        model = Contact\n\nThis limits the number of objects per page and adds a ``paginator`` and\n``page_obj`` to the ``context``. To allow your users to navigate between pages,\nadd links to the next and previous page, in your template like this:\n\n.. code-block:: html+django\n\n    {% for contact in page_obj %}\n        {# Each \"contact\" is a Contact model object. #}\n        {{ contact.full_name|upper }}<br>\n        ...\n    {% endfor %}\n\n    <div class=\"pagination\">\n        <span class=\"step-links\">\n            {% if page_obj.has_previous %}\n                <a href=\"?page=1\">&laquo; first</a>\n                <a href=\"?page={{ page_obj.previous_page_number }}\">previous</a>\n            {% endif %}\n\n            <span class=\"current\">\n                Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.\n            </span>\n\n            {% if page_obj.has_next %}\n                <a href=\"?page={{ page_obj.next_page_number }}\">next</a>\n                <a href=\"?page={{ page_obj.paginator.num_pages }}\">last &raquo;</a>\n            {% endif %}\n        </span>\n    </div>\n\n.. _using-paginator-in-view:\n\nUsing ``Paginator`` in a view function\n======================================\n\nHere's an example using :class:`~django.core.paginator.Paginator` in a view\nfunction to paginate a queryset::\n\n    from django.core.paginator import Paginator\n    from django.shortcuts import render\n\n    from myapp.models import Contact\n\n    def listing(request):\n        contact_list = Contact.objects.all()\n        paginator = Paginator(contact_list, 25) # Show 25 contacts per page.\n\n        page_number = request.GET.get('page')\n        page_obj = paginator.get_page(page_number)\n        return render(request, 'list.html', {'page_obj': page_obj})\n\nIn the template :file:`list.html`, you can include navigation between pages in\nthe same way as in the template for the ``ListView`` above.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":247,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/topics","text":"============\nUsing Django\n============\n\nIntroductions to all the key parts of Django you'll need to know:\n\n.. toctree::\n   :maxdepth: 2\n\n   install\n   db/index\n   http/index\n   forms/index\n   templates\n   class-based-views/index\n   migrations\n   files\n   testing/index\n   auth/index\n   cache\n   conditional-view-processing\n   signing\n   email\n   i18n/index\n   logging\n   pagination\n   security\n   performance\n   serialization\n   settings\n   signals\n   checks\n   external-packages\n   async\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":248,"nodeType":"TextFile","repoName":null,"name":"signing.txt","path":"docs/topics","text":"=====================\nCryptographic signing\n=====================\n\n.. module:: django.core.signing\n   :synopsis: Django's signing framework.\n\nThe golden rule of Web application security is to never trust data from\nuntrusted sources. Sometimes it can be useful to pass data through an\nuntrusted medium. Cryptographically signed values can be passed through an\nuntrusted channel safe in the knowledge that any tampering will be detected.\n\nDjango provides both a low-level API for signing values and a high-level API\nfor setting and reading signed cookies, one of the most common uses of\nsigning in Web applications.\n\nYou may also find signing useful for the following:\n\n* Generating \"recover my account\" URLs for sending to users who have\n  lost their password.\n\n* Ensuring data stored in hidden form fields has not been tampered with.\n\n* Generating one-time secret URLs for allowing temporary access to a\n  protected resource, for example a downloadable file that a user has\n  paid for.\n\nProtecting the ``SECRET_KEY``\n=============================\n\nWhen you create a new Django project using :djadmin:`startproject`, the\n``settings.py`` file is generated automatically and gets a random\n:setting:`SECRET_KEY` value. This value is the key to securing signed\ndata -- it is vital you keep this secure, or attackers could use it to\ngenerate their own signed values.\n\nUsing the low-level API\n=======================\n\nDjango's signing methods live in the ``django.core.signing`` module.\nTo sign a value, first instantiate a ``Signer`` instance::\n\n    >>> from django.core.signing import Signer\n    >>> signer = Signer()\n    >>> value = signer.sign('My string')\n    >>> value\n    'My string:GdMGD6HNQ_qdgxYP8yBZAdAIV1w'\n\nThe signature is appended to the end of the string, following the colon.\nYou can retrieve the original value using the ``unsign`` method::\n\n    >>> original = signer.unsign(value)\n    >>> original\n    'My string'\n\nIf you pass a non-string value to ``sign``, the value will be forced to string\nbefore being signed, and the ``unsign`` result will give you that string\nvalue::\n\n    >>> signed = signer.sign(2.5)\n    >>> original = signer.unsign(signed)\n    >>> original\n    '2.5'\n\nIf the signature or value have been altered in any way, a\n``django.core.signing.BadSignature`` exception will be raised::\n\n    >>> from django.core import signing\n    >>> value += 'm'\n    >>> try:\n    ...    original = signer.unsign(value)\n    ... except signing.BadSignature:\n    ...    print(\"Tampering detected!\")\n\nBy default, the ``Signer`` class uses the :setting:`SECRET_KEY` setting to\ngenerate signatures. You can use a different secret by passing it to the\n``Signer`` constructor::\n\n    >>> signer = Signer('my-other-secret')\n    >>> value = signer.sign('My string')\n    >>> value\n    'My string:EkfQJafvGyiofrdGnuthdxImIJw'\n\n.. class:: Signer(key=None, sep=':', salt=None, algorithm='sha256')\n\n    Returns a signer which uses ``key`` to generate signatures and ``sep`` to\n    separate values. ``sep`` cannot be in the :rfc:`URL safe base64 alphabet\n    <4648#section-5>`. This alphabet contains alphanumeric characters, hyphens,\n    and underscores. ``algorithm`` must be an algorithm supported by\n    :py:mod:`hashlib`.\n\n    .. versionchanged:: 3.1\n\n        The ``algorithm`` parameter was added.\n\nUsing the ``salt`` argument\n---------------------------\n\nIf you do not wish for every occurrence of a particular string to have the same\nsignature hash, you can use the optional ``salt`` argument to the ``Signer``\nclass. Using a salt will seed the signing hash function with both the salt and\nyour :setting:`SECRET_KEY`::\n\n    >>> signer = Signer()\n    >>> signer.sign('My string')\n    'My string:GdMGD6HNQ_qdgxYP8yBZAdAIV1w'\n    >>> signer = Signer(salt='extra')\n    >>> signer.sign('My string')\n    'My string:Ee7vGi-ING6n02gkcJ-QLHg6vFw'\n    >>> signer.unsign('My string:Ee7vGi-ING6n02gkcJ-QLHg6vFw')\n    'My string'\n\nUsing salt in this way puts the different signatures into different\nnamespaces.  A signature that comes from one namespace (a particular salt\nvalue) cannot be used to validate the same plaintext string in a different\nnamespace that is using a different salt setting. The result is to prevent an\nattacker from using a signed string generated in one place in the code as input\nto another piece of code that is generating (and verifying) signatures using a\ndifferent salt.\n\nUnlike your :setting:`SECRET_KEY`, your salt argument does not need to stay\nsecret.\n\nVerifying timestamped values\n----------------------------\n\n``TimestampSigner`` is a subclass of :class:`~Signer` that appends a signed\ntimestamp to the value. This allows you to confirm that a signed value was\ncreated within a specified period of time::\n\n    >>> from datetime import timedelta\n    >>> from django.core.signing import TimestampSigner\n    >>> signer = TimestampSigner()\n    >>> value = signer.sign('hello')\n    >>> value\n    'hello:1NMg5H:oPVuCqlJWmChm1rA2lyTUtelC-c'\n    >>> signer.unsign(value)\n    'hello'\n    >>> signer.unsign(value, max_age=10)\n    ...\n    SignatureExpired: Signature age 15.5289158821 > 10 seconds\n    >>> signer.unsign(value, max_age=20)\n    'hello'\n    >>> signer.unsign(value, max_age=timedelta(seconds=20))\n    'hello'\n\n.. class:: TimestampSigner(key=None, sep=':', salt=None, algorithm='sha256')\n\n    .. method:: sign(value)\n\n        Sign ``value`` and append current timestamp to it.\n\n    .. method:: unsign(value, max_age=None)\n\n        Checks if ``value`` was signed less than ``max_age`` seconds ago,\n        otherwise raises ``SignatureExpired``. The ``max_age`` parameter can\n        accept an integer or a :py:class:`datetime.timedelta` object.\n\n    .. versionchanged:: 3.1\n\n        The ``algorithm`` parameter was added.\n\nProtecting complex data structures\n----------------------------------\n\nIf you wish to protect a list, tuple or dictionary you can do so using the\nsigning module's ``dumps`` and ``loads`` functions. These imitate Python's\npickle module, but use JSON serialization under the hood. JSON ensures that\neven if your :setting:`SECRET_KEY` is stolen an attacker will not be able\nto execute arbitrary commands by exploiting the pickle format::\n\n    >>> from django.core import signing\n    >>> value = signing.dumps({\"foo\": \"bar\"})\n    >>> value\n    'eyJmb28iOiJiYXIifQ:1NMg1b:zGcDE4-TCkaeGzLeW9UQwZesciI'\n    >>> signing.loads(value)\n    {'foo': 'bar'}\n\nBecause of the nature of JSON (there is no native distinction between lists\nand tuples) if you pass in a tuple, you will get a list from\n``signing.loads(object)``::\n\n    >>> from django.core import signing\n    >>> value = signing.dumps(('a','b','c'))\n    >>> signing.loads(value)\n    ['a', 'b', 'c']\n\n.. function:: dumps(obj, key=None, salt='django.core.signing', compress=False)\n\n    Returns URL-safe, sha1 signed base64 compressed JSON string. Serialized\n    object is signed using :class:`~TimestampSigner`.\n\n.. function:: loads(string, key=None, salt='django.core.signing', max_age=None)\n\n    Reverse of ``dumps()``, raises ``BadSignature`` if signature fails.\n    Checks ``max_age`` (in seconds) if given.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":249,"nodeType":"TextFile","repoName":null,"name":".gitignore","path":"","text":"# If you need to exclude files such as those generated by an IDE, use\n# $GIT_DIR/info/exclude or the core.excludesFile configuration variable as\n# described in https://git-scm.com/docs/gitignore\n\n*.egg-info\n*.pot\n*.py[co]\n.tox/\n__pycache__\nMANIFEST\ndist/\ndocs/_build/\ndocs/locale/\nnode_modules/\ntests/coverage_html/\ntests/.coverage\nbuild/\ntests/report/\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":250,"nodeType":"TextFile","repoName":null,"name":"external-packages.txt","path":"docs/topics","text":"=================\nExternal packages\n=================\n\nDjango ships with a variety of extra, optional tools that solve common\nproblems (``contrib.*``). For easier maintenance and to trim the size of the\ncodebase, a few of those applications have been moved out to separate projects.\n\nLocalflavor\n===========\n\n``django-localflavor`` is a collection of utilities for particular countries\nand cultures.\n\n* `GitHub <https://github.com/django/django-localflavor>`__\n* `Documentation <https://django-localflavor.readthedocs.io/>`__\n* `PyPI <https://pypi.org/project/django-localflavor/>`__\n\nComments\n========\n\n``django-contrib-comments`` can be used to attach comments to any model, so you\ncan use it for comments on blog entries, photos, book chapters, or anything\nelse. Most users will be better served with a custom solution, or a hosted\nproduct like Disqus.\n\n* `GitHub <https://github.com/django/django-contrib-comments>`__\n* `Documentation <https://django-contrib-comments.readthedocs.io/>`__\n* `PyPI <https://pypi.org/project/django-contrib-comments/>`__\n\nFormtools\n=========\n\n``django-formtools`` is a collection of assorted utilities to work with forms.\n\n* `GitHub <https://github.com/django/django-formtools>`__\n* `Documentation <https://django-formtools.readthedocs.io/>`__\n* `PyPI <https://pypi.org/project/django-formtools/>`__\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":251,"nodeType":"TextFile","repoName":null,"name":".editorconfig","path":"","text":"# https://editorconfig.org/\n\nroot = true\n\n[*]\nindent_style = space\nindent_size = 4\ninsert_final_newline = true\ntrim_trailing_whitespace = true\nend_of_line = lf\ncharset = utf-8\n\n# Docstrings and comments use max_line_length = 79\n[*.py]\nmax_line_length = 119\n\n# Use 2 spaces for the HTML files\n[*.html]\nindent_size = 2\n\n# The JSON files contain newlines inconsistently\n[*.json]\nindent_size = 2\ninsert_final_newline = ignore\n\n[**/admin/js/vendor/**]\nindent_style = ignore\nindent_size = ignore\n\n# Minified JavaScript files shouldn't be changed\n[**.min.js]\nindent_style = ignore\ninsert_final_newline = ignore\n\n# Makefiles always use tabs for indentation\n[Makefile]\nindent_style = tab\n\n# Batch files use tabs for indentation\n[*.bat]\nindent_style = tab\n\n[docs/**.txt]\nmax_line_length = 79\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":252,"nodeType":"TextFile","repoName":null,"name":"install.txt","path":"docs/topics","text":"=====================\nHow to install Django\n=====================\n\nThis document will get you up and running with Django.\n\nInstall Python\n==============\n\nDjango is a Python Web framework. See :ref:`faq-python-version-support` for\ndetails.\n\nGet the latest version of Python at https://www.python.org/downloads/ or with\nyour operating system's package manager.\n\n.. admonition:: Python on Windows\n\n    If you are just starting with Django and using Windows, you may find\n    :doc:`/howto/windows` useful.\n\nInstall Apache and ``mod_wsgi``\n===============================\n\nIf you just want to experiment with Django, skip ahead to the next\nsection; Django includes a lightweight web server you can use for\ntesting, so you won't need to set up Apache until you're ready to\ndeploy Django in production.\n\nIf you want to use Django on a production site, use `Apache`_ with\n`mod_wsgi`_. mod_wsgi operates in one of two modes: embedded\nmode or daemon mode. In embedded mode, mod_wsgi is similar to\nmod_perl -- it embeds Python within Apache and loads Python code into\nmemory when the server starts. Code stays in memory throughout the\nlife of an Apache process, which leads to significant performance\ngains over other server arrangements. In daemon mode, mod_wsgi spawns\nan independent daemon process that handles requests. The daemon\nprocess can run as a different user than the Web server, possibly\nleading to improved security. The daemon process can be restarted\nwithout restarting the entire Apache Web server, possibly making\nrefreshing your codebase more seamless. Consult the mod_wsgi\ndocumentation to determine which mode is right for your setup. Make\nsure you have Apache installed with the mod_wsgi module activated.\nDjango will work with any version of Apache that supports mod_wsgi.\n\nSee :doc:`How to use Django with mod_wsgi </howto/deployment/wsgi/modwsgi>`\nfor information on how to configure mod_wsgi once you have it\ninstalled.\n\nIf you can't use mod_wsgi for some reason, fear not: Django supports many other\ndeployment options. One is :doc:`uWSGI </howto/deployment/wsgi/uwsgi>`; it works\nvery well with `nginx`_. Additionally, Django follows the WSGI spec\n(:pep:`3333`), which allows it to run on a variety of server platforms.\n\n.. _Apache: https://httpd.apache.org/\n.. _nginx: https://nginx.org/\n.. _mod_wsgi: https://modwsgi.readthedocs.io/en/develop/\n\n.. _database-installation:\n\nGet your database running\n=========================\n\nIf you plan to use Django's database API functionality, you'll need to make\nsure a database server is running. Django supports many different database\nservers and is officially supported with PostgreSQL_, MariaDB_, MySQL_, Oracle_\nand SQLite_.\n\nIf you are developing a small project or something you don't plan to deploy in\na production environment, SQLite is generally the best option as it doesn't\nrequire running a separate server. However, SQLite has many differences from\nother databases, so if you are working on something substantial, it's\nrecommended to develop with the same database that you plan on using in\nproduction.\n\nIn addition to the officially supported databases, there are :ref:`backends\nprovided by 3rd parties <third-party-notes>` that allow you to use other\ndatabases with Django.\n\nIn addition to a database backend, you'll need to make sure your Python\ndatabase bindings are installed.\n\n* If you're using PostgreSQL, you'll need the `psycopg2`_ package. Refer to the\n  :ref:`PostgreSQL notes <postgresql-notes>` for further details.\n\n* If you're using MySQL or MariaDB, you'll need a :ref:`DB API driver\n  <mysql-db-api-drivers>` like ``mysqlclient``. See :ref:`notes for the MySQL\n  backend <mysql-notes>` for details.\n\n* If you're using SQLite you might want to read the :ref:`SQLite backend notes\n  <sqlite-notes>`.\n\n* If you're using Oracle, you'll need a copy of cx_Oracle_, but please\n  read the :ref:`notes for the Oracle backend <oracle-notes>` for details\n  regarding supported versions of both Oracle and ``cx_Oracle``.\n\n* If you're using an unofficial 3rd party backend, please consult the\n  documentation provided for any additional requirements.\n\nIf you plan to use Django's ``manage.py migrate`` command to automatically\ncreate database tables for your models (after first installing Django and\ncreating a project), you'll need to ensure that Django has permission to create\nand alter tables in the database you're using; if you plan to manually create\nthe tables, you can grant Django ``SELECT``, ``INSERT``, ``UPDATE`` and\n``DELETE`` permissions. After creating a database user with these permissions,\nyou'll specify the details in your project's settings file, see\n:setting:`DATABASES` for details.\n\nIf you're using Django's :doc:`testing framework</topics/testing/index>` to test\ndatabase queries, Django will need permission to create a test database.\n\n.. _PostgreSQL: https://www.postgresql.org/\n.. _MariaDB: https://mariadb.org/\n.. _MySQL: https://www.mysql.com/\n.. _psycopg2: https://www.psycopg.org/\n.. _SQLite: https://www.sqlite.org/\n.. _cx_Oracle: https://oracle.github.io/python-cx_Oracle/\n.. _Oracle: https://www.oracle.com/\n\n.. _install-django-code:\n\nInstall the Django code\n=======================\n\nInstallation instructions are slightly different depending on whether you're\ninstalling a distribution-specific package, downloading the latest official\nrelease, or fetching the latest development version.\n\n.. _installing-official-release:\n\nInstalling an official release with ``pip``\n-------------------------------------------\n\nThis is the recommended way to install Django.\n\n#. Install pip_. The easiest is to use the `standalone pip installer`_. If your\n   distribution already has ``pip`` installed, you might need to update it if\n   it's outdated. If it's outdated, you'll know because installation won't\n   work.\n\n#. Take a look at virtualenv_ and virtualenvwrapper_. These tools provide\n   isolated Python environments, which are more practical than installing\n   packages systemwide. They also allow installing packages without\n   administrator privileges. The :doc:`contributing tutorial\n   </intro/contributing>` walks through how to create a virtualenv.\n\n#. After you've created and activated a virtual environment, enter the command:\n\n   .. console::\n\n        $ python -m pip install Django\n\n.. _pip: https://pip.pypa.io/\n.. _virtualenv: https://virtualenv.pypa.io/\n.. _virtualenvwrapper: https://virtualenvwrapper.readthedocs.io/en/latest/\n.. _standalone pip installer: https://pip.pypa.io/en/latest/installing/#installing-with-get-pip-py\n\n.. _installing-distribution-package:\n\nInstalling a distribution-specific package\n------------------------------------------\n\nCheck the :doc:`distribution specific notes </misc/distributions>` to see if\nyour platform/distribution provides official Django packages/installers.\nDistribution-provided packages will typically allow for automatic installation\nof dependencies and supported upgrade paths; however, these packages will rarely\ncontain the latest release of Django.\n\n.. _installing-development-version:\n\nInstalling the development version\n----------------------------------\n\n.. admonition:: Tracking Django development\n\n    If you decide to use the latest development version of Django,\n    you'll want to pay close attention to `the development timeline`_,\n    and you'll want to keep an eye on the :ref:`release notes for the\n    upcoming release <development_release_notes>`. This will help you stay\n    on top of any new features you might want to use, as well as any changes\n    you'll need to make to your code when updating your copy of Django.\n    (For stable releases, any necessary changes are documented in the\n    release notes.)\n\n.. _the development timeline: https://code.djangoproject.com/timeline\n\nIf you'd like to be able to update your Django code occasionally with the\nlatest bug fixes and improvements, follow these instructions:\n\n#. Make sure that you have Git_ installed and that you can run its commands\n   from a shell. (Enter ``git help`` at a shell prompt to test this.)\n\n#. Check out Django's main development branch like so:\n\n   .. console::\n\n        $ git clone https://github.com/django/django.git\n\n   This will create a directory ``django`` in your current directory.\n\n#. Make sure that the Python interpreter can load Django's code. The most\n   convenient way to do this is to use virtualenv_, virtualenvwrapper_, and\n   pip_. The :doc:`contributing tutorial </intro/contributing>` walks through\n   how to create a virtualenv.\n\n#. After setting up and activating the virtualenv, run the following command:\n\n   .. console::\n\n        $ python -m pip install -e django/\n\n   This will make Django's code importable, and will also make the\n   ``django-admin`` utility command available. In other words, you're all\n   set!\n\nWhen you want to update your copy of the Django source code, run the command\n``git pull`` from within the ``django`` directory. When you do this, Git will\ndownload any changes.\n\n.. _Git: https://git-scm.com/\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":253,"nodeType":"TextFile","repoName":null,"name":"signals.txt","path":"docs/topics","text":"=======\nSignals\n=======\n\n.. module:: django.dispatch\n   :synopsis: Signal dispatch\n\nDjango includes a \"signal dispatcher\" which helps allow decoupled applications\nget notified when actions occur elsewhere in the framework. In a nutshell,\nsignals allow certain *senders* to notify a set of *receivers* that some action\nhas taken place. They're especially useful when many pieces of code may be\ninterested in the same events.\n\nDjango provides a :doc:`set of built-in signals </ref/signals>` that let user\ncode get notified by Django itself of certain actions. These include some useful\nnotifications:\n\n* :data:`django.db.models.signals.pre_save` &\n  :data:`django.db.models.signals.post_save`\n\n  Sent before or after a model's :meth:`~django.db.models.Model.save` method\n  is called.\n\n* :data:`django.db.models.signals.pre_delete` &\n  :data:`django.db.models.signals.post_delete`\n\n  Sent before or after a model's :meth:`~django.db.models.Model.delete`\n  method or queryset's :meth:`~django.db.models.query.QuerySet.delete`\n  method is called.\n\n* :data:`django.db.models.signals.m2m_changed`\n\n  Sent when a :class:`~django.db.models.ManyToManyField` on a model is changed.\n\n* :data:`django.core.signals.request_started` &\n  :data:`django.core.signals.request_finished`\n\n  Sent when Django starts or finishes an HTTP request.\n\nSee the :doc:`built-in signal documentation </ref/signals>` for a complete list,\nand a complete explanation of each signal.\n\nYou can also `define and send your own custom signals`_; see below.\n\n.. _define and send your own custom signals: `defining and sending signals`_\n\nListening to signals\n====================\n\nTo receive a signal, register a *receiver* function using the\n:meth:`Signal.connect` method. The receiver function is called when the signal\nis sent. All of the signal's receiver functions are called one at a time, in\nthe order they were registered.\n\n.. method:: Signal.connect(receiver, sender=None, weak=True, dispatch_uid=None)\n\n    :param receiver: The callback function which will be connected to this\n        signal. See :ref:`receiver-functions` for more information.\n\n    :param sender: Specifies a particular sender to receive signals from. See\n        :ref:`connecting-to-specific-signals` for more information.\n\n    :param weak: Django stores signal handlers as weak references by\n        default. Thus, if your receiver is a local function, it may be\n        garbage collected. To prevent this, pass ``weak=False`` when you call\n        the signal's ``connect()`` method.\n\n    :param dispatch_uid: A unique identifier for a signal receiver in cases\n        where duplicate signals may be sent. See\n        :ref:`preventing-duplicate-signals` for more information.\n\nLet's see how this works by registering a signal that\ngets called after each HTTP request is finished. We'll be connecting to the\n:data:`~django.core.signals.request_finished` signal.\n\n.. _receiver-functions:\n\nReceiver functions\n------------------\n\nFirst, we need to define a receiver function. A receiver can be any Python\nfunction or method::\n\n    def my_callback(sender, **kwargs):\n        print(\"Request finished!\")\n\nNotice that the function takes a ``sender`` argument, along with wildcard\nkeyword arguments (``**kwargs``); all signal handlers must take these arguments.\n\nWe'll look at senders `a bit later`_, but right now look at the ``**kwargs``\nargument. All signals send keyword arguments, and may change those keyword\narguments at any time. In the case of\n:data:`~django.core.signals.request_finished`, it's documented as sending no\narguments, which means we might be tempted to write our signal handling as\n``my_callback(sender)``.\n\n.. _a bit later: `connecting to signals sent by specific senders`_\n\nThis would be wrong -- in fact, Django will throw an error if you do so. That's\nbecause at any point arguments could get added to the signal and your receiver\nmust be able to handle those new arguments.\n\n.. _connecting-receiver-functions:\n\nConnecting receiver functions\n-----------------------------\n\nThere are two ways you can connect a receiver to a signal. You can take the\nmanual connect route::\n\n    from django.core.signals import request_finished\n\n    request_finished.connect(my_callback)\n\nAlternatively, you can use a :func:`receiver` decorator:\n\n.. function:: receiver(signal)\n\n    :param signal: A signal or a list of signals to connect a function to.\n\nHere's how you connect with the decorator::\n\n    from django.core.signals import request_finished\n    from django.dispatch import receiver\n\n    @receiver(request_finished)\n    def my_callback(sender, **kwargs):\n        print(\"Request finished!\")\n\nNow, our ``my_callback`` function will be called each time a request finishes.\n\n.. admonition:: Where should this code live?\n\n    Strictly speaking, signal handling and registration code can live anywhere\n    you like, although it's recommended to avoid the application's root module\n    and its ``models`` module to minimize side-effects of importing code.\n\n    In practice, signal handlers are usually defined in a ``signals``\n    submodule of the application they relate to. Signal receivers are\n    connected in the :meth:`~django.apps.AppConfig.ready` method of your\n    application configuration class. If you're using the :func:`receiver`\n    decorator, import the ``signals`` submodule inside\n    :meth:`~django.apps.AppConfig.ready`.\n\n.. note::\n\n    The :meth:`~django.apps.AppConfig.ready` method may be executed more than\n    once during testing, so you may want to :ref:`guard your signals from\n    duplication <preventing-duplicate-signals>`, especially if you're planning\n    to send them within tests.\n\n.. _connecting-to-specific-signals:\n\nConnecting to signals sent by specific senders\n----------------------------------------------\n\nSome signals get sent many times, but you'll only be interested in receiving a\ncertain subset of those signals. For example, consider the\n:data:`django.db.models.signals.pre_save` signal sent before a model gets saved.\nMost of the time, you don't need to know when *any* model gets saved -- just\nwhen one *specific* model is saved.\n\nIn these cases, you can register to receive signals sent only by particular\nsenders. In the case of :data:`django.db.models.signals.pre_save`, the sender\nwill be the model class being saved, so you can indicate that you only want\nsignals sent by some model::\n\n    from django.db.models.signals import pre_save\n    from django.dispatch import receiver\n    from myapp.models import MyModel\n\n\n    @receiver(pre_save, sender=MyModel)\n    def my_handler(sender, **kwargs):\n        ...\n\nThe ``my_handler`` function will only be called when an instance of ``MyModel``\nis saved.\n\nDifferent signals use different objects as their senders; you'll need to consult\nthe :doc:`built-in signal documentation </ref/signals>` for details of each\nparticular signal.\n\n.. _preventing-duplicate-signals:\n\nPreventing duplicate signals\n----------------------------\n\nIn some circumstances, the code connecting receivers to signals may run\nmultiple times. This can cause your receiver function to be registered more\nthan once, and thus called multiple times for a single signal event.\n\nIf this behavior is problematic (such as when using signals to\nsend an email whenever a model is saved), pass a unique identifier as\nthe ``dispatch_uid`` argument to identify your receiver function. This\nidentifier will usually be a string, although any hashable object will\nsuffice. The end result is that your receiver function will only be\nbound to the signal once for each unique ``dispatch_uid`` value::\n\n    from django.core.signals import request_finished\n\n    request_finished.connect(my_callback, dispatch_uid=\"my_unique_identifier\")\n\nDefining and sending signals\n============================\n\nYour applications can take advantage of the signal infrastructure and provide\nits own signals.\n\n.. admonition:: When to use custom signals\n\n    Signals are implicit function calls which make debugging harder. If the\n    sender and receiver of your custom signal are both within your project,\n    you're better off using an explicit function call.\n\nDefining signals\n----------------\n\n.. class:: Signal()\n\nAll signals are :class:`django.dispatch.Signal` instances.\n\nFor example::\n\n    import django.dispatch\n\n    pizza_done = django.dispatch.Signal()\n\nThis declares a ``pizza_done`` signal.\n\nSending signals\n---------------\n\nThere are two ways to send signals in Django.\n\n.. method:: Signal.send(sender, **kwargs)\n.. method:: Signal.send_robust(sender, **kwargs)\n\nTo send a signal, call either :meth:`Signal.send` (all built-in signals use\nthis) or :meth:`Signal.send_robust`. You must provide the ``sender`` argument\n(which is a class most of the time) and may provide as many other keyword\narguments as you like.\n\nFor example, here's how sending our ``pizza_done`` signal might look::\n\n    class PizzaStore:\n        ...\n\n        def send_pizza(self, toppings, size):\n            pizza_done.send(sender=self.__class__, toppings=toppings, size=size)\n            ...\n\nBoth ``send()`` and ``send_robust()`` return a list of tuple pairs\n``[(receiver, response), ... ]``, representing the list of called receiver\nfunctions and their response values.\n\n``send()`` differs from ``send_robust()`` in how exceptions raised by receiver\nfunctions are handled. ``send()`` does *not* catch any exceptions raised by\nreceivers; it simply allows errors to propagate. Thus not all receivers may\nbe notified of a signal in the face of an error.\n\n``send_robust()`` catches all errors derived from Python's ``Exception`` class,\nand ensures all receivers are notified of the signal. If an error occurs, the\nerror instance is returned in the tuple pair for the receiver that raised the error.\n\nThe tracebacks are present on the ``__traceback__`` attribute of the errors\nreturned when calling ``send_robust()``.\n\nDisconnecting signals\n=====================\n\n.. method:: Signal.disconnect(receiver=None, sender=None, dispatch_uid=None)\n\nTo disconnect a receiver from a signal, call :meth:`Signal.disconnect`. The\narguments are as described in :meth:`.Signal.connect`. The method returns\n``True`` if a receiver was disconnected and ``False`` if not.\n\nThe ``receiver`` argument indicates the registered receiver to disconnect. It\nmay be ``None`` if ``dispatch_uid`` is used to identify the receiver.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":254,"nodeType":"TextFile","repoName":null,"name":"README.md","path":"docs/_theme/djangodocs/static/fontawesome","text":"# Font Awesome 5.0.4\n\nThanks for downloading Font Awesome! We're so excited you're here.\n\nOur documentation is available online. Just head here:\n\nhttps://fontawesome.com\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":255,"nodeType":"TextFile","repoName":null,"name":"async.txt","path":"docs/topics","text":"====================\nAsynchronous support\n====================\n\n.. currentmodule:: asgiref.sync\n\nDjango has support for writing asynchronous (\"async\") views, along with an\nentirely async-enabled request stack if you are running under\n:doc:`ASGI </howto/deployment/asgi/index>`. Async views will still work under\nWSGI, but with performance penalties, and without the ability to have efficient\nlong-running requests.\n\nWe're still working on async support for the ORM and other parts of Django.\nYou can expect to see this in future releases. For now, you can use the\n:func:`sync_to_async` adapter to interact with the sync parts of Django.\nThere is also a whole range of async-native Python libraries that you can\nintegrate with.\n\n.. versionchanged:: 3.1\n\n    Support for async views was added.\n\nAsync views\n===========\n\n.. versionadded:: 3.1\n\nAny view can be declared async by making the callable part of it return a\ncoroutine - commonly, this is done using ``async def``. For a function-based\nview, this means declaring the whole view using ``async def``. For a\nclass-based view, this means making its ``__call__()`` method an ``async def``\n(not its ``__init__()`` or ``as_view()``).\n\n.. note::\n\n    Django uses ``asyncio.iscoroutinefunction`` to test if your view is\n    asynchronous or not. If you implement your own method of returning a\n    coroutine, ensure you set the ``_is_coroutine`` attribute of the view\n    to ``asyncio.coroutines._is_coroutine`` so this function returns ``True``.\n\nUnder a WSGI server, async views will run in their own, one-off event loop.\nThis means you can use async features, like parallel async HTTP requests,\nwithout any issues, but you will not get the benefits of an async stack.\n\nThe main benefits are the ability to service hundreds of connections without\nusing Python threads. This allows you to use slow streaming, long-polling, and\nother exciting response types.\n\nIf you want to use these, you will need to deploy Django using\n:doc:`ASGI </howto/deployment/asgi/index>` instead.\n\n.. warning::\n\n    You will only get the benefits of a fully-asynchronous request stack if you\n    have *no synchronous middleware* loaded into your site. If there is a piece\n    of synchronous middleware, then Django must use a thread per request to\n    safely emulate a synchronous environment for it.\n\n    Middleware can be built to support :ref:`both sync and async\n    <async-middleware>` contexts. Some of Django's middleware is built like\n    this, but not all. To see what middleware Django has to adapt, you can turn\n    on debug logging for the ``django.request`` logger and look for log\n    messages about *`\"Synchronous middleware ... adapted\"*.\n\nIn both ASGI and WSGI mode, you can still safely use asynchronous support to\nrun code in parallel rather than serially. This is especially handy when\ndealing with external APIs or data stores.\n\nIf you want to call a part of Django that is still synchronous, like the ORM,\nyou will need to wrap it in a :func:`sync_to_async` call. For example::\n\n    from asgiref.sync import sync_to_async\n\n    results = sync_to_async(Blog.objects.get)(pk=123)\n\nYou may find it easier to move any ORM code into its own function and call that\nentire function using :func:`sync_to_async`. For example::\n\n    from asgiref.sync import sync_to_async\n\n    @sync_to_async\n    def get_blog(pk):\n        return Blog.objects.select_related('author').get(pk=pk)\n\nIf you accidentally try to call a part of Django that is still synchronous-only\nfrom an async view, you will trigger Django's\n:ref:`asynchronous safety protection <async-safety>` to protect your data from\ncorruption.\n\nPerformance\n-----------\n\nWhen running in a mode that does not match the view (e.g. an async view under\nWSGI, or a traditional sync view under ASGI), Django must emulate the other\ncall style to allow your code to run. This context-switch causes a small\nperformance penalty of around a millisecond.\n\nThis is also true of middleware. Django will attempt to minimize the number of\ncontext-switches between sync and async. If you have an ASGI server, but all\nyour middleware and views are synchronous, it will switch just once, before it\nenters the middleware stack.\n\nHowever, if you put synchronous middleware between an ASGI server and an\nasynchronous view, it will have to switch into sync mode for the middleware and\nthen back to async mode for the view. Django will also hold the sync thread\nopen for middleware exception propagation. This may not be noticeable at first,\nbut adding this penalty of one thread per request can remove any async\nperformance advantage.\n\nYou should do your own performance testing to see what effect ASGI versus WSGI\nhas on your code. In some cases, there may be a performance increase even for\na purely synchronous codebase under ASGI because the request-handling code is\nstill all running asynchronously. In general you will only want to enable ASGI\nmode if you have asynchronous code in your project.\n\n.. _async-safety:\n\nAsync safety\n============\n\n.. envvar:: DJANGO_ALLOW_ASYNC_UNSAFE\n\nCertain key parts of Django are not able to operate safely in an async\nenvironment, as they have global state that is not coroutine-aware. These parts\nof Django are classified as \"async-unsafe\", and are protected from execution in\nan async environment. The ORM is the main example, but there are other parts\nthat are also protected in this way.\n\nIf you try to run any of these parts from a thread where there is a *running\nevent loop*, you will get a\n:exc:`~django.core.exceptions.SynchronousOnlyOperation` error. Note that you\ndon't have to be inside an async function directly to have this error occur. If\nyou have called a sync function directly from an async function,\nwithout using :func:`sync_to_async` or similar, then it can also occur. This is\nbecause your code is still running in a thread with an active event loop, even\nthough it may not be declared as async code.\n\nIf you encounter this error, you should fix your code to not call the offending\ncode from an async context. Instead, write your code that talks to async-unsafe\nfunctions in its own, sync function, and call that using\n:func:`asgiref.sync.sync_to_async` (or any other way of running sync code in\nits own thread).\n\nYou may still be forced to run sync code from an async context. For example,\nif the requirement is forced on you by an external environment, such as in a\nJupyter_ notebook. If you are sure there is no chance of the code being run\nconcurrently, and you *absolutely* need to run this sync code from an async\ncontext, then you can disable the warning by setting the\n:envvar:`DJANGO_ALLOW_ASYNC_UNSAFE` environment variable to any value.\n\n.. warning::\n\n    If you enable this option and there is concurrent access to the\n    async-unsafe parts of Django, you may suffer data loss or corruption. Be\n    very careful and do not use this in production environments.\n\nIf you need to do this from within Python, do that with ``os.environ``::\n\n    import os\n\n    os.environ[\"DJANGO_ALLOW_ASYNC_UNSAFE\"] = \"true\"\n\n.. _Jupyter: https://jupyter.org/\n\nAsync adapter functions\n=======================\n\nIt is necessary to adapt the calling style when calling sync code from an async\ncontext, or vice-versa. For this there are two adapter functions, from the\n``asgiref.sync`` module: :func:`async_to_sync` and :func:`sync_to_async`. They\nare used to transition between the calling styles while preserving\ncompatibility.\n\nThese adapter functions are widely used in Django. The `asgiref`_ package\nitself is part of the Django project, and it is automatically installed as a\ndependency when you install Django with ``pip``.\n\n.. _asgiref: https://pypi.org/project/asgiref/\n\n``async_to_sync()``\n-------------------\n\n.. function:: async_to_sync(async_function, force_new_loop=False)\n\nTakes an async function and returns a sync function that wraps it. Can be used\nas either a direct wrapper or a decorator::\n\n    from asgiref.sync import async_to_sync\n\n    async def get_data(...):\n        ...\n\n    sync_get_data = async_to_sync(get_data)\n\n    @async_to_sync\n    async def get_other_data(...):\n        ...\n\nThe async function is run in the event loop for the current thread, if one is\npresent. If there is no current event loop, a new event loop is spun up\nspecifically for the single async invocation and shut down again once it\ncompletes. In either situation, the async function will execute on a different\nthread to the calling code.\n\nThreadlocals and contextvars values are preserved across the boundary in both\ndirections.\n\n:func:`async_to_sync` is essentially a more powerful version of the\n:py:func:`asyncio.run` function in Python's standard library. As well\nas ensuring threadlocals work, it also enables the ``thread_sensitive`` mode of\n:func:`sync_to_async` when that wrapper is used below it.\n\n``sync_to_async()``\n-------------------\n\n.. function:: sync_to_async(sync_function, thread_sensitive=False)\n\nTakes a sync function and returns an async function that wraps it. Can be used\nas either a direct wrapper or a decorator::\n\n    from asgiref.sync import sync_to_async\n\n    async_function = sync_to_async(sync_function)\n    async_function = sync_to_async(sensitive_sync_function, thread_sensitive=True)\n\n    @sync_to_async\n    def sync_function(...):\n        ...\n\nThreadlocals and contextvars values are preserved across the boundary in both\ndirections.\n\nSync functions tend to be written assuming they all run in the main\nthread, so :func:`sync_to_async` has two threading modes:\n\n* ``thread_sensitive=False`` (the default): the sync function will run in a\n  brand new thread which is then closed once the invocation completes.\n\n* ``thread_sensitive=True``: the sync function will run in the same thread as\n  all other ``thread_sensitive`` functions. This will be the main thread, if\n  the main thread is synchronous and you are using the :func:`async_to_sync`\n  wrapper.\n\nThread-sensitive mode is quite special, and does a lot of work to run all\nfunctions in the same thread. Note, though, that it *relies on usage of*\n:func:`async_to_sync` *above it in the stack* to correctly run things on the\nmain thread. If you use ``asyncio.run()`` or similar, it will fall back to\nrunning thread-sensitive functions in a single, shared thread, but this will\nnot be the main thread.\n\nThe reason this is needed in Django is that many libraries, specifically\ndatabase adapters, require that they are accessed in the same thread that they\nwere created in. Also a lot of existing Django code assumes it all runs in the\nsame thread, e.g. middleware adding things to a request for later use in views.\n\nRather than introduce potential compatibility issues with this code, we instead\nopted to add this mode so that all existing Django sync code runs in the same\nthread and thus is fully compatible with async mode. Note that sync code will\nalways be in a *different* thread to any async code that is calling it, so you\nshould avoid passing raw database handles or other thread-sensitive references\naround.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":256,"nodeType":"TextFile","repoName":null,"name":"settings.txt","path":"docs/topics","text":"===============\nDjango settings\n===============\n\nA Django settings file contains all the configuration of your Django\ninstallation. This document explains how settings work and which settings are\navailable.\n\nThe basics\n==========\n\nA settings file is just a Python module with module-level variables.\n\nHere are a couple of example settings::\n\n    ALLOWED_HOSTS = ['www.example.com']\n    DEBUG = False\n    DEFAULT_FROM_EMAIL = 'webmaster@example.com'\n\n.. note::\n\n    If you set :setting:`DEBUG` to ``False``, you also need to properly set\n    the :setting:`ALLOWED_HOSTS` setting.\n\nBecause a settings file is a Python module, the following apply:\n\n* It doesn't allow for Python syntax errors.\n* It can assign settings dynamically using normal Python syntax.\n  For example::\n\n      MY_SETTING = [str(i) for i in range(30)]\n\n* It can import values from other settings files.\n\n.. _django-settings-module:\n\nDesignating the settings\n========================\n\n.. envvar:: DJANGO_SETTINGS_MODULE\n\nWhen you use Django, you have to tell it which settings you're using. Do this\nby using an environment variable, :envvar:`DJANGO_SETTINGS_MODULE`.\n\nThe value of :envvar:`DJANGO_SETTINGS_MODULE` should be in Python path syntax,\ne.g. ``mysite.settings``. Note that the settings module should be on the\nPython `import search path`_.\n\n.. _import search path: https://www.diveinto.org/python3/your-first-python-program.html#importsearchpath\n\nThe ``django-admin`` utility\n----------------------------\n\nWhen using :doc:`django-admin </ref/django-admin>`, you can either set the\nenvironment variable once, or explicitly pass in the settings module each time\nyou run the utility.\n\nExample (Unix Bash shell)::\n\n    export DJANGO_SETTINGS_MODULE=mysite.settings\n    django-admin runserver\n\nExample (Windows shell)::\n\n    set DJANGO_SETTINGS_MODULE=mysite.settings\n    django-admin runserver\n\nUse the ``--settings`` command-line argument to specify the settings manually::\n\n    django-admin runserver --settings=mysite.settings\n\n.. _django-admin: ../django-admin/\n\nOn the server (``mod_wsgi``)\n----------------------------\n\nIn your live server environment, you'll need to tell your WSGI\napplication what settings file to use. Do that with ``os.environ``::\n\n    import os\n\n    os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'\n\nRead the :doc:`Django mod_wsgi documentation\n</howto/deployment/wsgi/modwsgi>` for more information and other common\nelements to a Django WSGI application.\n\nDefault settings\n================\n\nA Django settings file doesn't have to define any settings if it doesn't need\nto. Each setting has a sensible default value. These defaults live in the\nmodule :file:`django/conf/global_settings.py`.\n\nHere's the algorithm Django uses in compiling settings:\n\n* Load settings from ``global_settings.py``.\n* Load settings from the specified settings file, overriding the global\n  settings as necessary.\n\nNote that a settings file should *not* import from ``global_settings``, because\nthat's redundant.\n\nSeeing which settings you've changed\n------------------------------------\n\nThe command ``python manage.py diffsettings`` displays differences between the\ncurrent settings file and Django's default settings.\n\nFor more, see the :djadmin:`diffsettings` documentation.\n\nUsing settings in Python code\n=============================\n\nIn your Django apps, use settings by importing the object\n``django.conf.settings``. Example::\n\n    from django.conf import settings\n\n    if settings.DEBUG:\n        # Do something\n\nNote that ``django.conf.settings`` isn't a module -- it's an object. So\nimporting individual settings is not possible::\n\n    from django.conf.settings import DEBUG  # This won't work.\n\nAlso note that your code should *not* import from either ``global_settings`` or\nyour own settings file. ``django.conf.settings`` abstracts the concepts of\ndefault settings and site-specific settings; it presents a single interface.\nIt also decouples the code that uses settings from the location of your\nsettings.\n\nAltering settings at runtime\n============================\n\nYou shouldn't alter settings in your applications at runtime. For example,\ndon't do this in a view::\n\n    from django.conf import settings\n\n    settings.DEBUG = True   # Don't do this!\n\nThe only place you should assign to settings is in a settings file.\n\nSecurity\n========\n\nBecause a settings file contains sensitive information, such as the database\npassword, you should make every attempt to limit access to it. For example,\nchange its file permissions so that only you and your Web server's user can\nread it. This is especially important in a shared-hosting environment.\n\nAvailable settings\n==================\n\nFor a full list of available settings, see the :doc:`settings reference </ref/settings>`.\n\nCreating your own settings\n==========================\n\nThere's nothing stopping you from creating your own settings, for your own\nDjango apps, but follow these guidelines:\n\n* Setting names must be all uppercase.\n* Don't reinvent an already-existing setting.\n\nFor settings that are sequences, Django itself uses lists, but this is only\na convention.\n\n.. _settings-without-django-settings-module:\n\nUsing settings without setting :envvar:`DJANGO_SETTINGS_MODULE`\n===============================================================\n\nIn some cases, you might want to bypass the :envvar:`DJANGO_SETTINGS_MODULE`\nenvironment variable. For example, if you're using the template system by\nitself, you likely don't want to have to set up an environment variable\npointing to a settings module.\n\nIn these cases, you can configure Django's settings manually. Do this by\ncalling:\n\n.. function:: django.conf.settings.configure(default_settings, **settings)\n\nExample::\n\n    from django.conf import settings\n\n    settings.configure(DEBUG=True)\n\nPass ``configure()`` as many keyword arguments as you'd like, with each keyword\nargument representing a setting and its value. Each argument name should be all\nuppercase, with the same name as the settings described above. If a particular\nsetting is not passed to ``configure()`` and is needed at some later point,\nDjango will use the default setting value.\n\nConfiguring Django in this fashion is mostly necessary -- and, indeed,\nrecommended -- when you're using a piece of the framework inside a larger\napplication.\n\nConsequently, when configured via ``settings.configure()``, Django will not\nmake any modifications to the process environment variables (see the\ndocumentation of :setting:`TIME_ZONE` for why this would normally occur). It's\nassumed that you're already in full control of your environment in these\ncases.\n\nCustom default settings\n-----------------------\n\nIf you'd like default values to come from somewhere other than\n``django.conf.global_settings``, you can pass in a module or class that\nprovides the default settings as the ``default_settings`` argument (or as the\nfirst positional argument) in the call to ``configure()``.\n\nIn this example, default settings are taken from ``myapp_defaults``, and the\n:setting:`DEBUG` setting is set to ``True``, regardless of its value in\n``myapp_defaults``::\n\n    from django.conf import settings\n    from myapp import myapp_defaults\n\n    settings.configure(default_settings=myapp_defaults, DEBUG=True)\n\nThe following example, which uses ``myapp_defaults`` as a positional argument,\nis equivalent::\n\n    settings.configure(myapp_defaults, DEBUG=True)\n\nNormally, you will not need to override the defaults in this fashion. The\nDjango defaults are sufficiently tame that you can safely use them. Be aware\nthat if you do pass in a new default module, it entirely *replaces* the Django\ndefaults, so you must specify a value for every possible setting that might be\nused in that code you are importing. Check in\n``django.conf.settings.global_settings`` for the full list.\n\nEither ``configure()`` or :envvar:`DJANGO_SETTINGS_MODULE` is required\n----------------------------------------------------------------------\n\nIf you're not setting the :envvar:`DJANGO_SETTINGS_MODULE` environment\nvariable, you *must* call ``configure()`` at some point before using any code\nthat reads settings.\n\nIf you don't set :envvar:`DJANGO_SETTINGS_MODULE` and don't call\n``configure()``, Django will raise an ``ImportError`` exception the first time\na setting is accessed.\n\nIf you set :envvar:`DJANGO_SETTINGS_MODULE`, access settings values somehow,\n*then* call ``configure()``, Django will raise a ``RuntimeError`` indicating\nthat settings have already been configured. There is a property for this\npurpose:\n\n.. attribute: django.conf.settings.configured\n\nFor example::\n\n    from django.conf import settings\n    if not settings.configured:\n        settings.configure(myapp_defaults, DEBUG=True)\n\nAlso, it's an error to call ``configure()`` more than once, or to call\n``configure()`` after any setting has been accessed.\n\nIt boils down to this: Use exactly one of either ``configure()`` or\n:envvar:`DJANGO_SETTINGS_MODULE`. Not both, and not neither.\n\nCalling ``django.setup()`` is required for \"standalone\" Django usage\n--------------------------------------------------------------------\n\nIf you're using components of Django \"standalone\" -- for example, writing a\nPython script which loads some Django templates and renders them, or uses the\nORM to fetch some data -- there's one more step you'll need in addition to\nconfiguring settings.\n\nAfter you've either set :envvar:`DJANGO_SETTINGS_MODULE` or called\n``configure()``, you'll need to call :func:`django.setup()` to load your\nsettings and populate Django's application registry. For example::\n\n    import django\n    from django.conf import settings\n    from myapp import myapp_defaults\n\n    settings.configure(default_settings=myapp_defaults, DEBUG=True)\n    django.setup()\n\n    # Now this script or any imported module can use any part of Django it needs.\n    from myapp import models\n\nNote that calling ``django.setup()`` is only necessary if your code is truly\nstandalone. When invoked by your Web server, or through :doc:`django-admin\n</ref/django-admin>`, Django will handle this for you.\n\n.. admonition:: ``django.setup()`` may only be called once.\n\n    Therefore, avoid putting reusable application logic in standalone scripts\n    so that you have to import from the script elsewhere in your application.\n    If you can't avoid that, put the call to ``django.setup()`` inside an\n    ``if`` block::\n\n        if __name__ == '__main__':\n            import django\n            django.setup()\n\n.. seealso::\n\n    :doc:`The Settings Reference </ref/settings>`\n        Contains the complete list of core and contrib app settings.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":257,"nodeType":"TextFile","repoName":null,"name":"conditional-view-processing.txt","path":"docs/topics","text":"===========================\nConditional View Processing\n===========================\n\nHTTP clients can send a number of headers to tell the server about copies of a\nresource that they have already seen. This is commonly used when retrieving a\nWeb page (using an HTTP ``GET`` request) to avoid sending all the data for\nsomething the client has already retrieved. However, the same headers can be\nused for all HTTP methods (``POST``, ``PUT``, ``DELETE``, etc.).\n\nFor each page (response) that Django sends back from a view, it might provide\ntwo HTTP headers: the ``ETag`` header and the ``Last-Modified`` header. These\nheaders are optional on HTTP responses. They can be set by your view function,\nor you can rely on the :class:`~django.middleware.http.ConditionalGetMiddleware`\nmiddleware to set the ``ETag`` header.\n\nWhen the client next requests the same resource, it might send along a header\nsuch as either :rfc:`If-modified-since <7232#section-3.3>` or\n:rfc:`If-unmodified-since <7232#section-3.4>`, containing the date of the last\nmodification time it was sent, or either :rfc:`If-match <7232#section-3.1>` or\n:rfc:`If-none-match <7232#section-3.2>`, containing the last ``ETag`` it was\nsent. If the current version of the page matches the ``ETag`` sent by the\nclient, or if the resource has not been modified, a 304 status code can be sent\nback, instead of a full response, telling the client that nothing has changed.\nDepending on the header, if the page has been modified or does not match the\n``ETag`` sent by the client, a 412 status code (Precondition Failed) may be\nreturned.\n\nWhen you need more fine-grained control you may use per-view conditional\nprocessing functions.\n\n.. _conditional-decorators:\n\nThe ``condition`` decorator\n===========================\n\nSometimes (in fact, quite often) you can create functions to rapidly compute the ETag_\nvalue or the last-modified time for a resource, **without** needing to do all\nthe computations needed to construct the full view. Django can then use these\nfunctions to provide an \"early bailout\" option for the view processing.\nTelling the client that the content has not been modified since the last\nrequest, perhaps.\n\n.. _ETag: https://tools.ietf.org/html/rfc7232#section-2.3\n\nThese two functions are passed as parameters to the\n``django.views.decorators.http.condition`` decorator. This decorator uses\nthe two functions (you only need to supply one, if you can't compute both\nquantities easily and quickly) to work out if the headers in the HTTP request\nmatch those on the resource. If they don't match, a new copy of the resource\nmust be computed and your normal view is called.\n\nThe ``condition`` decorator's signature looks like this::\n\n    condition(etag_func=None, last_modified_func=None)\n\nThe two functions, to compute the ETag and the last modified time, will be\npassed the incoming ``request`` object and the same parameters, in the same\norder, as the view function they are helping to wrap. The function passed\n``last_modified_func`` should return a standard datetime value specifying the\nlast time the resource was modified, or ``None`` if the resource doesn't\nexist. The function passed to the ``etag`` decorator should return a string\nrepresenting the `ETag`_ for the resource, or ``None`` if it doesn't exist.\n\nThe decorator sets the ``ETag`` and ``Last-Modified`` headers on the response\nif they are not already set by the view and if the request's method is safe\n(``GET`` or ``HEAD``).\n\nUsing this feature usefully is probably best explained with an example.\nSuppose you have this pair of models, representing a small blog system::\n\n    import datetime\n    from django.db import models\n\n    class Blog(models.Model):\n        ...\n\n    class Entry(models.Model):\n        blog = models.ForeignKey(Blog, on_delete=models.CASCADE)\n        published = models.DateTimeField(default=datetime.datetime.now)\n        ...\n\nIf the front page, displaying the latest blog entries, only changes when you\nadd a new blog entry, you can compute the last modified time very quickly. You\nneed the latest ``published`` date for every entry associated with that blog.\nOne way to do this would be::\n\n    def latest_entry(request, blog_id):\n        return Entry.objects.filter(blog=blog_id).latest(\"published\").published\n\nYou can then use this function to provide early detection of an unchanged page\nfor your front page view::\n\n    from django.views.decorators.http import condition\n\n    @condition(last_modified_func=latest_entry)\n    def front_page(request, blog_id):\n        ...\n\n.. admonition:: Be careful with the order of decorators\n\n    When ``condition()`` returns a conditional response, any decorators below\n    it will be skipped and won't apply to the response. Therefore, any\n    decorators that need to apply to both the regular view response and a\n    conditional response must be above ``condition()``. In particular,\n    :func:`~django.views.decorators.vary.vary_on_cookie`,\n    :func:`~django.views.decorators.vary.vary_on_headers`, and\n    :func:`~django.views.decorators.cache.cache_control` should come first\n    because :rfc:`RFC 7232 <7232#section-4.1>` requires that the headers they\n    set be present on 304 responses.\n\nShortcuts for only computing one value\n======================================\n\nAs a general rule, if you can provide functions to compute *both* the ETag and\nthe last modified time, you should do so. You don't know which headers any\ngiven HTTP client will send you, so be prepared to handle both. However,\nsometimes only one value is easy to compute and Django provides decorators\nthat handle only ETag or only last-modified computations.\n\nThe ``django.views.decorators.http.etag`` and\n``django.views.decorators.http.last_modified`` decorators are passed the same\ntype of functions as the ``condition`` decorator. Their signatures are::\n\n    etag(etag_func)\n    last_modified(last_modified_func)\n\nWe could write the earlier example, which only uses a last-modified function,\nusing one of these decorators::\n\n    @last_modified(latest_entry)\n    def front_page(request, blog_id):\n        ...\n\n...or::\n\n    def front_page(request, blog_id):\n        ...\n    front_page = last_modified(latest_entry)(front_page)\n\nUse ``condition`` when testing both conditions\n----------------------------------------------\n\nIt might look nicer to some people to try and chain the ``etag`` and\n``last_modified`` decorators if you want to test both preconditions. However,\nthis would lead to incorrect behavior.\n\n::\n\n    # Bad code. Don't do this!\n    @etag(etag_func)\n    @last_modified(last_modified_func)\n    def my_view(request):\n        # ...\n\n    # End of bad code.\n\nThe first decorator doesn't know anything about the second and might\nanswer that the response is not modified even if the second decorators would\ndetermine otherwise. The ``condition`` decorator uses both callback functions\nsimultaneously to work out the right action to take.\n\nUsing the decorators with other HTTP methods\n============================================\n\nThe ``condition`` decorator is useful for more than only ``GET`` and\n``HEAD`` requests (``HEAD`` requests are the same as ``GET`` in this\nsituation). It can also be used to provide checking for ``POST``,\n``PUT`` and ``DELETE`` requests. In these situations, the idea isn't to return\na \"not modified\" response, but to tell the client that the resource they are\ntrying to change has been altered in the meantime.\n\nFor example, consider the following exchange between the client and server:\n\n#. Client requests ``/foo/``.\n#. Server responds with some content with an ETag of ``\"abcd1234\"``.\n#. Client sends an HTTP ``PUT`` request to ``/foo/`` to update the\n   resource. It also sends an ``If-Match: \"abcd1234\"`` header to specify\n   the version it is trying to update.\n#. Server checks to see if the resource has changed, by computing the ETag\n   the same way it does for a ``GET`` request (using the same function).\n   If the resource *has* changed, it will return a 412 status code,\n   meaning \"precondition failed\".\n#. Client sends a ``GET`` request to ``/foo/``, after receiving a 412\n   response, to retrieve an updated version of the content before updating\n   it.\n\nThe important thing this example shows is that the same functions can be used\nto compute the ETag and last modification values in all situations. In fact,\nyou **should** use the same functions, so that the same values are returned\nevery time.\n\n.. admonition:: Validator headers with non-safe request methods\n\n    The ``condition`` decorator only sets validator headers (``ETag`` and\n    ``Last-Modified``) for safe HTTP methods, i.e. ``GET`` and ``HEAD``. If you\n    wish to return them in other cases, set them in your view. See\n    :rfc:`7231#section-4.3.4` to learn about the distinction between setting a\n    validator header in response to requests made with ``PUT`` versus ``POST``.\n\nComparison with middleware conditional processing\n=================================================\n\nDjango provides conditional ``GET`` handling via\n:class:`django.middleware.http.ConditionalGetMiddleware`. While being suitable\nfor many situations, the middleware has limitations for advanced usage:\n\n* It's applied globally to all views in your project.\n* It doesn't save you from generating the response, which may be expensive.\n* It's only appropriate for HTTP ``GET`` requests.\n\nYou should choose the most appropriate tool for your particular problem here.\nIf you have a way to compute ETags and modification times quickly and if some\nview takes a while to generate the content, you should consider using the\n``condition`` decorator described in this document. If everything already runs\nfairly quickly, stick to using the middleware and the amount of network\ntraffic sent back to the clients will still be reduced if the view hasn't\nchanged.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":258,"nodeType":"TextFile","repoName":null,"name":"performance.txt","path":"docs/topics","text":"============================\nPerformance and optimization\n============================\n\nThis document provides an overview of techniques and tools that can help get\nyour Django code running more efficiently - faster, and using fewer system\nresources.\n\nIntroduction\n============\n\nGenerally one's first concern is to write code that *works*, whose logic\nfunctions as required to produce the expected output. Sometimes, however, this\nwill not be enough to make the code work as *efficiently* as one would like.\n\nIn this case, what's needed is something - and in practice, often a collection\nof things - to improve the code's performance without, or only minimally,\naffecting its behavior.\n\nGeneral approaches\n==================\n\nWhat are you optimizing *for*?\n------------------------------\n\nIt's important to have a clear idea what you mean by 'performance'. There is\nnot just one metric of it.\n\nImproved speed might be the most obvious aim for a program, but sometimes other\nperformance improvements might be sought, such as lower memory consumption or\nfewer demands on the database or network.\n\nImprovements in one area will often bring about improved performance in\nanother, but not always; sometimes one can even be at the expense of another.\nFor example, an improvement in a program's speed might cause it to use more\nmemory. Even worse, it can be self-defeating - if the speed improvement is so\nmemory-hungry that the system starts to run out of memory, you'll have done\nmore harm than good.\n\nThere are other trade-offs to bear in mind. Your own time is a valuable\nresource, more precious than CPU time. Some improvements might be too difficult\nto be worth implementing, or might affect the portability or maintainability of\nthe code. Not all performance improvements are worth the effort.\n\nSo, you need to know what performance improvements you are aiming for, and you\nalso need to know that you have a good reason for aiming in that direction -\nand for that you need:\n\nPerformance benchmarking\n------------------------\n\nIt's no good just guessing or assuming where the inefficiencies lie in your\ncode.\n\nDjango tools\n~~~~~~~~~~~~\n\n`django-debug-toolbar\n<https://github.com/jazzband/django-debug-toolbar/>`_ is a very handy tool that\nprovides insights into what your code is doing and how much time it spends\ndoing it. In particular it can show you all the SQL queries your page is\ngenerating, and how long each one has taken.\n\nThird-party panels are also available for the toolbar, that can (for example)\nreport on cache performance and template rendering times.\n\nThird-party services\n~~~~~~~~~~~~~~~~~~~~\n\nThere are a number of free services that will analyze and report on the\nperformance of your site's pages from the perspective of a remote HTTP client,\nin effect simulating the experience of an actual user.\n\nThese can't report on the internals of your code, but can provide a useful\ninsight into your site's overall performance, including aspects that can't be\nadequately measured from within Django environment. Examples include:\n\n* `Yahoo's Yslow <http://yslow.org/>`_\n* `Google PageSpeed <https://developers.google.com/speed/pagespeed/>`_\n\nThere are also several paid-for services that perform a similar analysis,\nincluding some that are Django-aware and can integrate with your codebase to\nprofile its performance far more comprehensively.\n\nGet things right from the start\n-------------------------------\n\nSome work in optimization involves tackling performance shortcomings, but some\nof the work can be built-in to what you'd do anyway, as part of the good\npractices you should adopt even before you start thinking about improving\nperformance.\n\nIn this respect Python is an excellent language to work with, because solutions\nthat look elegant and feel right usually are the best performing ones. As with\nmost skills, learning what \"looks right\" takes practice, but one of the most\nuseful guidelines is:\n\nWork at the appropriate level\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nDjango offers many different ways of approaching things, but just because it's\npossible to do something in a certain way doesn't mean that it's the most\nappropriate way to do it. For example, you might find that you could calculate\nthe same thing - the number of items in a collection, perhaps - in a\n``QuerySet``, in Python, or in a template.\n\nHowever, it will almost always be faster to do this work at lower rather than\nhigher levels. At higher levels the system has to deal with objects through\nmultiple levels of abstraction and layers of machinery.\n\nThat is, the database can typically do things faster than Python can, which can\ndo them faster than the template language can::\n\n    # QuerySet operation on the database\n    # fast, because that's what databases are good at\n    my_bicycles.count()\n\n    # counting Python objects\n    # slower, because it requires a database query anyway, and processing\n    # of the Python objects\n    len(my_bicycles)\n\n    # Django template filter\n    # slower still, because it will have to count them in Python anyway,\n    # and because of template language overheads\n    {{ my_bicycles|length }}\n\nGenerally speaking, the most appropriate level for the job is the lowest-level\none that it is comfortable to code for.\n\n.. note::\n\n    The example above is merely illustrative.\n\n    Firstly, in a real-life case you need to consider what is happening before\n    and after your count to work out what's an optimal way of doing it *in that\n    particular context*. The database optimization documents describes :ref:`a\n    case where counting in the template would be better\n    <overuse_of_count_and_exists>`.\n\n    Secondly, there are other options to consider: in a real-life case, ``{{\n    my_bicycles.count }}``, which invokes the ``QuerySet`` ``count()`` method\n    directly from the template, might be the most appropriate choice.\n\nCaching\n=======\n\nOften it is expensive (that is, resource-hungry and slow) to compute a value,\nso there can be huge benefit in saving the value to a quickly accessible cache,\nready for the next time it's required.\n\nIt's a sufficiently significant and powerful technique that Django includes a\ncomprehensive caching framework, as well as other smaller pieces of caching\nfunctionality.\n\n:doc:`The caching framework </topics/cache>`\n--------------------------------------------\n\nDjango's :doc:`caching framework </topics/cache>` offers very significant\nopportunities for performance gains, by saving dynamic content so that it\ndoesn't need to be calculated for each request.\n\nFor convenience, Django offers different levels of cache granularity: you can\ncache the output of specific views, or only the pieces that are difficult to\nproduce, or even an entire site.\n\nImplementing caching should not be regarded as an alternative to improving code\nthat's performing poorly because it has been written badly. It's one of the\nfinal steps towards producing well-performing code, not a shortcut.\n\n:class:`~django.utils.functional.cached_property`\n-------------------------------------------------\n\nIt's common to have to call a class instance's method more than once. If\nthat function is expensive, then doing so can be wasteful.\n\nUsing the :class:`~django.utils.functional.cached_property` decorator saves the\nvalue returned by a property; the next time the function is called on that\ninstance, it will return the saved value rather than re-computing it. Note that\nthis only works on methods that take ``self`` as their only argument and that\nit changes the method to a property.\n\nCertain Django components also have their own caching functionality; these are\ndiscussed below in the sections related to those components.\n\nUnderstanding laziness\n======================\n\n*Laziness* is a strategy complementary to caching. Caching avoids\nrecomputation by saving results; laziness delays computation until it's\nactually required.\n\nLaziness allows us to refer to things before they are instantiated, or even\nbefore it's possible to instantiate them. This has numerous uses.\n\nFor example, :ref:`lazy translation <lazy-translations>` can be used before the\ntarget language is even known, because it doesn't take place until the\ntranslated string is actually required, such as in a rendered template.\n\nLaziness is also a way to save effort by trying to avoid work in the first\nplace. That is, one aspect of laziness is not doing anything until it has to be\ndone, because it may not turn out to be necessary after all. Laziness can\ntherefore have performance implications, and the more expensive the work\nconcerned, the more there is to gain through laziness.\n\nPython provides a number of tools for lazy evaluation, particularly through the\n:py:term:`generator` and :py:term:`generator expression` constructs. It's worth\nreading up on laziness in Python to discover opportunities for making use of\nlazy patterns in your code.\n\nLaziness in Django\n------------------\n\nDjango is itself quite lazy. A good example of this can be found in the\nevaluation of ``QuerySets``. :ref:`QuerySets are lazy <querysets-are-lazy>`.\nThus a ``QuerySet`` can be created, passed around and combined with other\n``QuerySets``, without actually incurring any trips to the database to fetch\nthe items it describes. What gets passed around is the ``QuerySet`` object, not\nthe collection of items that - eventually - will be required from the database.\n\nOn the other hand, :ref:`certain operations will force the evaluation of a\nQuerySet <when-querysets-are-evaluated>`. Avoiding the premature evaluation of\na ``QuerySet`` can save making an expensive and unnecessary trip to the\ndatabase.\n\nDjango also offers a :meth:`~django.utils.functional.keep_lazy` decorator.\nThis allows a function that has been called with a lazy argument to behave\nlazily itself, only being evaluated when it needs to be. Thus the lazy argument\n- which could be an expensive one - will not be called upon for evaluation\nuntil it's strictly required.\n\nDatabases\n=========\n\nDatabase optimization\n---------------------\n\nDjango's database layer provides various ways to help developers get the best\nperformance from their databases. The :doc:`database optimization documentation\n</topics/db/optimization>` gathers together links to the relevant\ndocumentation and adds various tips that outline the steps to take when\nattempting to optimize your database usage.\n\nOther database-related tips\n---------------------------\n\nEnabling :ref:`persistent-database-connections` can speed up connections to the\ndatabase accounts for a significant part of the request processing time.\n\nThis helps a lot on virtualized hosts with limited network performance, for example.\n\nHTTP performance\n================\n\nMiddleware\n----------\n\nDjango comes with a few helpful pieces of :doc:`middleware </ref/middleware>`\nthat can help optimize your site's performance. They include:\n\n:class:`~django.middleware.http.ConditionalGetMiddleware`\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nAdds support for modern browsers to conditionally GET responses based on the\n``ETag`` and ``Last-Modified`` headers. It also calculates and sets an ETag if\nneeded.\n\n:class:`~django.middleware.gzip.GZipMiddleware`\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nCompresses responses for all modern browsers, saving bandwidth and transfer\ntime. Note that GZipMiddleware is currently considered a security risk, and is\nvulnerable to attacks that nullify the protection provided by TLS/SSL. See the\nwarning in :class:`~django.middleware.gzip.GZipMiddleware` for more information.\n\nSessions\n--------\n\nUsing cached sessions\n~~~~~~~~~~~~~~~~~~~~~\n\n:ref:`Using cached sessions <cached-sessions-backend>` may be a way to increase\nperformance by eliminating the need to load session data from a slower storage\nsource like the database and instead storing frequently used session data in\nmemory.\n\nStatic files\n------------\n\nStatic files, which by definition are not dynamic, make an excellent target for\noptimization gains.\n\n:class:`~django.contrib.staticfiles.storage.ManifestStaticFilesStorage`\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nBy taking advantage of web browsers' caching abilities, you can\neliminate network hits entirely for a given file after the initial download.\n\n:class:`~django.contrib.staticfiles.storage.ManifestStaticFilesStorage` appends a\ncontent-dependent tag to the filenames of :doc:`static files\n</ref/contrib/staticfiles>` to make it safe for browsers to cache them\nlong-term without missing future changes - when a file changes, so will the\ntag, so browsers will reload the asset automatically.\n\n\"Minification\"\n~~~~~~~~~~~~~~\n\nSeveral third-party Django tools and packages provide the ability to \"minify\"\nHTML, CSS, and JavaScript. They remove unnecessary whitespace, newlines, and\ncomments, and shorten variable names, and thus reduce the size of the documents\nthat your site publishes.\n\nTemplate performance\n====================\n\nNote that:\n\n* using ``{% block %}`` is faster than using ``{% include %}``\n* heavily-fragmented templates, assembled from many small pieces, can affect\n  performance\n\nThe cached template loader\n--------------------------\n\nEnabling the :class:`cached template loader\n<django.template.loaders.cached.Loader>` often improves performance\ndrastically, as it avoids compiling each template every time it needs to be\nrendered.\n\nUsing different versions of available software\n==============================================\n\nIt can sometimes be worth checking whether different and better-performing\nversions of the software that you're using are available.\n\nThese techniques are targeted at more advanced users who want to push the\nboundaries of performance of an already well-optimized Django site.\n\nHowever, they are not magic solutions to performance problems, and they're\nunlikely to bring better than marginal gains to sites that don't already do the\nmore basic things the right way.\n\n.. note::\n\n    It's worth repeating: **reaching for alternatives to software you're\n    already using is never the first answer to performance problems**. When\n    you reach this level of optimization, you need a formal benchmarking\n    solution.\n\nNewer is often - but not always - better\n----------------------------------------\n\nIt's fairly rare for a new release of well-maintained software to be less\nefficient, but the maintainers can't anticipate every possible use-case - so\nwhile being aware that newer versions are likely to perform better, don't\nassume that they always will.\n\nThis is true of Django itself. Successive releases have offered a number of\nimprovements across the system, but you should still check the real-world\nperformance of your application, because in some cases you may find that\nchanges mean it performs worse rather than better.\n\nNewer versions of Python, and also of Python packages, will often perform\nbetter too - but measure, rather than assume.\n\n.. note::\n\n    Unless you've encountered an unusual performance problem in a particular\n    version, you'll generally find better features, reliability, and security\n    in a new release and that these benefits are far more significant than any\n    performance you might win or lose.\n\nAlternatives to Django's template language\n------------------------------------------\n\nFor nearly all cases, Django's built-in template language is perfectly\nadequate. However, if the bottlenecks in your Django project seem to lie in the\ntemplate system and you have exhausted other opportunities to remedy this, a\nthird-party alternative may be the answer.\n\n`Jinja2 <http://jinja.pocoo.org/docs/>`_ can offer performance improvements,\nparticularly when it comes to speed.\n\nAlternative template systems vary in the extent to which they share Django's\ntemplating language.\n\n.. note::\n\n    *If* you experience performance issues in templates, the first thing to do\n    is to understand exactly why. Using an alternative template system may\n    prove faster, but the same gains may also be available without going to\n    that trouble - for example, expensive processing and logic in your\n    templates could be done more efficiently in your views.\n\nAlternative software implementations\n------------------------------------\n\nIt may be worth checking whether Python software you're using has been\nprovided in a different implementation that can execute the same code faster.\n\nHowever: most performance problems in well-written Django sites aren't at the\nPython execution level, but rather in inefficient database querying, caching,\nand templates. If you're relying on poorly-written Python code, your\nperformance problems are unlikely to be solved by having it execute faster.\n\nUsing an alternative implementation may introduce compatibility, deployment,\nportability, or maintenance issues. It goes without saying that before adopting\na non-standard implementation you should ensure it provides sufficient\nperformance gains for your application to outweigh the potential risks.\n\nWith these caveats in mind, you should be aware of:\n\n`PyPy <https://pypy.org/>`_\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n`PyPy <https://pypy.org/>`_ is an implementation of Python in Python itself\n(the 'standard' Python implementation is in C). PyPy can offer substantial\nperformance gains, typically for heavyweight applications.\n\nA key aim of the PyPy project is `compatibility\n<https://pypy.org/compat.html>`_ with existing Python APIs and libraries.\nDjango is compatible, but you will need to check the compatibility of other\nlibraries you rely on.\n\nC implementations of Python libraries\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nSome Python libraries are also implemented in C, and can be much faster. They\naim to offer the same APIs. Note that compatibility issues and behavior\ndifferences are not unknown (and not always immediately evident).\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":259,"nodeType":"TextFile","repoName":null,"name":"security.txt","path":"docs/topics","text":"==================\nSecurity in Django\n==================\n\nThis document is an overview of Django's security features. It includes advice\non securing a Django-powered site.\n\n.. _cross-site-scripting:\n\nCross site scripting (XSS) protection\n=====================================\n\n.. highlight:: html+django\n\nXSS attacks allow a user to inject client side scripts into the browsers of\nother users. This is usually achieved by storing the malicious scripts in the\ndatabase where it will be retrieved and displayed to other users, or by getting\nusers to click a link which will cause the attacker's JavaScript to be executed\nby the user's browser. However, XSS attacks can originate from any untrusted\nsource of data, such as cookies or Web services, whenever the data is not\nsufficiently sanitized before including in a page.\n\nUsing Django templates protects you against the majority of XSS attacks.\nHowever, it is important to understand what protections it provides\nand its limitations.\n\nDjango templates :ref:`escape specific characters <automatic-html-escaping>`\nwhich are particularly dangerous to HTML. While this protects users from most\nmalicious input, it is not entirely foolproof. For example, it will not\nprotect the following:\n\n.. code-block:: text\n\n    <style class={{ var }}>...</style>\n\n.. highlighting as html+django fails due to intentionally missing quotes.\n\nIf ``var`` is set to ``'class1 onmouseover=javascript:func()'``, this can result\nin unauthorized JavaScript execution, depending on how the browser renders\nimperfect HTML. (Quoting the attribute value would fix this case.)\n\nIt is also important to be particularly careful when using ``is_safe`` with\ncustom template tags, the :tfilter:`safe` template tag, :mod:`mark_safe\n<django.utils.safestring>`, and when autoescape is turned off.\n\nIn addition, if you are using the template system to output something other\nthan HTML, there may be entirely separate characters and words which require\nescaping.\n\nYou should also be very careful when storing HTML in the database, especially\nwhen that HTML is retrieved and displayed.\n\n\nCross site request forgery (CSRF) protection\n============================================\n\nCSRF attacks allow a malicious user to execute actions using the credentials\nof another user without that user's knowledge or consent.\n\nDjango has built-in protection against most types of CSRF attacks, providing you\nhave :ref:`enabled and used it <using-csrf>` where appropriate. However, as with\nany mitigation technique, there are limitations. For example, it is possible to\ndisable the CSRF module globally or for particular views. You should only do\nthis if you know what you are doing. There are other :ref:`limitations\n<csrf-limitations>` if your site has subdomains that are outside of your\ncontrol.\n\n:ref:`CSRF protection works <how-csrf-works>` by checking for a secret in each\nPOST request. This ensures that a malicious user cannot \"replay\" a form POST to\nyour website and have another logged in user unwittingly submit that form. The\nmalicious user would have to know the secret, which is user specific (using a\ncookie).\n\nWhen deployed with :ref:`HTTPS <security-recommendation-ssl>`,\n``CsrfViewMiddleware`` will check that the HTTP referer header is set to a\nURL on the same origin (including subdomain and port). Because HTTPS\nprovides additional security, it is imperative to ensure connections use HTTPS\nwhere it is available by forwarding insecure connection requests and using\nHSTS for supported browsers.\n\nBe very careful with marking views with the ``csrf_exempt`` decorator unless\nit is absolutely necessary.\n\n.. _sql-injection-protection:\n\nSQL injection protection\n========================\n\nSQL injection is a type of attack where a malicious user is able to execute\narbitrary SQL code on a database. This can result in records\nbeing deleted or data leakage.\n\nDjango's querysets are protected from SQL injection since their queries are\nconstructed using query parameterization. A query's SQL code is defined\nseparately from the query's parameters. Since parameters may be user-provided\nand therefore unsafe, they are escaped by the underlying database driver.\n\nDjango also gives developers power to write :ref:`raw queries\n<executing-raw-queries>` or execute :ref:`custom sql <executing-custom-sql>`.\nThese capabilities should be used sparingly and you should always be careful to\nproperly escape any parameters that the user can control. In addition, you\nshould exercise caution when using :meth:`~django.db.models.query.QuerySet.extra`\nand :class:`~django.db.models.expressions.RawSQL`.\n\nClickjacking protection\n=======================\n\nClickjacking is a type of attack where a malicious site wraps another site\nin a frame. This attack can result in an unsuspecting user being tricked\ninto performing unintended actions on the target site.\n\nDjango contains :ref:`clickjacking protection <clickjacking-prevention>` in\nthe form of the\n:mod:`X-Frame-Options middleware <django.middleware.clickjacking.XFrameOptionsMiddleware>`\nwhich in a supporting browser can prevent a site from being rendered inside\na frame. It is possible to disable the protection on a per view basis\nor to configure the exact header value sent.\n\nThe middleware is strongly recommended for any site that does not need to have\nits pages wrapped in a frame by third party sites, or only needs to allow that\nfor a small section of the site.\n\n.. _security-recommendation-ssl:\n\nSSL/HTTPS\n=========\n\nIt is always better for security to deploy your site behind HTTPS. Without\nthis, it is possible for malicious network users to sniff authentication\ncredentials or any other information transferred between client and server, and\nin some cases -- **active** network attackers -- to alter data that is sent in\neither direction.\n\nIf you want the protection that HTTPS provides, and have enabled it on your\nserver, there are some additional steps you may need:\n\n* If necessary, set :setting:`SECURE_PROXY_SSL_HEADER`, ensuring that you have\n  understood the warnings there thoroughly. Failure to do this can result\n  in CSRF vulnerabilities, and failure to do it correctly can also be\n  dangerous!\n\n* Set :setting:`SECURE_SSL_REDIRECT` to ``True``, so that requests over HTTP\n  are redirected to HTTPS.\n\n  Please note the caveats under :setting:`SECURE_PROXY_SSL_HEADER`. For the\n  case of a reverse proxy, it may be easier or more secure to configure the\n  main Web server to do the redirect to HTTPS.\n\n* Use 'secure' cookies.\n\n  If a browser connects initially via HTTP, which is the default for most\n  browsers, it is possible for existing cookies to be leaked. For this reason,\n  you should set your :setting:`SESSION_COOKIE_SECURE` and\n  :setting:`CSRF_COOKIE_SECURE` settings to ``True``. This instructs the browser\n  to only send these cookies over HTTPS connections. Note that this will mean\n  that sessions will not work over HTTP, and the CSRF protection will prevent\n  any POST data being accepted over HTTP (which will be fine if you are\n  redirecting all HTTP traffic to HTTPS).\n\n* Use :ref:`http-strict-transport-security` (HSTS)\n\n  HSTS is an HTTP header that informs a browser that all future connections\n  to a particular site should always use HTTPS. Combined with redirecting\n  requests over HTTP to HTTPS, this will ensure that connections always enjoy\n  the added security of SSL provided one successful connection has occurred.\n  HSTS may either be configured with :setting:`SECURE_HSTS_SECONDS`,\n  :setting:`SECURE_HSTS_INCLUDE_SUBDOMAINS`, and :setting:`SECURE_HSTS_PRELOAD`,\n  or on the Web server.\n\n.. _host-headers-virtual-hosting:\n\nHost header validation\n======================\n\nDjango uses the ``Host`` header provided by the client to construct URLs in\ncertain cases. While these values are sanitized to prevent Cross Site Scripting\nattacks, a fake ``Host`` value can be used for Cross-Site Request Forgery,\ncache poisoning attacks, and poisoning links in emails.\n\nBecause even seemingly-secure web server configurations are susceptible to fake\n``Host`` headers, Django validates ``Host`` headers against the\n:setting:`ALLOWED_HOSTS` setting in the\n:meth:`django.http.HttpRequest.get_host()` method.\n\nThis validation only applies via :meth:`~django.http.HttpRequest.get_host()`;\nif your code accesses the ``Host`` header directly from ``request.META`` you\nare bypassing this security protection.\n\nFor more details see the full :setting:`ALLOWED_HOSTS` documentation.\n\n.. warning::\n\n   Previous versions of this document recommended configuring your web server to\n   ensure it validates incoming HTTP ``Host`` headers. While this is still\n   recommended, in many common web servers a configuration that seems to\n   validate the ``Host`` header may not in fact do so. For instance, even if\n   Apache is configured such that your Django site is served from a non-default\n   virtual host with the ``ServerName`` set, it is still possible for an HTTP\n   request to match this virtual host and supply a fake ``Host`` header. Thus,\n   Django now requires that you set :setting:`ALLOWED_HOSTS` explicitly rather\n   than relying on web server configuration.\n\nAdditionally, Django requires you to explicitly enable support for the\n``X-Forwarded-Host`` header (via the :setting:`USE_X_FORWARDED_HOST` setting)\nif your configuration requires it.\n\nReferrer policy\n===============\n\nBrowsers use the ``Referer`` header as a way to send information to a site\nabout how users got there. By setting a *Referrer Policy* you can help to\nprotect the privacy of your users, restricting under which circumstances the\n``Referer`` header is set. See :ref:`the referrer policy section of the\nsecurity middleware reference <referrer-policy>` for details.\n\nSession security\n================\n\nSimilar to the :ref:`CSRF limitations <csrf-limitations>` requiring a site to\nbe deployed such that untrusted users don't have access to any subdomains,\n:mod:`django.contrib.sessions` also has limitations. See :ref:`the session\ntopic guide section on security <topics-session-security>` for details.\n\n.. _user-uploaded-content-security:\n\nUser-uploaded content\n=====================\n\n.. note::\n    Consider :ref:`serving static files from a cloud service or CDN\n    <staticfiles-from-cdn>` to avoid some of these issues.\n\n* If your site accepts file uploads, it is strongly advised that you limit\n  these uploads in your Web server configuration to a reasonable\n  size in order to prevent denial of service (DOS) attacks. In Apache, this\n  can be easily set using the LimitRequestBody_ directive.\n\n* If you are serving your own static files, be sure that handlers like Apache's\n  ``mod_php``, which would execute static files as code, are disabled. You don't\n  want users to be able to execute arbitrary code by uploading and requesting a\n  specially crafted file.\n\n* Django's media upload handling poses some vulnerabilities when that media is\n  served in ways that do not follow security best practices. Specifically, an\n  HTML file can be uploaded as an image if that file contains a valid PNG\n  header followed by malicious HTML. This file will pass verification of the\n  library that Django uses for :class:`~django.db.models.ImageField` image\n  processing (Pillow). When this file is subsequently displayed to a\n  user, it may be displayed as HTML depending on the type and configuration of\n  your web server.\n\n  No bulletproof technical solution exists at the framework level to safely\n  validate all user uploaded file content, however, there are some other steps\n  you can take to mitigate these attacks:\n\n  #. One class of attacks can be prevented by always serving user uploaded\n     content from a distinct top-level or second-level domain. This prevents\n     any exploit blocked by `same-origin policy`_ protections such as cross\n     site scripting. For example, if your site runs on ``example.com``, you\n     would want to serve uploaded content (the :setting:`MEDIA_URL` setting)\n     from something like ``usercontent-example.com``. It's *not* sufficient to\n     serve content from a subdomain like ``usercontent.example.com``.\n\n  #. Beyond this, applications may choose to define a whitelist of allowable\n     file extensions for user uploaded files and configure the web server\n     to only serve such files.\n\n.. _same-origin policy: https://en.wikipedia.org/wiki/Same-origin_policy\n\n.. _additional-security-topics:\n\nAdditional security topics\n==========================\n\nWhile Django provides good security protection out of the box, it is still\nimportant to properly deploy your application and take advantage of the\nsecurity protection of the Web server, operating system and other components.\n\n* Make sure that your Python code is outside of the Web server's root. This\n  will ensure that your Python code is not accidentally served as plain text\n  (or accidentally executed).\n* Take care with any :ref:`user uploaded files <file-upload-security>`.\n* Django does not throttle requests to authenticate users. To protect against\n  brute-force attacks against the authentication system, you may consider\n  deploying a Django plugin or Web server module to throttle these requests.\n* Keep your :setting:`SECRET_KEY` a secret.\n* It is a good idea to limit the accessibility of your caching system and\n  database using a firewall.\n* Take a look at the Open Web Application Security Project (OWASP) `Top 10\n  list`_ which identifies some common vulnerabilities in web applications. While\n  Django has tools to address some of the issues, other issues must be\n  accounted for in the design of your project.\n* Mozilla discusses various topics regarding `web security`_. Their\n  pages also include security principles that apply to any system.\n\n.. _LimitRequestBody: https://httpd.apache.org/docs/2.4/mod/core.html#limitrequestbody\n.. _Top 10 list: https://www.owasp.org/index.php/Top_10-2017_Top_10\n.. _web security: https://infosec.mozilla.org/guidelines/web_security.html\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":260,"nodeType":"TextFile","repoName":null,"name":"email.txt","path":"docs/topics","text":"=============\nSending email\n=============\n\n.. module:: django.core.mail\n   :synopsis: Helpers to easily send email.\n\nAlthough Python provides a mail sending interface via the :mod:`smtplib`\nmodule, Django provides a couple of light wrappers over it. These wrappers are\nprovided to make sending email extra quick, to help test email sending during\ndevelopment, and to provide support for platforms that can't use SMTP.\n\nThe code lives in the ``django.core.mail`` module.\n\nQuick example\n=============\n\nIn two lines::\n\n    from django.core.mail import send_mail\n\n    send_mail(\n        'Subject here',\n        'Here is the message.',\n        'from@example.com',\n        ['to@example.com'],\n        fail_silently=False,\n    )\n\nMail is sent using the SMTP host and port specified in the\n:setting:`EMAIL_HOST` and :setting:`EMAIL_PORT` settings. The\n:setting:`EMAIL_HOST_USER` and :setting:`EMAIL_HOST_PASSWORD` settings, if\nset, are used to authenticate to the SMTP server, and the\n:setting:`EMAIL_USE_TLS` and :setting:`EMAIL_USE_SSL` settings control whether\na secure connection is used.\n\n.. note::\n\n    The character set of email sent with ``django.core.mail`` will be set to\n    the value of your :setting:`DEFAULT_CHARSET` setting.\n\n``send_mail()``\n===============\n\n.. function:: send_mail(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None, html_message=None)\n\nIn most cases, you can send email using ``django.core.mail.send_mail()``.\n\nThe ``subject``, ``message``, ``from_email`` and ``recipient_list`` parameters\nare required.\n\n* ``subject``: A string.\n* ``message``: A string.\n* ``from_email``: A string. If ``None``, Django will use the value of the\n  :setting:`DEFAULT_FROM_EMAIL` setting.\n* ``recipient_list``: A list of strings, each an email address. Each\n  member of ``recipient_list`` will see the other recipients in the \"To:\"\n  field of the email message.\n* ``fail_silently``: A boolean. When it's ``False``, ``send_mail()`` will raise\n  an :exc:`smtplib.SMTPException` if an error occurs. See the :mod:`smtplib`\n  docs for a list of possible exceptions, all of which are subclasses of\n  :exc:`~smtplib.SMTPException`.\n* ``auth_user``: The optional username to use to authenticate to the SMTP\n  server. If this isn't provided, Django will use the value of the\n  :setting:`EMAIL_HOST_USER` setting.\n* ``auth_password``: The optional password to use to authenticate to the\n  SMTP server. If this isn't provided, Django will use the value of the\n  :setting:`EMAIL_HOST_PASSWORD` setting.\n* ``connection``: The optional email backend to use to send the mail.\n  If unspecified, an instance of the default backend will be used.\n  See the documentation on :ref:`Email backends <topic-email-backends>`\n  for more details.\n* ``html_message``: If ``html_message`` is provided, the resulting email will be a\n  :mimetype:`multipart/alternative` email with ``message`` as the\n  :mimetype:`text/plain` content type and ``html_message`` as the\n  :mimetype:`text/html` content type.\n\nThe return value will be the number of successfully delivered messages (which\ncan be ``0`` or ``1`` since it can only send one message).\n\n``send_mass_mail()``\n====================\n\n.. function:: send_mass_mail(datatuple, fail_silently=False, auth_user=None, auth_password=None, connection=None)\n\n``django.core.mail.send_mass_mail()`` is intended to handle mass emailing.\n\n``datatuple`` is a tuple in which each element is in this format::\n\n    (subject, message, from_email, recipient_list)\n\n``fail_silently``, ``auth_user`` and ``auth_password`` have the same functions\nas in :meth:`~django.core.mail.send_mail()`.\n\nEach separate element of ``datatuple`` results in a separate email message.\nAs in :meth:`~django.core.mail.send_mail()`, recipients in the same\n``recipient_list`` will all see the other addresses in the email messages'\n\"To:\" field.\n\nFor example, the following code would send two different messages to\ntwo different sets of recipients; however, only one connection to the\nmail server would be opened::\n\n    message1 = ('Subject here', 'Here is the message', 'from@example.com', ['first@example.com', 'other@example.com'])\n    message2 = ('Another Subject', 'Here is another message', 'from@example.com', ['second@test.com'])\n    send_mass_mail((message1, message2), fail_silently=False)\n\nThe return value will be the number of successfully delivered messages.\n\n``send_mass_mail()`` vs. ``send_mail()``\n----------------------------------------\n\nThe main difference between :meth:`~django.core.mail.send_mass_mail()` and\n:meth:`~django.core.mail.send_mail()` is that\n:meth:`~django.core.mail.send_mail()` opens a connection to the mail server\neach time it's executed, while :meth:`~django.core.mail.send_mass_mail()` uses\na single connection for all of its messages. This makes\n:meth:`~django.core.mail.send_mass_mail()` slightly more efficient.\n\n``mail_admins()``\n=================\n\n.. function:: mail_admins(subject, message, fail_silently=False, connection=None, html_message=None)\n\n``django.core.mail.mail_admins()`` is a shortcut for sending an email to the\nsite admins, as defined in the :setting:`ADMINS` setting.\n\n``mail_admins()`` prefixes the subject with the value of the\n:setting:`EMAIL_SUBJECT_PREFIX` setting, which is ``\"[Django] \"`` by default.\n\nThe \"From:\" header of the email will be the value of the\n:setting:`SERVER_EMAIL` setting.\n\nThis method exists for convenience and readability.\n\nIf ``html_message`` is provided, the resulting email will be a\n:mimetype:`multipart/alternative` email with ``message`` as the\n:mimetype:`text/plain` content type and ``html_message`` as the\n:mimetype:`text/html` content type.\n\n``mail_managers()``\n===================\n\n.. function:: mail_managers(subject, message, fail_silently=False, connection=None, html_message=None)\n\n``django.core.mail.mail_managers()`` is just like ``mail_admins()``, except it\nsends an email to the site managers, as defined in the :setting:`MANAGERS`\nsetting.\n\nExamples\n========\n\nThis sends a single email to john@example.com and jane@example.com, with them\nboth appearing in the \"To:\"::\n\n    send_mail(\n        'Subject',\n        'Message.',\n        'from@example.com',\n        ['john@example.com', 'jane@example.com'],\n    )\n\nThis sends a message to john@example.com and jane@example.com, with them both\nreceiving a separate email::\n\n    datatuple = (\n        ('Subject', 'Message.', 'from@example.com', ['john@example.com']),\n        ('Subject', 'Message.', 'from@example.com', ['jane@example.com']),\n    )\n    send_mass_mail(datatuple)\n\nPreventing header injection\n===========================\n\n`Header injection`_ is a security exploit in which an attacker inserts extra\nemail headers to control the \"To:\" and \"From:\" in email messages that your\nscripts generate.\n\nThe Django email functions outlined above all protect against header injection\nby forbidding newlines in header values. If any ``subject``, ``from_email`` or\n``recipient_list`` contains a newline (in either Unix, Windows or Mac style),\nthe email function (e.g. :meth:`~django.core.mail.send_mail()`) will raise\n``django.core.mail.BadHeaderError`` (a subclass of ``ValueError``) and, hence,\nwill not send the email. It's your responsibility to validate all data before\npassing it to the email functions.\n\nIf a ``message`` contains headers at the start of the string, the headers will\nbe printed as the first bit of the email message.\n\nHere's an example view that takes a ``subject``, ``message`` and ``from_email``\nfrom the request's POST data, sends that to admin@example.com and redirects to\n\"/contact/thanks/\" when it's done::\n\n    from django.core.mail import BadHeaderError, send_mail\n    from django.http import HttpResponse, HttpResponseRedirect\n\n    def send_email(request):\n        subject = request.POST.get('subject', '')\n        message = request.POST.get('message', '')\n        from_email = request.POST.get('from_email', '')\n        if subject and message and from_email:\n            try:\n                send_mail(subject, message, from_email, ['admin@example.com'])\n            except BadHeaderError:\n                return HttpResponse('Invalid header found.')\n            return HttpResponseRedirect('/contact/thanks/')\n        else:\n            # In reality we'd use a form class\n            # to get proper validation errors.\n            return HttpResponse('Make sure all fields are entered and valid.')\n\n.. _Header injection: http://www.nyphp.org/phundamentals/8_Preventing-Email-Header-Injection\n\n.. _emailmessage-and-smtpconnection:\n\nThe ``EmailMessage`` class\n==========================\n\nDjango's :meth:`~django.core.mail.send_mail()` and\n:meth:`~django.core.mail.send_mass_mail()` functions are actually thin\nwrappers that make use of the :class:`~django.core.mail.EmailMessage` class.\n\nNot all features of the :class:`~django.core.mail.EmailMessage` class are\navailable through the :meth:`~django.core.mail.send_mail()` and related\nwrapper functions. If you wish to use advanced features, such as BCC'ed\nrecipients, file attachments, or multi-part email, you'll need to create\n:class:`~django.core.mail.EmailMessage` instances directly.\n\n.. note::\n    This is a design feature. :meth:`~django.core.mail.send_mail()` and\n    related functions were originally the only interface Django provided.\n    However, the list of parameters they accepted was slowly growing over\n    time. It made sense to move to a more object-oriented design for email\n    messages and retain the original functions only for backwards\n    compatibility.\n\n:class:`~django.core.mail.EmailMessage` is responsible for creating the email\nmessage itself. The :ref:`email backend <topic-email-backends>` is then\nresponsible for sending the email.\n\nFor convenience, :class:`~django.core.mail.EmailMessage` provides a ``send()``\nmethod for sending a single email. If you need to send multiple messages, the\nemail backend API :ref:`provides an alternative\n<topics-sending-multiple-emails>`.\n\n``EmailMessage`` Objects\n------------------------\n\n.. class:: EmailMessage\n\nThe :class:`~django.core.mail.EmailMessage` class is initialized with the\nfollowing parameters (in the given order, if positional arguments are used).\nAll parameters are optional and can be set at any time prior to calling the\n``send()`` method.\n\n* ``subject``: The subject line of the email.\n\n* ``body``: The body text. This should be a plain text message.\n\n* ``from_email``: The sender's address. Both ``fred@example.com`` and\n  ``\"Fred\" <fred@example.com>`` forms are legal. If omitted, the\n  :setting:`DEFAULT_FROM_EMAIL` setting is used.\n\n* ``to``: A list or tuple of recipient addresses.\n\n* ``bcc``: A list or tuple of addresses used in the \"Bcc\" header when\n  sending the email.\n\n* ``connection``: An email backend instance. Use this parameter if\n  you want to use the same connection for multiple messages. If omitted, a\n  new connection is created when ``send()`` is called.\n\n* ``attachments``: A list of attachments to put on the message. These can\n  be either :class:`~email.mime.base.MIMEBase` instances, or ``(filename,\n  content, mimetype)`` triples.\n\n* ``headers``: A dictionary of extra headers to put on the message. The\n  keys are the header name, values are the header values. It's up to the\n  caller to ensure header names and values are in the correct format for\n  an email message. The corresponding attribute is ``extra_headers``.\n\n* ``cc``: A list or tuple of recipient addresses used in the \"Cc\" header\n  when sending the email.\n\n* ``reply_to``: A list or tuple of recipient addresses used in the \"Reply-To\"\n  header when sending the email.\n\nFor example::\n\n    from django.core.mail import EmailMessage\n\n    email = EmailMessage(\n        'Hello',\n        'Body goes here',\n        'from@example.com',\n        ['to1@example.com', 'to2@example.com'],\n        ['bcc@example.com'],\n        reply_to=['another@example.com'],\n        headers={'Message-ID': 'foo'},\n    )\n\nThe class has the following methods:\n\n* ``send(fail_silently=False)`` sends the message. If a connection was\n  specified when the email was constructed, that connection will be used.\n  Otherwise, an instance of the default backend will be instantiated and\n  used. If the keyword argument ``fail_silently`` is ``True``, exceptions\n  raised while sending the message will be quashed. An empty list of\n  recipients will not raise an exception.\n\n* ``message()`` constructs a ``django.core.mail.SafeMIMEText`` object (a\n  subclass of Python's :class:`~email.mime.text.MIMEText` class) or a\n  ``django.core.mail.SafeMIMEMultipart`` object holding the message to be\n  sent. If you ever need to extend the\n  :class:`~django.core.mail.EmailMessage` class, you'll probably want to\n  override this method to put the content you want into the MIME object.\n\n* ``recipients()`` returns a list of all the recipients of the message,\n  whether they're recorded in the ``to``, ``cc`` or ``bcc`` attributes. This\n  is another method you might need to override when subclassing, because the\n  SMTP server needs to be told the full list of recipients when the message\n  is sent. If you add another way to specify recipients in your class, they\n  need to be returned from this method as well.\n\n* ``attach()`` creates a new file attachment and adds it to the message.\n  There are two ways to call ``attach()``:\n\n  * You can pass it a single argument that is a\n    :class:`~email.mime.base.MIMEBase` instance. This will be inserted directly\n    into the resulting message.\n\n  * Alternatively, you can pass ``attach()`` three arguments:\n    ``filename``, ``content`` and ``mimetype``. ``filename`` is the name\n    of the file attachment as it will appear in the email, ``content`` is\n    the data that will be contained inside the attachment and\n    ``mimetype`` is the optional MIME type for the attachment. If you\n    omit ``mimetype``, the MIME content type will be guessed from the\n    filename of the attachment.\n\n    For example::\n\n       message.attach('design.png', img_data, 'image/png')\n\n    If you specify a ``mimetype`` of :mimetype:`message/rfc822`, it will also\n    accept :class:`django.core.mail.EmailMessage` and\n    :py:class:`email.message.Message`.\n\n    For a ``mimetype`` starting with :mimetype:`text/`, content is expected to\n    be a string. Binary data will be decoded using UTF-8, and if that fails,\n    the MIME type will be changed to :mimetype:`application/octet-stream` and\n    the data will be attached unchanged.\n\n    In addition, :mimetype:`message/rfc822` attachments will no longer be\n    base64-encoded in violation of :rfc:`2046#section-5.2.1`, which can cause\n    issues with displaying the attachments in `Evolution`__ and `Thunderbird`__.\n\n    __ https://bugzilla.gnome.org/show_bug.cgi?id=651197\n    __ https://bugzilla.mozilla.org/show_bug.cgi?id=333880\n\n* ``attach_file()`` creates a new attachment using a file from your\n  filesystem. Call it with the path of the file to attach and, optionally,\n  the MIME type to use for the attachment. If the MIME type is omitted, it\n  will be guessed from the filename. You can use it like this::\n\n    message.attach_file('/images/weather_map.png')\n\n  For MIME types starting with :mimetype:`text/`, binary data is handled as in\n  ``attach()``.\n\nSending alternative content types\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIt can be useful to include multiple versions of the content in an email; the\nclassic example is to send both text and HTML versions of a message. With\nDjango's email library, you can do this using the ``EmailMultiAlternatives``\nclass. This subclass of :class:`~django.core.mail.EmailMessage` has an\n``attach_alternative()`` method for including extra versions of the message\nbody in the email. All the other methods (including the class initialization)\nare inherited directly from :class:`~django.core.mail.EmailMessage`.\n\nTo send a text and HTML combination, you could write::\n\n    from django.core.mail import EmailMultiAlternatives\n\n    subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'\n    text_content = 'This is an important message.'\n    html_content = '<p>This is an <strong>important</strong> message.</p>'\n    msg = EmailMultiAlternatives(subject, text_content, from_email, [to])\n    msg.attach_alternative(html_content, \"text/html\")\n    msg.send()\n\nBy default, the MIME type of the ``body`` parameter in an\n:class:`~django.core.mail.EmailMessage` is ``\"text/plain\"``. It is good\npractice to leave this alone, because it guarantees that any recipient will be\nable to read the email, regardless of their mail client. However, if you are\nconfident that your recipients can handle an alternative content type, you can\nuse the ``content_subtype`` attribute on the\n:class:`~django.core.mail.EmailMessage` class to change the main content type.\nThe major type will always be ``\"text\"``, but you can change the\nsubtype. For example::\n\n    msg = EmailMessage(subject, html_content, from_email, [to])\n    msg.content_subtype = \"html\"  # Main content is now text/html\n    msg.send()\n\n.. _topic-email-backends:\n\nEmail backends\n==============\n\nThe actual sending of an email is handled by the email backend.\n\nThe email backend class has the following methods:\n\n* ``open()`` instantiates a long-lived email-sending connection.\n\n* ``close()`` closes the current email-sending connection.\n\n* ``send_messages(email_messages)`` sends a list of\n  :class:`~django.core.mail.EmailMessage` objects. If the connection is\n  not open, this call will implicitly open the connection, and close the\n  connection afterwards. If the connection is already open, it will be\n  left open after mail has been sent.\n\nIt can also be used as a context manager, which will automatically call\n``open()`` and ``close()`` as needed::\n\n    from django.core import mail\n\n    with mail.get_connection() as connection:\n        mail.EmailMessage(\n            subject1, body1, from1, [to1],\n            connection=connection,\n        ).send()\n        mail.EmailMessage(\n            subject2, body2, from2, [to2],\n            connection=connection,\n        ).send()\n\nObtaining an instance of an email backend\n-----------------------------------------\n\nThe :meth:`get_connection` function in ``django.core.mail`` returns an\ninstance of the email backend that you can use.\n\n.. currentmodule:: django.core.mail\n\n.. function:: get_connection(backend=None, fail_silently=False, *args, **kwargs)\n\nBy default, a call to ``get_connection()`` will return an instance of the\nemail backend specified in :setting:`EMAIL_BACKEND`. If you specify the\n``backend`` argument, an instance of that backend will be instantiated.\n\nThe ``fail_silently`` argument controls how the backend should handle errors.\nIf ``fail_silently`` is True, exceptions during the email sending process\nwill be silently ignored.\n\nAll other arguments are passed directly to the constructor of the\nemail backend.\n\nDjango ships with several email sending backends. With the exception of the\nSMTP backend (which is the default), these backends are only useful during\ntesting and development. If you have special email sending requirements, you\ncan :ref:`write your own email backend <topic-custom-email-backend>`.\n\n.. _topic-email-smtp-backend:\n\nSMTP backend\n~~~~~~~~~~~~\n\n.. class:: backends.smtp.EmailBackend(host=None, port=None, username=None, password=None, use_tls=None, fail_silently=False, use_ssl=None, timeout=None, ssl_keyfile=None, ssl_certfile=None, **kwargs)\n\n    This is the default backend. Email will be sent through a SMTP server.\n\n    The value for each argument is retrieved from the matching setting if the\n    argument is ``None``:\n\n    * ``host``: :setting:`EMAIL_HOST`\n    * ``port``: :setting:`EMAIL_PORT`\n    * ``username``: :setting:`EMAIL_HOST_USER`\n    * ``password``: :setting:`EMAIL_HOST_PASSWORD`\n    * ``use_tls``: :setting:`EMAIL_USE_TLS`\n    * ``use_ssl``: :setting:`EMAIL_USE_SSL`\n    * ``timeout``: :setting:`EMAIL_TIMEOUT`\n    * ``ssl_keyfile``: :setting:`EMAIL_SSL_KEYFILE`\n    * ``ssl_certfile``: :setting:`EMAIL_SSL_CERTFILE`\n\n    The SMTP backend is the default configuration inherited by Django. If you\n    want to specify it explicitly, put the following in your settings::\n\n        EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'\n\n    If unspecified, the default ``timeout`` will be the one provided by\n    :func:`socket.getdefaulttimeout()`, which defaults to ``None`` (no timeout).\n\n.. _topic-email-console-backend:\n\nConsole backend\n~~~~~~~~~~~~~~~\n\nInstead of sending out real emails the console backend just writes the\nemails that would be sent to the standard output. By default, the console\nbackend writes to ``stdout``. You can use a different stream-like object by\nproviding the ``stream`` keyword argument when constructing the connection.\n\nTo specify this backend, put the following in your settings::\n\n    EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n\nThis backend is not intended for use in production -- it is provided as a\nconvenience that can be used during development.\n\n.. _topic-email-file-backend:\n\nFile backend\n~~~~~~~~~~~~\n\nThe file backend writes emails to a file. A new file is created for each new\nsession that is opened on this backend. The directory to which the files are\nwritten is either taken from the :setting:`EMAIL_FILE_PATH` setting or from\nthe ``file_path`` keyword when creating a connection with\n:meth:`~django.core.mail.get_connection`.\n\nTo specify this backend, put the following in your settings::\n\n    EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'\n    EMAIL_FILE_PATH = '/tmp/app-messages' # change this to a proper location\n\nThis backend is not intended for use in production -- it is provided as a\nconvenience that can be used during development.\n\n.. versionchanged:: 3.1\n\n    Support for :class:`pathlib.Path` was added.\n\n.. _topic-email-memory-backend:\n\nIn-memory backend\n~~~~~~~~~~~~~~~~~\n\nThe ``'locmem'`` backend stores messages in a special attribute of the\n``django.core.mail`` module. The ``outbox`` attribute is created when the\nfirst message is sent. It's a list with an\n:class:`~django.core.mail.EmailMessage` instance for each message that would\nbe sent.\n\nTo specify this backend, put the following in your settings::\n\n  EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'\n\nThis backend is not intended for use in production -- it is provided as a\nconvenience that can be used during development and testing.\n\nDjango's test runner :ref:`automatically uses this backend for testing\n<topics-testing-email>`.\n\n.. _topic-email-dummy-backend:\n\nDummy backend\n~~~~~~~~~~~~~\n\nAs the name suggests the dummy backend does nothing with your messages. To\nspecify this backend, put the following in your settings::\n\n   EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend'\n\nThis backend is not intended for use in production -- it is provided as a\nconvenience that can be used during development.\n\n.. _topic-custom-email-backend:\n\nDefining a custom email backend\n-------------------------------\n\nIf you need to change how emails are sent you can write your own email\nbackend. The :setting:`EMAIL_BACKEND` setting in your settings file is then\nthe Python import path for your backend class.\n\nCustom email backends should subclass ``BaseEmailBackend`` that is located in\nthe ``django.core.mail.backends.base`` module. A custom email backend must\nimplement the ``send_messages(email_messages)`` method. This method receives a\nlist of :class:`~django.core.mail.EmailMessage` instances and returns the\nnumber of successfully delivered messages. If your backend has any concept of\na persistent session or connection, you should also implement the ``open()``\nand ``close()`` methods. Refer to ``smtp.EmailBackend`` for a reference\nimplementation.\n\n.. _topics-sending-multiple-emails:\n\nSending multiple emails\n-----------------------\n\nEstablishing and closing an SMTP connection (or any other network connection,\nfor that matter) is an expensive process. If you have a lot of emails to send,\nit makes sense to reuse an SMTP connection, rather than creating and\ndestroying a connection every time you want to send an email.\n\nThere are two ways you tell an email backend to reuse a connection.\n\nFirstly, you can use the ``send_messages()`` method. ``send_messages()`` takes\na list of :class:`~django.core.mail.EmailMessage` instances (or subclasses),\nand sends them all using a single connection.\n\nFor example, if you have a function called ``get_notification_email()`` that\nreturns a list of :class:`~django.core.mail.EmailMessage` objects representing\nsome periodic email you wish to send out, you could send these emails using\na single call to send_messages::\n\n    from django.core import mail\n    connection = mail.get_connection()   # Use default email connection\n    messages = get_notification_email()\n    connection.send_messages(messages)\n\nIn this example, the call to ``send_messages()`` opens a connection on the\nbackend, sends the list of messages, and then closes the connection again.\n\nThe second approach is to use the ``open()`` and ``close()`` methods on the\nemail backend to manually control the connection. ``send_messages()`` will not\nmanually open or close the connection if it is already open, so if you\nmanually open the connection, you can control when it is closed. For example::\n\n    from django.core import mail\n    connection = mail.get_connection()\n\n    # Manually open the connection\n    connection.open()\n\n    # Construct an email message that uses the connection\n    email1 = mail.EmailMessage(\n        'Hello',\n        'Body goes here',\n        'from@example.com',\n        ['to1@example.com'],\n        connection=connection,\n    )\n    email1.send() # Send the email\n\n    # Construct two more messages\n    email2 = mail.EmailMessage(\n        'Hello',\n        'Body goes here',\n        'from@example.com',\n        ['to2@example.com'],\n    )\n    email3 = mail.EmailMessage(\n        'Hello',\n        'Body goes here',\n        'from@example.com',\n        ['to3@example.com'],\n    )\n\n    # Send the two emails in a single call -\n    connection.send_messages([email2, email3])\n    # The connection was already open so send_messages() doesn't close it.\n    # We need to manually close the connection.\n    connection.close()\n\n\nConfiguring email for development\n=================================\n\nThere are times when you do not want Django to send emails at\nall. For example, while developing a website, you probably don't want\nto send out thousands of emails -- but you may want to validate that\nemails will be sent to the right people under the right conditions,\nand that those emails will contain the correct content.\n\nThe easiest way to configure email for local development is to use the\n:ref:`console <topic-email-console-backend>` email backend. This backend\nredirects all email to stdout, allowing you to inspect the content of mail.\n\nThe :ref:`file <topic-email-file-backend>` email backend can also be useful\nduring development -- this backend dumps the contents of every SMTP connection\nto a file that can be inspected at your leisure.\n\nAnother approach is to use a \"dumb\" SMTP server that receives the emails\nlocally and displays them to the terminal, but does not actually send\nanything. Python has a built-in way to accomplish this with a single command::\n\n    python -m smtpd -n -c DebuggingServer localhost:1025\n\nThis command will start a minimal SMTP server listening on port 1025 of\nlocalhost. This server prints to standard output all email headers and the\nemail body. You then only need to set the :setting:`EMAIL_HOST` and\n:setting:`EMAIL_PORT` accordingly. For a more detailed discussion of SMTP\nserver options, see the Python documentation for the :mod:`smtpd` module.\n\nFor information about unit-testing the sending of emails in your application,\nsee the :ref:`topics-testing-email` section of the testing documentation.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":261,"nodeType":"TextFile","repoName":null,"name":"serialization.txt","path":"docs/topics","text":"==========================\nSerializing Django objects\n==========================\n\nDjango's serialization framework provides a mechanism for \"translating\" Django\nmodels into other formats. Usually these other formats will be text-based and\nused for sending Django data over a wire, but it's possible for a\nserializer to handle any format (text-based or not).\n\n.. seealso::\n\n    If you just want to get some data from your tables into a serialized\n    form, you could use the :djadmin:`dumpdata` management command.\n\nSerializing data\n================\n\nAt the highest level, you can serialize data like this::\n\n    from django.core import serializers\n    data = serializers.serialize(\"xml\", SomeModel.objects.all())\n\nThe arguments to the ``serialize`` function are the format to serialize the data\nto (see `Serialization formats`_) and a\n:class:`~django.db.models.query.QuerySet` to serialize. (Actually, the second\nargument can be any iterator that yields Django model instances, but it'll\nalmost always be a QuerySet).\n\n.. function:: django.core.serializers.get_serializer(format)\n\nYou can also use a serializer object directly::\n\n    XMLSerializer = serializers.get_serializer(\"xml\")\n    xml_serializer = XMLSerializer()\n    xml_serializer.serialize(queryset)\n    data = xml_serializer.getvalue()\n\nThis is useful if you want to serialize data directly to a file-like object\n(which includes an :class:`~django.http.HttpResponse`)::\n\n    with open(\"file.xml\", \"w\") as out:\n        xml_serializer.serialize(SomeModel.objects.all(), stream=out)\n\n.. note::\n\n    Calling :func:`~django.core.serializers.get_serializer` with an unknown\n    :ref:`format <serialization-formats>` will raise a\n    ``django.core.serializers.SerializerDoesNotExist`` exception.\n\n.. _subset-of-fields:\n\nSubset of fields\n----------------\n\nIf you only want a subset of fields to be serialized, you can\nspecify a ``fields`` argument to the serializer::\n\n    from django.core import serializers\n    data = serializers.serialize('xml', SomeModel.objects.all(), fields=('name','size'))\n\nIn this example, only the ``name`` and ``size`` attributes of each model will\nbe serialized. The primary key is always serialized as the ``pk`` element in the\nresulting output; it never appears in the ``fields`` part.\n\n.. note::\n\n    Depending on your model, you may find that it is not possible to\n    deserialize a model that only serializes a subset of its fields. If a\n    serialized object doesn't specify all the fields that are required by a\n    model, the deserializer will not be able to save deserialized instances.\n\nInherited models\n----------------\n\nIf you have a model that is defined using an :ref:`abstract base class\n<abstract-base-classes>`, you don't have to do anything special to serialize\nthat model. Call the serializer on the object (or objects) that you want to\nserialize, and the output will be a complete representation of the serialized\nobject.\n\nHowever, if you have a model that uses :ref:`multi-table inheritance\n<multi-table-inheritance>`, you also need to serialize all of the base classes\nfor the model. This is because only the fields that are locally defined on the\nmodel will be serialized. For example, consider the following models::\n\n    class Place(models.Model):\n        name = models.CharField(max_length=50)\n\n    class Restaurant(Place):\n        serves_hot_dogs = models.BooleanField(default=False)\n\nIf you only serialize the Restaurant model::\n\n    data = serializers.serialize('xml', Restaurant.objects.all())\n\nthe fields on the serialized output will only contain the ``serves_hot_dogs``\nattribute. The ``name`` attribute of the base class will be ignored.\n\nIn order to fully serialize your ``Restaurant`` instances, you will need to\nserialize the ``Place`` models as well::\n\n    all_objects = [*Restaurant.objects.all(), *Place.objects.all()]\n    data = serializers.serialize('xml', all_objects)\n\nDeserializing data\n==================\n\nDeserializing data is very similar to serializing it::\n\n    for obj in serializers.deserialize(\"xml\", data):\n        do_something_with(obj)\n\nAs you can see, the ``deserialize`` function takes the same format argument as\n``serialize``, a string or stream of data, and returns an iterator.\n\nHowever, here it gets slightly complicated. The objects returned by the\n``deserialize`` iterator *aren't* regular Django objects. Instead, they are\nspecial ``DeserializedObject`` instances that wrap a created -- but unsaved --\nobject and any associated relationship data.\n\nCalling ``DeserializedObject.save()`` saves the object to the database.\n\n.. note::\n\n    If the ``pk`` attribute in the serialized data doesn't exist or is\n    null, a new instance will be saved to the database.\n\nThis ensures that deserializing is a non-destructive operation even if the\ndata in your serialized representation doesn't match what's currently in the\ndatabase. Usually, working with these ``DeserializedObject`` instances looks\nsomething like::\n\n    for deserialized_object in serializers.deserialize(\"xml\", data):\n        if object_should_be_saved(deserialized_object):\n            deserialized_object.save()\n\nIn other words, the usual use is to examine the deserialized objects to make\nsure that they are \"appropriate\" for saving before doing so. If you trust your\ndata source you can instead save the object directly and move on.\n\nThe Django object itself can be inspected as ``deserialized_object.object``.\nIf fields in the serialized data do not exist on a model, a\n``DeserializationError`` will be raised unless the ``ignorenonexistent``\nargument is passed in as ``True``::\n\n    serializers.deserialize(\"xml\", data, ignorenonexistent=True)\n\n.. _serialization-formats:\n\nSerialization formats\n=====================\n\nDjango supports a number of serialization formats, some of which require you\nto install third-party Python modules:\n\n==========  ==============================================================\nIdentifier  Information\n==========  ==============================================================\n``xml``     Serializes to and from a simple XML dialect.\n\n``json``    Serializes to and from JSON_.\n\n``yaml``    Serializes to YAML (YAML Ain't a Markup Language). This\n            serializer is only available if PyYAML_ is installed.\n==========  ==============================================================\n\n.. _json: https://json.org/\n.. _PyYAML: https://pyyaml.org/\n\nXML\n---\n\nThe basic XML serialization format looks like this::\n\n    <?xml version=\"1.0\" encoding=\"utf-8\"?>\n    <django-objects version=\"1.0\">\n        <object pk=\"123\" model=\"sessions.session\">\n            <field type=\"DateTimeField\" name=\"expire_date\">2013-01-16T08:16:59.844560+00:00</field>\n            <!-- ... -->\n        </object>\n    </django-objects>\n\nThe whole collection of objects that is either serialized or deserialized is\nrepresented by a ``<django-objects>``-tag which contains multiple\n``<object>``-elements. Each such object has two attributes: \"pk\" and \"model\",\nthe latter being represented by the name of the app (\"sessions\") and the\nlowercase name of the model (\"session\") separated by a dot.\n\nEach field of the object is serialized as a ``<field>``-element sporting the\nfields \"type\" and \"name\". The text content of the element represents the value\nthat should be stored.\n\nForeign keys and other relational fields are treated a little bit differently::\n\n    <object pk=\"27\" model=\"auth.permission\">\n        <!-- ... -->\n        <field to=\"contenttypes.contenttype\" name=\"content_type\" rel=\"ManyToOneRel\">9</field>\n        <!-- ... -->\n    </object>\n\nIn this example we specify that the ``auth.Permission`` object with the PK 27\nhas a foreign key to the ``contenttypes.ContentType`` instance with the PK 9.\n\nManyToMany-relations are exported for the model that binds them. For instance,\nthe ``auth.User`` model has such a relation to the ``auth.Permission`` model::\n\n    <object pk=\"1\" model=\"auth.user\">\n        <!-- ... -->\n        <field to=\"auth.permission\" name=\"user_permissions\" rel=\"ManyToManyRel\">\n            <object pk=\"46\"></object>\n            <object pk=\"47\"></object>\n        </field>\n    </object>\n\nThis example links the given user with the permission models with PKs 46 and 47.\n\n.. admonition:: Control characters\n\n    If the content to be serialized contains control characters that are not\n    accepted in the XML 1.0 standard, the serialization will fail with a\n    :exc:`ValueError` exception. Read also the W3C's explanation of `HTML,\n    XHTML, XML and Control Codes\n    <https://www.w3.org/International/questions/qa-controls>`_.\n\n.. _serialization-formats-json:\n\nJSON\n----\n\nWhen staying with the same example data as before it would be serialized as\nJSON in the following way::\n\n    [\n        {\n            \"pk\": \"4b678b301dfd8a4e0dad910de3ae245b\",\n            \"model\": \"sessions.session\",\n            \"fields\": {\n                \"expire_date\": \"2013-01-16T08:16:59.844Z\",\n                ...\n            }\n        }\n    ]\n\nThe formatting here is a bit simpler than with XML. The whole collection\nis just represented as an array and the objects are represented by JSON objects\nwith three properties: \"pk\", \"model\" and \"fields\". \"fields\" is again an object\ncontaining each field's name and value as property and property-value\nrespectively.\n\nForeign keys have the PK of the linked object as property value.\nManyToMany-relations are serialized for the model that defines them and are\nrepresented as a list of PKs.\n\nBe aware that not all Django output can be passed unmodified to :mod:`json`.\nFor example, if you have some custom type in an object to be serialized, you'll\nhave to write a custom :mod:`json` encoder for it. Something like this will\nwork::\n\n    from django.core.serializers.json import DjangoJSONEncoder\n\n    class LazyEncoder(DjangoJSONEncoder):\n        def default(self, obj):\n            if isinstance(obj, YourCustomType):\n                return str(obj)\n            return super().default(obj)\n\nYou can then pass ``cls=LazyEncoder`` to the ``serializers.serialize()``\nfunction::\n\n    from django.core.serializers import serialize\n\n    serialize('json', SomeModel.objects.all(), cls=LazyEncoder)\n\nAlso note that GeoDjango provides a :doc:`customized GeoJSON serializer\n</ref/contrib/gis/serializers>`.\n\n.. versionchanged:: 3.1\n\n    All data is now dumped with Unicode. If you need the previous behavior,\n    pass ``ensure_ascii=True`` to the ``serializers.serialize()`` function.\n\n``DjangoJSONEncoder``\n~~~~~~~~~~~~~~~~~~~~~\n\n.. class:: django.core.serializers.json.DjangoJSONEncoder\n\nThe JSON serializer uses ``DjangoJSONEncoder`` for encoding. A subclass of\n:class:`~json.JSONEncoder`, it handles these additional types:\n\n:class:`~datetime.datetime`\n   A string of the form ``YYYY-MM-DDTHH:mm:ss.sssZ`` or\n   ``YYYY-MM-DDTHH:mm:ss.sss+HH:MM`` as defined in `ECMA-262`_.\n\n:class:`~datetime.date`\n   A string of the form ``YYYY-MM-DD`` as defined in `ECMA-262`_.\n\n:class:`~datetime.time`\n   A string of the form ``HH:MM:ss.sss`` as defined in `ECMA-262`_.\n\n:class:`~datetime.timedelta`\n   A string representing a duration as defined in ISO-8601. For example,\n   ``timedelta(days=1, hours=2, seconds=3.4)`` is represented as\n   ``'P1DT02H00M03.400000S'``.\n\n:class:`~decimal.Decimal`, ``Promise`` (``django.utils.functional.lazy()`` objects), :class:`~uuid.UUID`\n   A string representation of the object.\n\n.. _ecma-262: https://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15\n\nYAML\n----\n\nYAML serialization looks quite similar to JSON. The object list is serialized\nas a sequence mappings with the keys \"pk\", \"model\" and \"fields\". Each field is\nagain a mapping with the key being name of the field and the value the value::\n\n    -   fields: {expire_date: !!timestamp '2013-01-16 08:16:59.844560+00:00'}\n        model: sessions.session\n        pk: 4b678b301dfd8a4e0dad910de3ae245b\n\nReferential fields are again represented by the PK or sequence of PKs.\n\n.. versionchanged:: 3.1\n\n    All data is now dumped with Unicode. If you need the previous behavior,\n    pass ``allow_unicode=False`` to the ``serializers.serialize()`` function.\n\n.. _topics-serialization-natural-keys:\n\nNatural keys\n============\n\nThe default serialization strategy for foreign keys and many-to-many relations\nis to serialize the value of the primary key(s) of the objects in the relation.\nThis strategy works well for most objects, but it can cause difficulty in some\ncircumstances.\n\nConsider the case of a list of objects that have a foreign key referencing\n:class:`~django.contrib.contenttypes.models.ContentType`. If you're going to\nserialize an object that refers to a content type, then you need to have a way\nto refer to that content type to begin with. Since ``ContentType`` objects are\nautomatically created by Django during the database synchronization process,\nthe primary key of a given content type isn't easy to predict; it will\ndepend on how and when :djadmin:`migrate` was executed. This is true for all\nmodels which automatically generate objects, notably including\n:class:`~django.contrib.auth.models.Permission`,\n:class:`~django.contrib.auth.models.Group`, and\n:class:`~django.contrib.auth.models.User`.\n\n.. warning::\n\n    You should never include automatically generated objects in a fixture or\n    other serialized data. By chance, the primary keys in the fixture\n    may match those in the database and loading the fixture will\n    have no effect. In the more likely case that they don't match, the fixture\n    loading will fail with an :class:`~django.db.IntegrityError`.\n\nThere is also the matter of convenience. An integer id isn't always\nthe most convenient way to refer to an object; sometimes, a\nmore natural reference would be helpful.\n\nIt is for these reasons that Django provides *natural keys*. A natural\nkey is a tuple of values that can be used to uniquely identify an\nobject instance without using the primary key value.\n\nDeserialization of natural keys\n-------------------------------\n\nConsider the following two models::\n\n    from django.db import models\n\n    class Person(models.Model):\n        first_name = models.CharField(max_length=100)\n        last_name = models.CharField(max_length=100)\n\n        birthdate = models.DateField()\n\n        class Meta:\n            unique_together = [['first_name', 'last_name']]\n\n    class Book(models.Model):\n        name = models.CharField(max_length=100)\n        author = models.ForeignKey(Person, on_delete=models.CASCADE)\n\nOrdinarily, serialized data for ``Book`` would use an integer to refer to\nthe author. For example, in JSON, a Book might be serialized as::\n\n    ...\n    {\n        \"pk\": 1,\n        \"model\": \"store.book\",\n        \"fields\": {\n            \"name\": \"Mostly Harmless\",\n            \"author\": 42\n        }\n    }\n    ...\n\nThis isn't a particularly natural way to refer to an author. It\nrequires that you know the primary key value for the author; it also\nrequires that this primary key value is stable and predictable.\n\nHowever, if we add natural key handling to Person, the fixture becomes\nmuch more humane. To add natural key handling, you define a default\nManager for Person with a ``get_by_natural_key()`` method. In the case\nof a Person, a good natural key might be the pair of first and last\nname::\n\n    from django.db import models\n\n    class PersonManager(models.Manager):\n        def get_by_natural_key(self, first_name, last_name):\n            return self.get(first_name=first_name, last_name=last_name)\n\n    class Person(models.Model):\n        first_name = models.CharField(max_length=100)\n        last_name = models.CharField(max_length=100)\n        birthdate = models.DateField()\n\n        objects = PersonManager()\n\n        class Meta:\n            unique_together = [['first_name', 'last_name']]\n\nNow books can use that natural key to refer to ``Person`` objects::\n\n    ...\n    {\n        \"pk\": 1,\n        \"model\": \"store.book\",\n        \"fields\": {\n            \"name\": \"Mostly Harmless\",\n            \"author\": [\"Douglas\", \"Adams\"]\n        }\n    }\n    ...\n\nWhen you try to load this serialized data, Django will use the\n``get_by_natural_key()`` method to resolve ``[\"Douglas\", \"Adams\"]``\ninto the primary key of an actual ``Person`` object.\n\n.. note::\n\n    Whatever fields you use for a natural key must be able to uniquely\n    identify an object. This will usually mean that your model will\n    have a uniqueness clause (either unique=True on a single field, or\n    ``unique_together`` over multiple fields) for the field or fields\n    in your natural key. However, uniqueness doesn't need to be\n    enforced at the database level. If you are certain that a set of\n    fields will be effectively unique, you can still use those fields\n    as a natural key.\n\nDeserialization of objects with no primary key will always check whether the\nmodel's manager has a ``get_by_natural_key()`` method and if so, use it to\npopulate the deserialized object's primary key.\n\nSerialization of natural keys\n-----------------------------\n\nSo how do you get Django to emit a natural key when serializing an object?\nFirstly, you need to add another method -- this time to the model itself::\n\n    class Person(models.Model):\n        first_name = models.CharField(max_length=100)\n        last_name = models.CharField(max_length=100)\n        birthdate = models.DateField()\n\n        objects = PersonManager()\n\n        class Meta:\n            unique_together = [['first_name', 'last_name']]\n\n        def natural_key(self):\n            return (self.first_name, self.last_name)\n\nThat method should always return a natural key tuple -- in this\nexample, ``(first name, last name)``. Then, when you call\n``serializers.serialize()``, you provide ``use_natural_foreign_keys=True``\nor ``use_natural_primary_keys=True`` arguments::\n\n    >>> serializers.serialize('json', [book1, book2], indent=2,\n    ...      use_natural_foreign_keys=True, use_natural_primary_keys=True)\n\nWhen ``use_natural_foreign_keys=True`` is specified, Django will use the\n``natural_key()`` method to serialize any foreign key reference to objects\nof the type that defines the method.\n\nWhen ``use_natural_primary_keys=True`` is specified, Django will not provide the\nprimary key in the serialized data of this object since it can be calculated\nduring deserialization::\n\n    ...\n    {\n        \"model\": \"store.person\",\n        \"fields\": {\n            \"first_name\": \"Douglas\",\n            \"last_name\": \"Adams\",\n            \"birth_date\": \"1952-03-11\",\n        }\n    }\n    ...\n\nThis can be useful when you need to load serialized data into an existing\ndatabase and you cannot guarantee that the serialized primary key value is not\nalready in use, and do not need to ensure that deserialized objects retain the\nsame primary keys.\n\nIf you are using :djadmin:`dumpdata` to generate serialized data, use the\n:option:`dumpdata --natural-foreign` and :option:`dumpdata --natural-primary`\ncommand line flags to generate natural keys.\n\n.. note::\n\n    You don't need to define both ``natural_key()`` and\n    ``get_by_natural_key()``. If you don't want Django to output\n    natural keys during serialization, but you want to retain the\n    ability to load natural keys, then you can opt to not implement\n    the ``natural_key()`` method.\n\n    Conversely, if (for some strange reason) you want Django to output\n    natural keys during serialization, but *not* be able to load those\n    key values, just don't define the ``get_by_natural_key()`` method.\n\n.. _natural-keys-and-forward-references:\n\nNatural keys and forward references\n-----------------------------------\n\nSometimes when you use :ref:`natural foreign keys\n<topics-serialization-natural-keys>` you'll need to deserialize data where\nan object has a foreign key referencing another object that hasn't yet been\ndeserialized. This is called a \"forward reference\".\n\nFor instance, suppose you have the following objects in your fixture::\n\n    ...\n    {\n        \"model\": \"store.book\",\n        \"fields\": {\n            \"name\": \"Mostly Harmless\",\n            \"author\": [\"Douglas\", \"Adams\"]\n        }\n    },\n    ...\n    {\n        \"model\": \"store.person\",\n        \"fields\": {\n            \"first_name\": \"Douglas\",\n            \"last_name\": \"Adams\"\n        }\n    },\n    ...\n\nIn order to handle this situation, you need to pass\n``handle_forward_references=True`` to ``serializers.deserialize()``. This will\nset the ``deferred_fields`` attribute on the ``DeserializedObject`` instances.\nYou'll need to keep track of ``DeserializedObject`` instances where this\nattribute isn't ``None`` and later call ``save_deferred_fields()`` on them.\n\nTypical usage looks like this::\n\n    objs_with_deferred_fields = []\n\n    for obj in serializers.deserialize('xml', data, handle_forward_references=True):\n        obj.save()\n        if obj.deferred_fields is not None:\n            objs_with_deferred_fields.append(obj)\n\n    for obj in objs_with_deferred_fields:\n        obj.save_deferred_fields()\n\nFor this to work, the ``ForeignKey`` on the referencing model must have\n``null=True``.\n\nDependencies during serialization\n---------------------------------\n\nIt's often possible to avoid explicitly having to handle forward references by\ntaking care with the ordering of objects within a fixture.\n\nTo help with this, calls to :djadmin:`dumpdata` that use the :option:`dumpdata\n--natural-foreign` option will serialize any model with a ``natural_key()``\nmethod before serializing standard primary key objects.\n\nHowever, this may not always be enough. If your natural key refers to\nanother object (by using a foreign key or natural key to another object\nas part of a natural key), then you need to be able to ensure that\nthe objects on which a natural key depends occur in the serialized data\nbefore the natural key requires them.\n\nTo control this ordering, you can define dependencies on your\n``natural_key()`` methods. You do this by setting a ``dependencies``\nattribute on the ``natural_key()`` method itself.\n\nFor example, let's add a natural key to the ``Book`` model from the\nexample above::\n\n    class Book(models.Model):\n        name = models.CharField(max_length=100)\n        author = models.ForeignKey(Person, on_delete=models.CASCADE)\n\n        def natural_key(self):\n            return (self.name,) + self.author.natural_key()\n\nThe natural key for a ``Book`` is a combination of its name and its\nauthor. This means that ``Person`` must be serialized before ``Book``.\nTo define this dependency, we add one extra line::\n\n        def natural_key(self):\n            return (self.name,) + self.author.natural_key()\n        natural_key.dependencies = ['example_app.person']\n\nThis definition ensures that all ``Person`` objects are serialized before\nany ``Book`` objects. In turn, any object referencing ``Book`` will be\nserialized after both ``Person`` and ``Book`` have been serialized.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":262,"nodeType":"Package","repoName":null,"name":"docs/topics/db","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":263,"nodeType":"TextFile","repoName":null,"name":"tablespaces.txt","path":"docs/topics/db","text":"===========\nTablespaces\n===========\n\nA common paradigm for optimizing performance in database systems is the use of\n`tablespaces`_ to organize disk layout.\n\n.. _`tablespaces`: https://en.wikipedia.org/wiki/Tablespace\n\n.. warning::\n    Django does not create the tablespaces for you. Please refer to your\n    database engine's documentation for details on creating and managing\n    tablespaces.\n\n\nDeclaring tablespaces for tables\n================================\n\nA tablespace can be specified for the table generated by a model by supplying\nthe :attr:`~django.db.models.Options.db_tablespace` option inside the model's\n``class Meta``. This option also affects tables automatically created for\n:class:`~django.db.models.ManyToManyField`\\ s in the model.\n\nYou can use the :setting:`DEFAULT_TABLESPACE` setting to specify a default value\nfor :attr:`~django.db.models.Options.db_tablespace`. This is useful for setting\na tablespace for the built-in Django apps and other applications whose code you\ncannot control.\n\nDeclaring tablespaces for indexes\n=================================\n\nYou can pass the :attr:`~django.db.models.Index.db_tablespace` option to an\n``Index`` constructor to specify the name of a tablespace to use for the index.\nFor single field indexes, you can pass the\n:attr:`~django.db.models.Field.db_tablespace` option to a ``Field`` constructor\nto specify an alternate tablespace for the field's column index. If the column\ndoesn't have an index, the option is ignored.\n\nYou can use the :setting:`DEFAULT_INDEX_TABLESPACE` setting to specify\na default value for :attr:`~django.db.models.Field.db_tablespace`.\n\nIf :attr:`~django.db.models.Field.db_tablespace` isn't specified and you didn't\nset :setting:`DEFAULT_INDEX_TABLESPACE`, the index is created in the same\ntablespace as the tables.\n\nAn example\n==========\n\n.. code-block:: python\n\n    class TablespaceExample(models.Model):\n        name = models.CharField(max_length=30, db_index=True, db_tablespace=\"indexes\")\n        data = models.CharField(max_length=255, db_index=True)\n        shortcut = models.CharField(max_length=7)\n        edges = models.ManyToManyField(to=\"self\", db_tablespace=\"indexes\")\n\n        class Meta:\n            db_tablespace = \"tables\"\n            indexes = [models.Index(fields=['shortcut'], db_tablespace='other_indexes')]\n\nIn this example, the tables generated by the ``TablespaceExample`` model (i.e.\nthe model table and the many-to-many table) would be stored in the ``tables``\ntablespace. The index for the name field and the indexes on the many-to-many\ntable would be stored in the ``indexes`` tablespace. The ``data`` field would\nalso generate an index, but no tablespace for it is specified, so it would be\nstored in the model tablespace ``tables`` by default. The index for the\n``shortcut`` field would be stored in the ``other_indexes`` tablespace.\n\nDatabase support\n================\n\nPostgreSQL and Oracle support tablespaces. SQLite, MariaDB and MySQL don't.\n\nWhen you use a backend that lacks support for tablespaces, Django ignores all\ntablespace-related options.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":264,"nodeType":"TextFile","repoName":null,"name":"instrumentation.txt","path":"docs/topics/db","text":"========================\nDatabase instrumentation\n========================\n\nTo help you understand and control the queries issued by your code, Django\nprovides a hook for installing wrapper functions around the execution of\ndatabase queries. For example, wrappers can count queries, measure query\nduration, log queries, or even prevent query execution (e.g. to make sure that\nno queries are issued while rendering a template with prefetched data).\n\nThe wrappers are modeled after :doc:`middleware </topics/http/middleware>` --\nthey are callables which take another callable as one of their arguments. They\ncall that callable to invoke the (possibly wrapped) database query, and they\ncan do what they want around that call. They are, however, created and\ninstalled by user code, and so don't need a separate factory like middleware do.\n\nInstalling a wrapper is done in a context manager -- so the wrappers are\ntemporary and specific to some flow in your code.\n\nAs mentioned above, an example of a wrapper is a query execution blocker. It\ncould look like this::\n\n    def blocker(*args):\n        raise Exception('No database access allowed here.')\n\nAnd it would be used in a view to block queries from the template like so::\n\n    from django.db import connection\n    from django.shortcuts import render\n\n    def my_view(request):\n        context = {...}  # Code to generate context with all data.\n        template_name = ...\n        with connection.execute_wrapper(blocker):\n            return render(request, template_name, context)\n\nThe parameters sent to the wrappers are:\n\n* ``execute`` -- a callable, which should be invoked with the rest of the\n  parameters in order to execute the query.\n\n* ``sql`` -- a ``str``, the SQL query to be sent to the database.\n\n* ``params`` -- a list/tuple of parameter values for the SQL command, or a\n  list/tuple of lists/tuples if the wrapped call is ``executemany()``.\n\n* ``many`` -- a ``bool`` indicating whether the ultimately invoked call is\n  ``execute()`` or ``executemany()`` (and whether ``params`` is expected to be\n  a sequence of values, or a sequence of sequences of values).\n\n* ``context`` -- a dictionary with further data about the context of\n  invocation. This includes the connection and cursor.\n\nUsing the parameters, a slightly more complex version of the blocker could\ninclude the connection name in the error message::\n\n    def blocker(execute, sql, params, many, context):\n        alias = context['connection'].alias\n        raise Exception(\"Access to database '{}' blocked here\".format(alias))\n\nFor a more complete example, a query logger could look like this::\n\n    import time\n\n    class QueryLogger:\n\n        def __init__(self):\n            self.queries = []\n\n        def __call__(self, execute, sql, params, many, context):\n            current_query = {'sql': sql, 'params': params, 'many': many}\n            start = time.monotonic()\n            try:\n                result = execute(sql, params, many, context)\n            except Exception as e:\n                current_query['status'] = 'error'\n                current_query['exception'] = e\n                raise\n            else:\n                current_query['status'] = 'ok'\n                return result\n            finally:\n                duration = time.monotonic() - start\n                current_query['duration'] = duration\n                self.queries.append(current_query)\n\nTo use this, you would create a logger object and install it as a wrapper::\n\n    from django.db import connection\n\n    ql = QueryLogger()\n    with connection.execute_wrapper(ql):\n        do_queries()\n    # Now we can print the log.\n    print(ql.queries)\n\n.. currentmodule:: django.db.backends.base.DatabaseWrapper\n\n``connection.execute_wrapper()``\n--------------------------------\n\n.. method:: execute_wrapper(wrapper)\n\nReturns a context manager which, when entered, installs a wrapper around\ndatabase query executions, and when exited, removes the wrapper. The wrapper is\ninstalled on the thread-local connection object.\n\n``wrapper`` is a callable taking five arguments.  It is called for every query\nexecution in the scope of the context manager, with arguments ``execute``,\n``sql``, ``params``, ``many``, and ``context`` as described above. It's\nexpected to call ``execute(sql, params, many, context)`` and return the return\nvalue of that call.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":265,"nodeType":"TextFile","repoName":null,"name":"cache.txt","path":"docs/topics","text":"========================\nDjango's cache framework\n========================\n\nA fundamental trade-off in dynamic websites is, well, they're dynamic. Each\ntime a user requests a page, the Web server makes all sorts of calculations --\nfrom database queries to template rendering to business logic -- to create the\npage that your site's visitor sees. This is a lot more expensive, from a\nprocessing-overhead perspective, than your standard\nread-a-file-off-the-filesystem server arrangement.\n\nFor most Web applications, this overhead isn't a big deal. Most Web\napplications aren't ``washingtonpost.com`` or ``slashdot.org``; they're small-\nto medium-sized sites with so-so traffic. But for medium- to high-traffic\nsites, it's essential to cut as much overhead as possible.\n\nThat's where caching comes in.\n\nTo cache something is to save the result of an expensive calculation so that\nyou don't have to perform the calculation next time. Here's some pseudocode\nexplaining how this would work for a dynamically generated Web page::\n\n    given a URL, try finding that page in the cache\n    if the page is in the cache:\n        return the cached page\n    else:\n        generate the page\n        save the generated page in the cache (for next time)\n        return the generated page\n\nDjango comes with a robust cache system that lets you save dynamic pages so\nthey don't have to be calculated for each request. For convenience, Django\noffers different levels of cache granularity: You can cache the output of\nspecific views, you can cache only the pieces that are difficult to produce,\nor you can cache your entire site.\n\nDjango also works well with \"downstream\" caches, such as `Squid\n<http://www.squid-cache.org>`_ and browser-based caches. These are the types of\ncaches that you don't directly control but to which you can provide hints (via\nHTTP headers) about which parts of your site should be cached, and how.\n\n.. seealso::\n    The :ref:`Cache Framework design philosophy <cache-design-philosophy>`\n    explains a few of the design decisions of the framework.\n\n.. _setting-up-the-cache:\n\nSetting up the cache\n====================\n\nThe cache system requires a small amount of setup. Namely, you have to tell it\nwhere your cached data should live -- whether in a database, on the filesystem\nor directly in memory. This is an important decision that affects your cache's\nperformance; yes, some cache types are faster than others.\n\nYour cache preference goes in the :setting:`CACHES` setting in your\nsettings file. Here's an explanation of all available values for\n:setting:`CACHES`.\n\n.. _memcached:\n\nMemcached\n---------\n\nThe fastest, most efficient type of cache supported natively by Django,\nMemcached__ is an entirely memory-based cache server, originally developed\nto handle high loads at LiveJournal.com and subsequently open-sourced by\nDanga Interactive. It is used by sites such as Facebook and Wikipedia to\nreduce database access and dramatically increase site performance.\n\n__ https://memcached.org/\n\nMemcached runs as a daemon and is allotted a specified amount of RAM. All it\ndoes is provide a fast interface for adding, retrieving and deleting data in\nthe cache. All data is stored directly in memory, so there's no overhead of\ndatabase or filesystem usage.\n\nAfter installing Memcached itself, you'll need to install a Memcached\nbinding. There are several Python Memcached bindings available; the\ntwo most common are `python-memcached`_ and `pylibmc`_.\n\n.. _`python-memcached`: https://pypi.org/project/python-memcached/\n.. _`pylibmc`: https://pypi.org/project/pylibmc/\n\nTo use Memcached with Django:\n\n* Set :setting:`BACKEND <CACHES-BACKEND>` to\n  ``django.core.cache.backends.memcached.MemcachedCache`` or\n  ``django.core.cache.backends.memcached.PyLibMCCache`` (depending\n  on your chosen memcached binding)\n\n* Set :setting:`LOCATION <CACHES-LOCATION>` to ``ip:port`` values,\n  where ``ip`` is the IP address of the Memcached daemon and ``port`` is the\n  port on which Memcached is running, or to a ``unix:path`` value, where\n  ``path`` is the path to a Memcached Unix socket file.\n\nIn this example, Memcached is running on localhost (127.0.0.1) port 11211, using\nthe ``python-memcached`` binding::\n\n    CACHES = {\n        'default': {\n            'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',\n            'LOCATION': '127.0.0.1:11211',\n        }\n    }\n\nIn this example, Memcached is available through a local Unix socket file\n:file:`/tmp/memcached.sock` using the ``python-memcached`` binding::\n\n    CACHES = {\n        'default': {\n            'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',\n            'LOCATION': 'unix:/tmp/memcached.sock',\n        }\n    }\n\nWhen using the ``pylibmc`` binding, do not include the ``unix:/`` prefix::\n\n    CACHES = {\n        'default': {\n            'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',\n            'LOCATION': '/tmp/memcached.sock',\n        }\n    }\n\nOne excellent feature of Memcached is its ability to share a cache over\nmultiple servers. This means you can run Memcached daemons on multiple\nmachines, and the program will treat the group of machines as a *single*\ncache, without the need to duplicate cache values on each machine. To take\nadvantage of this feature, include all server addresses in\n:setting:`LOCATION <CACHES-LOCATION>`, either as a semicolon or comma\ndelimited string, or as a list.\n\nIn this example, the cache is shared over Memcached instances running on IP\naddress 172.19.26.240 and 172.19.26.242, both on port 11211::\n\n    CACHES = {\n        'default': {\n            'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',\n            'LOCATION': [\n                '172.19.26.240:11211',\n                '172.19.26.242:11211',\n            ]\n        }\n    }\n\nIn the following example, the cache is shared over Memcached instances running\non the IP addresses 172.19.26.240 (port 11211), 172.19.26.242 (port 11212), and\n172.19.26.244 (port 11213)::\n\n    CACHES = {\n        'default': {\n            'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',\n            'LOCATION': [\n                '172.19.26.240:11211',\n                '172.19.26.242:11212',\n                '172.19.26.244:11213',\n            ]\n        }\n    }\n\nA final point about Memcached is that memory-based caching has a\ndisadvantage: because the cached data is stored in memory, the data will be\nlost if your server crashes. Clearly, memory isn't intended for permanent data\nstorage, so don't rely on memory-based caching as your only data storage.\nWithout a doubt, *none* of the Django caching backends should be used for\npermanent storage -- they're all intended to be solutions for caching, not\nstorage -- but we point this out here because memory-based caching is\nparticularly temporary.\n\n.. _database-caching:\n\nDatabase caching\n----------------\n\nDjango can store its cached data in your database. This works best if you've\ngot a fast, well-indexed database server.\n\nTo use a database table as your cache backend:\n\n* Set :setting:`BACKEND <CACHES-BACKEND>` to\n  ``django.core.cache.backends.db.DatabaseCache``\n\n* Set :setting:`LOCATION <CACHES-LOCATION>` to ``tablename``, the name of the\n  database table. This name can be whatever you want, as long as it's a valid\n  table name that's not already being used in your database.\n\nIn this example, the cache table's name is ``my_cache_table``::\n\n    CACHES = {\n        'default': {\n            'BACKEND': 'django.core.cache.backends.db.DatabaseCache',\n            'LOCATION': 'my_cache_table',\n        }\n    }\n\nCreating the cache table\n~~~~~~~~~~~~~~~~~~~~~~~~\n\nBefore using the database cache, you must create the cache table with this\ncommand::\n\n    python manage.py createcachetable\n\nThis creates a table in your database that is in the proper format that\nDjango's database-cache system expects. The name of the table is taken from\n:setting:`LOCATION <CACHES-LOCATION>`.\n\nIf you are using multiple database caches, :djadmin:`createcachetable` creates\none table for each cache.\n\nIf you are using multiple databases, :djadmin:`createcachetable` observes the\n``allow_migrate()`` method of your database routers (see below).\n\nLike :djadmin:`migrate`, :djadmin:`createcachetable` won't touch an existing\ntable. It will only create missing tables.\n\nTo print the SQL that would be run, rather than run it, use the\n:option:`createcachetable --dry-run` option.\n\nMultiple databases\n~~~~~~~~~~~~~~~~~~\n\nIf you use database caching with multiple databases, you'll also need\nto set up routing instructions for your database cache table. For the\npurposes of routing, the database cache table appears as a model named\n``CacheEntry``, in an application named ``django_cache``. This model\nwon't appear in the models cache, but the model details can be used\nfor routing purposes.\n\nFor example, the following router would direct all cache read\noperations to ``cache_replica``, and all write operations to\n``cache_primary``. The cache table will only be synchronized onto\n``cache_primary``::\n\n    class CacheRouter:\n        \"\"\"A router to control all database cache operations\"\"\"\n\n        def db_for_read(self, model, **hints):\n            \"All cache read operations go to the replica\"\n            if model._meta.app_label == 'django_cache':\n                return 'cache_replica'\n            return None\n\n        def db_for_write(self, model, **hints):\n            \"All cache write operations go to primary\"\n            if model._meta.app_label == 'django_cache':\n                return 'cache_primary'\n            return None\n\n        def allow_migrate(self, db, app_label, model_name=None, **hints):\n            \"Only install the cache model on primary\"\n            if app_label == 'django_cache':\n                return db == 'cache_primary'\n            return None\n\nIf you don't specify routing directions for the database cache model,\nthe cache backend will use the ``default`` database.\n\nAnd if you don't use the database cache backend, you don't need to worry about\nproviding routing instructions for the database cache model.\n\nFilesystem caching\n------------------\n\nThe file-based backend serializes and stores each cache value as a separate\nfile. To use this backend set :setting:`BACKEND <CACHES-BACKEND>` to\n``\"django.core.cache.backends.filebased.FileBasedCache\"`` and\n:setting:`LOCATION <CACHES-LOCATION>` to a suitable directory. For example,\nto store cached data in ``/var/tmp/django_cache``, use this setting::\n\n    CACHES = {\n        'default': {\n            'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',\n            'LOCATION': '/var/tmp/django_cache',\n        }\n    }\n\nIf you're on Windows, put the drive letter at the beginning of the path,\nlike this::\n\n    CACHES = {\n        'default': {\n            'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',\n            'LOCATION': 'c:/foo/bar',\n        }\n    }\n\nThe directory path should be absolute -- that is, it should start at the root\nof your filesystem. It doesn't matter whether you put a slash at the end of the\nsetting.\n\nMake sure the directory pointed-to by this setting exists and is readable and\nwritable by the system user under which your Web server runs. Continuing the\nabove example, if your server runs as the user ``apache``, make sure the\ndirectory ``/var/tmp/django_cache`` exists and is readable and writable by the\nuser ``apache``.\n\n.. _local-memory-caching:\n\nLocal-memory caching\n--------------------\n\nThis is the default cache if another is not specified in your settings file. If\nyou want the speed advantages of in-memory caching but don't have the capability\nof running Memcached, consider the local-memory cache backend. This cache is\nper-process (see below) and thread-safe. To use it, set :setting:`BACKEND\n<CACHES-BACKEND>` to ``\"django.core.cache.backends.locmem.LocMemCache\"``. For\nexample::\n\n    CACHES = {\n        'default': {\n            'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',\n            'LOCATION': 'unique-snowflake',\n        }\n    }\n\nThe cache :setting:`LOCATION <CACHES-LOCATION>` is used to identify individual\nmemory stores. If you only have one ``locmem`` cache, you can omit the\n:setting:`LOCATION <CACHES-LOCATION>`; however, if you have more than one local\nmemory cache, you will need to assign a name to at least one of them in\norder to keep them separate.\n\nThe cache uses a least-recently-used (LRU) culling strategy.\n\nNote that each process will have its own private cache instance, which means no\ncross-process caching is possible. This also means the local memory cache isn't\nparticularly memory-efficient, so it's probably not a good choice for\nproduction environments. It's nice for development.\n\nDummy caching (for development)\n-------------------------------\n\nFinally, Django comes with a \"dummy\" cache that doesn't actually cache -- it\njust implements the cache interface without doing anything.\n\nThis is useful if you have a production site that uses heavy-duty caching in\nvarious places but a development/test environment where you don't want to cache\nand don't want to have to change your code to special-case the latter. To\nactivate dummy caching, set :setting:`BACKEND <CACHES-BACKEND>` like so::\n\n    CACHES = {\n        'default': {\n            'BACKEND': 'django.core.cache.backends.dummy.DummyCache',\n        }\n    }\n\nUsing a custom cache backend\n----------------------------\n\nWhile Django includes support for a number of cache backends out-of-the-box,\nsometimes you might want to use a customized cache backend. To use an external\ncache backend with Django, use the Python import path as the\n:setting:`BACKEND <CACHES-BACKEND>` of the :setting:`CACHES` setting, like so::\n\n    CACHES = {\n        'default': {\n            'BACKEND': 'path.to.backend',\n        }\n    }\n\nIf you're building your own backend, you can use the standard cache backends\nas reference implementations. You'll find the code in the\n``django/core/cache/backends/`` directory of the Django source.\n\nNote: Without a really compelling reason, such as a host that doesn't support\nthem, you should stick to the cache backends included with Django. They've\nbeen well-tested and are well-documented.\n\n.. _cache_arguments:\n\nCache arguments\n---------------\n\nEach cache backend can be given additional arguments to control caching\nbehavior. These arguments are provided as additional keys in the\n:setting:`CACHES` setting. Valid arguments are as follows:\n\n* :setting:`TIMEOUT <CACHES-TIMEOUT>`: The default timeout, in\n  seconds, to use for the cache. This argument defaults to ``300`` seconds (5 minutes).\n  You can set ``TIMEOUT`` to ``None`` so that, by default, cache keys never\n  expire. A value of ``0`` causes keys to immediately expire (effectively\n  \"don't cache\").\n\n* :setting:`OPTIONS <CACHES-OPTIONS>`: Any options that should be\n  passed to the cache backend. The list of valid options will vary\n  with each backend, and cache backends backed by a third-party library\n  will pass their options directly to the underlying cache library.\n\n  Cache backends that implement their own culling strategy (i.e.,\n  the ``locmem``, ``filesystem`` and ``database`` backends) will\n  honor the following options:\n\n  * ``MAX_ENTRIES``: The maximum number of entries allowed in\n    the cache before old values are deleted. This argument\n    defaults to ``300``.\n\n  * ``CULL_FREQUENCY``: The fraction of entries that are culled\n    when ``MAX_ENTRIES`` is reached. The actual ratio is\n    ``1 / CULL_FREQUENCY``, so set ``CULL_FREQUENCY`` to ``2`` to\n    cull half the entries when ``MAX_ENTRIES`` is reached. This argument\n    should be an integer and defaults to ``3``.\n\n    A value of ``0`` for ``CULL_FREQUENCY`` means that the\n    entire cache will be dumped when ``MAX_ENTRIES`` is reached.\n    On some backends (``database`` in particular) this makes culling *much*\n    faster at the expense of more cache misses.\n\n  Memcached backends pass the contents of :setting:`OPTIONS <CACHES-OPTIONS>`\n  as keyword arguments to the client constructors, allowing for more advanced\n  control of client behavior. For example usage, see below.\n\n* :setting:`KEY_PREFIX <CACHES-KEY_PREFIX>`: A string that will be\n  automatically included (prepended by default) to all cache keys\n  used by the Django server.\n\n  See the :ref:`cache documentation <cache_key_prefixing>` for\n  more information.\n\n* :setting:`VERSION <CACHES-VERSION>`: The default version number\n  for cache keys generated by the Django server.\n\n  See the :ref:`cache documentation <cache_versioning>` for more\n  information.\n\n* :setting:`KEY_FUNCTION <CACHES-KEY_FUNCTION>`\n  A string containing a dotted path to a function that defines how\n  to compose a prefix, version and key into a final cache key.\n\n  See the :ref:`cache documentation <cache_key_transformation>`\n  for more information.\n\nIn this example, a filesystem backend is being configured with a timeout\nof 60 seconds, and a maximum capacity of 1000 items::\n\n    CACHES = {\n        'default': {\n            'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',\n            'LOCATION': '/var/tmp/django_cache',\n            'TIMEOUT': 60,\n            'OPTIONS': {\n                'MAX_ENTRIES': 1000\n            }\n        }\n    }\n\nHere's an example configuration for a ``python-memcached`` based backend with\nan object size limit of 2MB::\n\n    CACHES = {\n        'default': {\n            'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',\n            'LOCATION': '127.0.0.1:11211',\n            'OPTIONS': {\n                'server_max_value_length': 1024 * 1024 * 2,\n            }\n        }\n    }\n\nHere's an example configuration for a ``pylibmc`` based backend that enables\nthe binary protocol, SASL authentication, and the ``ketama`` behavior mode::\n\n    CACHES = {\n        'default': {\n            'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',\n            'LOCATION': '127.0.0.1:11211',\n            'OPTIONS': {\n                'binary': True,\n                'username': 'user',\n                'password': 'pass',\n                'behaviors': {\n                    'ketama': True,\n                }\n            }\n        }\n    }\n\n.. _the-per-site-cache:\n\nThe per-site cache\n==================\n\nOnce the cache is set up, the simplest way to use caching is to cache your\nentire site. You'll need to add\n``'django.middleware.cache.UpdateCacheMiddleware'`` and\n``'django.middleware.cache.FetchFromCacheMiddleware'`` to your\n:setting:`MIDDLEWARE` setting, as in this example::\n\n    MIDDLEWARE = [\n        'django.middleware.cache.UpdateCacheMiddleware',\n        'django.middleware.common.CommonMiddleware',\n        'django.middleware.cache.FetchFromCacheMiddleware',\n    ]\n\n.. note::\n\n    No, that's not a typo: the \"update\" middleware must be first in the list,\n    and the \"fetch\" middleware must be last. The details are a bit obscure, but\n    see `Order of MIDDLEWARE`_ below if you'd like the full story.\n\nThen, add the following required settings to your Django settings file:\n\n* :setting:`CACHE_MIDDLEWARE_ALIAS` -- The cache alias to use for storage.\n* :setting:`CACHE_MIDDLEWARE_SECONDS` -- The number of seconds each page should\n  be cached.\n* :setting:`CACHE_MIDDLEWARE_KEY_PREFIX` -- If the cache is shared across\n  multiple sites using the same Django installation, set this to the name of\n  the site, or some other string that is unique to this Django instance, to\n  prevent key collisions. Use an empty string if you don't care.\n\n``FetchFromCacheMiddleware`` caches GET and HEAD responses with status 200,\nwhere the request and response headers allow. Responses to requests for the same\nURL with different query parameters are considered to be unique pages and are\ncached separately. This middleware expects that a HEAD request is answered with\nthe same response headers as the corresponding GET request; in which case it can\nreturn a cached GET response for HEAD request.\n\nAdditionally, ``UpdateCacheMiddleware`` automatically sets a few headers in each\n:class:`~django.http.HttpResponse`:\n\n* Sets the ``Expires`` header to the current date/time plus the defined\n  :setting:`CACHE_MIDDLEWARE_SECONDS`.\n\n* Sets the ``Cache-Control`` header to give a max age for the page --\n  again, from the :setting:`CACHE_MIDDLEWARE_SECONDS` setting.\n\nSee :doc:`/topics/http/middleware` for more on middleware.\n\nIf a view sets its own cache expiry time (i.e. it has a ``max-age`` section in\nits ``Cache-Control`` header) then the page will be cached until the expiry\ntime, rather than :setting:`CACHE_MIDDLEWARE_SECONDS`. Using the decorators in\n``django.views.decorators.cache`` you can easily set a view's expiry time\n(using the :func:`~django.views.decorators.cache.cache_control` decorator) or\ndisable caching for a view (using the\n:func:`~django.views.decorators.cache.never_cache` decorator). See the\n`using other headers`__ section for more on these decorators.\n\n.. _i18n-cache-key:\n\nIf :setting:`USE_I18N` is set to ``True`` then the generated cache key will\ninclude the name of the active :term:`language<language code>` -- see also\n:ref:`how-django-discovers-language-preference`). This allows you to easily\ncache multilingual sites without having to create the cache key yourself.\n\nCache keys also include the active :term:`language <language code>` when\n:setting:`USE_L10N` is set to ``True`` and the :ref:`current time zone\n<default-current-time-zone>` when :setting:`USE_TZ` is set to ``True``.\n\n__ `Controlling cache: Using other headers`_\n\nThe per-view cache\n==================\n\n.. function:: django.views.decorators.cache.cache_page\n\nA more granular way to use the caching framework is by caching the output of\nindividual views. ``django.views.decorators.cache`` defines a ``cache_page``\ndecorator that will automatically cache the view's response for you::\n\n    from django.views.decorators.cache import cache_page\n\n    @cache_page(60 * 15)\n    def my_view(request):\n        ...\n\n``cache_page`` takes a single argument: the cache timeout, in seconds. In the\nabove example, the result of the ``my_view()`` view will be cached for 15\nminutes. (Note that we've written it as ``60 * 15`` for the purpose of\nreadability. ``60 * 15`` will be evaluated to ``900`` -- that is, 15 minutes\nmultiplied by 60 seconds per minute.)\n\nThe cache timeout set by ``cache_page`` takes precedence over the ``max-age``\ndirective from the ``Cache-Control`` header.\n\nThe per-view cache, like the per-site cache, is keyed off of the URL. If\nmultiple URLs point at the same view, each URL will be cached separately.\nContinuing the ``my_view`` example, if your URLconf looks like this::\n\n    urlpatterns = [\n        path('foo/<int:code>/', my_view),\n    ]\n\nthen requests to ``/foo/1/`` and ``/foo/23/`` will be cached separately, as\nyou may expect. But once a particular URL (e.g., ``/foo/23/``) has been\nrequested, subsequent requests to that URL will use the cache.\n\n``cache_page`` can also take an optional keyword argument, ``cache``,\nwhich directs the decorator to use a specific cache (from your\n:setting:`CACHES` setting) when caching view results. By default, the\n``default`` cache will be used, but you can specify any cache you\nwant::\n\n    @cache_page(60 * 15, cache=\"special_cache\")\n    def my_view(request):\n        ...\n\nYou can also override the cache prefix on a per-view basis. ``cache_page``\ntakes an optional keyword argument, ``key_prefix``,\nwhich works in the same way as the :setting:`CACHE_MIDDLEWARE_KEY_PREFIX`\nsetting for the middleware.  It can be used like this::\n\n    @cache_page(60 * 15, key_prefix=\"site1\")\n    def my_view(request):\n        ...\n\nThe ``key_prefix`` and ``cache`` arguments may be specified together. The\n``key_prefix`` argument and the :setting:`KEY_PREFIX <CACHES-KEY_PREFIX>`\nspecified under :setting:`CACHES` will be concatenated.\n\n.. versionchanged:: 3.1\n\n    In older versions, the ``max-age`` directive from the ``Cache-Control``\n    header had precedence over the cache timeout set by ``cache_page``.\n\nSpecifying per-view cache in the URLconf\n----------------------------------------\n\nThe examples in the previous section have hard-coded the fact that the view is\ncached, because ``cache_page`` alters the ``my_view`` function in place. This\napproach couples your view to the cache system, which is not ideal for several\nreasons. For instance, you might want to reuse the view functions on another,\ncache-less site, or you might want to distribute the views to people who might\nwant to use them without being cached. The solution to these problems is to\nspecify the per-view cache in the URLconf rather than next to the view functions\nthemselves.\n\nYou can do so by wrapping the view function with ``cache_page`` when you refer\nto it in the URLconf. Here's the old URLconf from earlier::\n\n    urlpatterns = [\n        path('foo/<int:code>/', my_view),\n    ]\n\nHere's the same thing, with ``my_view`` wrapped in ``cache_page``::\n\n    from django.views.decorators.cache import cache_page\n\n    urlpatterns = [\n        path('foo/<int:code>/', cache_page(60 * 15)(my_view)),\n    ]\n\n.. templatetag:: cache\n\nTemplate fragment caching\n=========================\n\nIf you're after even more control, you can also cache template fragments using\nthe ``cache`` template tag. To give your template access to this tag, put\n``{% load cache %}`` near the top of your template.\n\nThe ``{% cache %}`` template tag caches the contents of the block for a given\namount of time. It takes at least two arguments: the cache timeout, in seconds,\nand the name to give the cache fragment. The fragment is cached forever if\ntimeout is ``None``. The name will be taken as is, do not use a variable. For\nexample:\n\n.. code-block:: html+django\n\n    {% load cache %}\n    {% cache 500 sidebar %}\n        .. sidebar ..\n    {% endcache %}\n\nSometimes you might want to cache multiple copies of a fragment depending on\nsome dynamic data that appears inside the fragment. For example, you might want a\nseparate cached copy of the sidebar used in the previous example for every user\nof your site. Do this by passing one or more additional arguments, which may be\nvariables with or without filters, to the ``{% cache %}`` template tag to\nuniquely identify the cache fragment:\n\n.. code-block:: html+django\n\n    {% load cache %}\n    {% cache 500 sidebar request.user.username %}\n        .. sidebar for logged in user ..\n    {% endcache %}\n\nIf :setting:`USE_I18N` is set to ``True`` the per-site middleware cache will\n:ref:`respect the active language<i18n-cache-key>`. For the ``cache`` template\ntag you could use one of the\n:ref:`translation-specific variables<template-translation-vars>` available in\ntemplates to achieve the same result:\n\n.. code-block:: html+django\n\n    {% load i18n %}\n    {% load cache %}\n\n    {% get_current_language as LANGUAGE_CODE %}\n\n    {% cache 600 welcome LANGUAGE_CODE %}\n        {% translate \"Welcome to example.com\" %}\n    {% endcache %}\n\nThe cache timeout can be a template variable, as long as the template variable\nresolves to an integer value. For example, if the template variable\n``my_timeout`` is set to the value ``600``, then the following two examples are\nequivalent:\n\n.. code-block:: html+django\n\n    {% cache 600 sidebar %} ... {% endcache %}\n    {% cache my_timeout sidebar %} ... {% endcache %}\n\nThis feature is useful in avoiding repetition in templates. You can set the\ntimeout in a variable, in one place, and reuse that value.\n\nBy default, the cache tag will try to use the cache called \"template_fragments\".\nIf no such cache exists, it will fall back to using the default cache. You may\nselect an alternate cache backend to use with the ``using`` keyword argument,\nwhich must be the last argument to the tag.\n\n.. code-block:: html+django\n\n    {% cache 300 local-thing ...  using=\"localcache\" %}\n\nIt is considered an error to specify a cache name that is not configured.\n\n.. function:: django.core.cache.utils.make_template_fragment_key(fragment_name, vary_on=None)\n\nIf you want to obtain the cache key used for a cached fragment, you can use\n``make_template_fragment_key``. ``fragment_name`` is the same as second argument\nto the ``cache`` template tag; ``vary_on`` is a list of all additional arguments\npassed to the tag. This function can be useful for invalidating or overwriting\na cached item, for example:\n\n.. code-block:: pycon\n\n    >>> from django.core.cache import cache\n    >>> from django.core.cache.utils import make_template_fragment_key\n    # cache key for {% cache 500 sidebar username %}\n    >>> key = make_template_fragment_key('sidebar', [username])\n    >>> cache.delete(key) # invalidates cached template fragment\n    True\n\n.. _low-level-cache-api:\n\nThe low-level cache API\n=======================\n\n.. highlight:: python\n\nSometimes, caching an entire rendered page doesn't gain you very much and is,\nin fact, inconvenient overkill.\n\nPerhaps, for instance, your site includes a view whose results depend on\nseveral expensive queries, the results of which change at different intervals.\nIn this case, it would not be ideal to use the full-page caching that the\nper-site or per-view cache strategies offer, because you wouldn't want to\ncache the entire result (since some of the data changes often), but you'd still\nwant to cache the results that rarely change.\n\nFor cases like this, Django exposes a low-level cache API. You can use this API\nto store objects in the cache with any level of granularity you like.  You can\ncache any Python object that can be pickled safely: strings, dictionaries,\nlists of model objects, and so forth. (Most common Python objects can be\npickled; refer to the Python documentation for more information about\npickling.)\n\nAccessing the cache\n-------------------\n\n.. data:: django.core.cache.caches\n\n    You can access the caches configured in the :setting:`CACHES` setting\n    through a dict-like object: ``django.core.cache.caches``. Repeated\n    requests for the same alias in the same thread will return the same\n    object.\n\n        >>> from django.core.cache import caches\n        >>> cache1 = caches['myalias']\n        >>> cache2 = caches['myalias']\n        >>> cache1 is cache2\n        True\n\n    If the named key does not exist, ``InvalidCacheBackendError`` will be\n    raised.\n\n    To provide thread-safety, a different instance of the cache backend will\n    be returned for each thread.\n\n.. data:: django.core.cache.cache\n\n    As a shortcut, the default cache is available as\n    ``django.core.cache.cache``::\n\n        >>> from django.core.cache import cache\n\n    This object is equivalent to ``caches['default']``.\n\nBasic usage\n-----------\n\n.. currentmodule:: django.core.caches\n\nThe basic interface is:\n\n.. method:: cache.set(key, value, timeout=DEFAULT_TIMEOUT, version=None)\n\n    >>> cache.set('my_key', 'hello, world!', 30)\n\n.. method:: cache.get(key, default=None, version=None)\n\n    >>> cache.get('my_key')\n    'hello, world!'\n\n``key`` should be a ``str``, and ``value`` can be any picklable Python object.\n\nThe ``timeout`` argument is optional and defaults to the ``timeout`` argument\nof the appropriate backend in the :setting:`CACHES` setting (explained above).\nIt's the number of seconds the value should be stored in the cache. Passing in\n``None`` for ``timeout`` will cache the value forever. A ``timeout`` of ``0``\nwon't cache the value.\n\nIf the object doesn't exist in the cache, ``cache.get()`` returns ``None``::\n\n    >>> # Wait 30 seconds for 'my_key' to expire...\n    >>> cache.get('my_key')\n    None\n\nWe advise against storing the literal value ``None`` in the cache, because you\nwon't be able to distinguish between your stored ``None`` value and a cache\nmiss signified by a return value of ``None``.\n\n``cache.get()`` can take a ``default`` argument. This specifies which value to\nreturn if the object doesn't exist in the cache::\n\n    >>> cache.get('my_key', 'has expired')\n    'has expired'\n\n.. method:: cache.add(key, value, timeout=DEFAULT_TIMEOUT, version=None)\n\nTo add a key only if it doesn't already exist, use the ``add()`` method.\nIt takes the same parameters as ``set()``, but it will not attempt to\nupdate the cache if the key specified is already present::\n\n    >>> cache.set('add_key', 'Initial value')\n    >>> cache.add('add_key', 'New value')\n    >>> cache.get('add_key')\n    'Initial value'\n\nIf you need to know whether ``add()`` stored a value in the cache, you can\ncheck the return value. It will return ``True`` if the value was stored,\n``False`` otherwise.\n\n.. method:: cache.get_or_set(key, default, timeout=DEFAULT_TIMEOUT, version=None)\n\nIf you want to get a key's value or set a value if the key isn't in the cache,\nthere is the ``get_or_set()`` method. It takes the same parameters as ``get()``\nbut the default is set as the new cache value for that key, rather than\nreturned::\n\n    >>> cache.get('my_new_key')  # returns None\n    >>> cache.get_or_set('my_new_key', 'my new value', 100)\n    'my new value'\n\nYou can also pass any callable as a *default* value::\n\n    >>> import datetime\n    >>> cache.get_or_set('some-timestamp-key', datetime.datetime.now)\n    datetime.datetime(2014, 12, 11, 0, 15, 49, 457920)\n\n.. method:: cache.get_many(keys, version=None)\n\nThere's also a ``get_many()`` interface that only hits the cache once.\n``get_many()`` returns a dictionary with all the keys you asked for that\nactually exist in the cache (and haven't expired)::\n\n    >>> cache.set('a', 1)\n    >>> cache.set('b', 2)\n    >>> cache.set('c', 3)\n    >>> cache.get_many(['a', 'b', 'c'])\n    {'a': 1, 'b': 2, 'c': 3}\n\n.. method:: cache.set_many(dict, timeout)\n\nTo set multiple values more efficiently, use ``set_many()`` to pass a dictionary\nof key-value pairs::\n\n    >>> cache.set_many({'a': 1, 'b': 2, 'c': 3})\n    >>> cache.get_many(['a', 'b', 'c'])\n    {'a': 1, 'b': 2, 'c': 3}\n\nLike ``cache.set()``, ``set_many()`` takes an optional ``timeout`` parameter.\n\nOn supported backends (memcached), ``set_many()`` returns a list of keys that\nfailed to be inserted.\n\n.. method:: cache.delete(key, version=None)\n\nYou can delete keys explicitly with ``delete()`` to clear the cache for a\nparticular object::\n\n    >>> cache.delete('a')\n    True\n\n``delete()`` returns ``True`` if the key was successfully deleted, ``False``\notherwise.\n\n.. versionchanged:: 3.1\n\n    The boolean return value was added.\n\n.. method:: cache.delete_many(keys, version=None)\n\nIf you want to clear a bunch of keys at once, ``delete_many()`` can take a list\nof keys to be cleared::\n\n    >>> cache.delete_many(['a', 'b', 'c'])\n\n.. method:: cache.clear()\n\nFinally, if you want to delete all the keys in the cache, use\n``cache.clear()``.  Be careful with this; ``clear()`` will remove *everything*\nfrom the cache, not just the keys set by your application. ::\n\n    >>> cache.clear()\n\n.. method:: cache.touch(key, timeout=DEFAULT_TIMEOUT, version=None)\n\n``cache.touch()`` sets a new expiration for a key. For example, to update a key\nto expire 10 seconds from now::\n\n    >>> cache.touch('a', 10)\n    True\n\nLike other methods, the ``timeout`` argument is optional and defaults to the\n``TIMEOUT`` option of the appropriate backend in the :setting:`CACHES` setting.\n\n``touch()`` returns ``True`` if the key was successfully touched, ``False``\notherwise.\n\n.. method:: cache.incr(key, delta=1, version=None)\n.. method:: cache.decr(key, delta=1, version=None)\n\nYou can also increment or decrement a key that already exists using the\n``incr()`` or ``decr()`` methods, respectively. By default, the existing cache\nvalue will be incremented or decremented by 1. Other increment/decrement values\ncan be specified by providing an argument to the increment/decrement call. A\nValueError will be raised if you attempt to increment or decrement a\nnonexistent cache key.::\n\n    >>> cache.set('num', 1)\n    >>> cache.incr('num')\n    2\n    >>> cache.incr('num', 10)\n    12\n    >>> cache.decr('num')\n    11\n    >>> cache.decr('num', 5)\n    6\n\n.. note::\n\n    ``incr()``/``decr()`` methods are not guaranteed to be atomic. On those\n    backends that support atomic increment/decrement (most notably, the\n    memcached backend), increment and decrement operations will be atomic.\n    However, if the backend doesn't natively provide an increment/decrement\n    operation, it will be implemented using a two-step retrieve/update.\n\n.. method:: cache.close()\n\nYou can close the connection to your cache with ``close()`` if implemented by\nthe cache backend.\n\n    >>> cache.close()\n\n.. note::\n\n    For caches that don't implement ``close`` methods it is a no-op.\n\n.. _cache_key_prefixing:\n\nCache key prefixing\n-------------------\n\nIf you are sharing a cache instance between servers, or between your\nproduction and development environments, it's possible for data cached\nby one server to be used by another server. If the format of cached\ndata is different between servers, this can lead to some very hard to\ndiagnose problems.\n\nTo prevent this, Django provides the ability to prefix all cache keys\nused by a server. When a particular cache key is saved or retrieved,\nDjango will automatically prefix the cache key with the value of the\n:setting:`KEY_PREFIX <CACHES-KEY_PREFIX>` cache setting.\n\nBy ensuring each Django instance has a different\n:setting:`KEY_PREFIX <CACHES-KEY_PREFIX>`, you can ensure that there will be no\ncollisions in cache values.\n\n.. _cache_versioning:\n\nCache versioning\n----------------\n\nWhen you change running code that uses cached values, you may need to\npurge any existing cached values. The easiest way to do this is to\nflush the entire cache, but this can lead to the loss of cache values\nthat are still valid and useful.\n\nDjango provides a better way to target individual cache values.\nDjango's cache framework has a system-wide version identifier,\nspecified using the :setting:`VERSION <CACHES-VERSION>` cache setting.\nThe value of this setting is automatically combined with the cache\nprefix and the user-provided cache key to obtain the final cache key.\n\nBy default, any key request will automatically include the site\ndefault cache key version. However, the primitive cache functions all\ninclude a ``version`` argument, so you can specify a particular cache\nkey version to set or get. For example::\n\n    >>> # Set version 2 of a cache key\n    >>> cache.set('my_key', 'hello world!', version=2)\n    >>> # Get the default version (assuming version=1)\n    >>> cache.get('my_key')\n    None\n    >>> # Get version 2 of the same key\n    >>> cache.get('my_key', version=2)\n    'hello world!'\n\nThe version of a specific key can be incremented and decremented using\nthe ``incr_version()`` and ``decr_version()`` methods. This\nenables specific keys to be bumped to a new version, leaving other\nkeys unaffected. Continuing our previous example::\n\n    >>> # Increment the version of 'my_key'\n    >>> cache.incr_version('my_key')\n    >>> # The default version still isn't available\n    >>> cache.get('my_key')\n    None\n    # Version 2 isn't available, either\n    >>> cache.get('my_key', version=2)\n    None\n    >>> # But version 3 *is* available\n    >>> cache.get('my_key', version=3)\n    'hello world!'\n\n.. _cache_key_transformation:\n\nCache key transformation\n------------------------\n\nAs described in the previous two sections, the cache key provided by a\nuser is not used verbatim -- it is combined with the cache prefix and\nkey version to provide a final cache key. By default, the three parts\nare joined using colons to produce a final string::\n\n    def make_key(key, key_prefix, version):\n        return '%s:%s:%s' % (key_prefix, version, key)\n\nIf you want to combine the parts in different ways, or apply other\nprocessing to the final key (e.g., taking a hash digest of the key\nparts), you can provide a custom key function.\n\nThe :setting:`KEY_FUNCTION <CACHES-KEY_FUNCTION>` cache setting\nspecifies a dotted-path to a function matching the prototype of\n``make_key()`` above. If provided, this custom key function will\nbe used instead of the default key combining function.\n\nCache key warnings\n------------------\n\nMemcached, the most commonly-used production cache backend, does not allow\ncache keys longer than 250 characters or containing whitespace or control\ncharacters, and using such keys will cause an exception. To encourage\ncache-portable code and minimize unpleasant surprises, the other built-in cache\nbackends issue a warning (``django.core.cache.backends.base.CacheKeyWarning``)\nif a key is used that would cause an error on memcached.\n\nIf you are using a production backend that can accept a wider range of keys (a\ncustom backend, or one of the non-memcached built-in backends), and want to use\nthis wider range without warnings, you can silence ``CacheKeyWarning`` with\nthis code in the ``management`` module of one of your\n:setting:`INSTALLED_APPS`::\n\n     import warnings\n\n     from django.core.cache import CacheKeyWarning\n\n     warnings.simplefilter(\"ignore\", CacheKeyWarning)\n\nIf you want to instead provide custom key validation logic for one of the\nbuilt-in backends, you can subclass it, override just the ``validate_key``\nmethod, and follow the instructions for `using a custom cache backend`_. For\ninstance, to do this for the ``locmem`` backend, put this code in a module::\n\n    from django.core.cache.backends.locmem import LocMemCache\n\n    class CustomLocMemCache(LocMemCache):\n        def validate_key(self, key):\n            \"\"\"Custom validation, raising exceptions or warnings as needed.\"\"\"\n            ...\n\n...and use the dotted Python path to this class in the\n:setting:`BACKEND <CACHES-BACKEND>` portion of your :setting:`CACHES` setting.\n\nDownstream caches\n=================\n\nSo far, this document has focused on caching your *own* data. But another type\nof caching is relevant to Web development, too: caching performed by\n\"downstream\" caches. These are systems that cache pages for users even before\nthe request reaches your website.\n\nHere are a few examples of downstream caches:\n\n* Your ISP may cache certain pages, so if you requested a page from\n  https://example.com/, your ISP would send you the page without having to\n  access example.com directly. The maintainers of example.com have no\n  knowledge of this caching; the ISP sits between example.com and your Web\n  browser, handling all of the caching transparently.\n\n* Your Django website may sit behind a *proxy cache*, such as Squid Web\n  Proxy Cache (http://www.squid-cache.org/), that caches pages for\n  performance. In this case, each request first would be handled by the\n  proxy, and it would be passed to your application only if needed.\n\n* Your Web browser caches pages, too. If a Web page sends out the\n  appropriate headers, your browser will use the local cached copy for\n  subsequent requests to that page, without even contacting the Web page\n  again to see whether it has changed.\n\nDownstream caching is a nice efficiency boost, but there's a danger to it:\nMany Web pages' contents differ based on authentication and a host of other\nvariables, and cache systems that blindly save pages based purely on URLs could\nexpose incorrect or sensitive data to subsequent visitors to those pages.\n\nFor example, if you operate a Web email system, then the contents of the\n\"inbox\" page depend on which user is logged in. If an ISP blindly cached your\nsite, then the first user who logged in through that ISP would have their\nuser-specific inbox page cached for subsequent visitors to the site.  That's\nnot cool.\n\nFortunately, HTTP provides a solution to this problem. A number of HTTP headers\nexist to instruct downstream caches to differ their cache contents depending on\ndesignated variables, and to tell caching mechanisms not to cache particular\npages. We'll look at some of these headers in the sections that follow.\n\n.. _using-vary-headers:\n\nUsing ``Vary`` headers\n======================\n\nThe ``Vary`` header defines which request headers a cache\nmechanism should take into account when building its cache key. For example, if\nthe contents of a Web page depend on a user's language preference, the page is\nsaid to \"vary on language.\"\n\nBy default, Django's cache system creates its cache keys using the requested\nfully-qualified URL -- e.g.,\n``\"https://www.example.com/stories/2005/?order_by=author\"``. This means every\nrequest to that URL will use the same cached version, regardless of user-agent\ndifferences such as cookies or language preferences. However, if this page\nproduces different content based on some difference in request headers -- such\nas a cookie, or a language, or a user-agent -- you'll need to use the ``Vary``\nheader to tell caching mechanisms that the page output depends on those things.\n\nTo do this in Django, use the convenient\n:func:`django.views.decorators.vary.vary_on_headers` view decorator, like so::\n\n    from django.views.decorators.vary import vary_on_headers\n\n    @vary_on_headers('User-Agent')\n    def my_view(request):\n        ...\n\nIn this case, a caching mechanism (such as Django's own cache middleware) will\ncache a separate version of the page for each unique user-agent.\n\nThe advantage to using the ``vary_on_headers`` decorator rather than manually\nsetting the ``Vary`` header (using something like\n``response['Vary'] = 'user-agent'``) is that the decorator *adds* to the\n``Vary`` header (which may already exist), rather than setting it from scratch\nand potentially overriding anything that was already in there.\n\nYou can pass multiple headers to ``vary_on_headers()``::\n\n    @vary_on_headers('User-Agent', 'Cookie')\n    def my_view(request):\n        ...\n\nThis tells downstream caches to vary on *both*, which means each combination of\nuser-agent and cookie will get its own cache value. For example, a request with\nthe user-agent ``Mozilla`` and the cookie value ``foo=bar`` will be considered\ndifferent from a request with the user-agent ``Mozilla`` and the cookie value\n``foo=ham``.\n\nBecause varying on cookie is so common, there's a\n:func:`django.views.decorators.vary.vary_on_cookie` decorator. These two views\nare equivalent::\n\n    @vary_on_cookie\n    def my_view(request):\n        ...\n\n    @vary_on_headers('Cookie')\n    def my_view(request):\n        ...\n\nThe headers you pass to ``vary_on_headers`` are not case sensitive;\n``\"User-Agent\"`` is the same thing as ``\"user-agent\"``.\n\nYou can also use a helper function, :func:`django.utils.cache.patch_vary_headers`,\ndirectly. This function sets, or adds to, the ``Vary header``. For example::\n\n    from django.shortcuts import render\n    from django.utils.cache import patch_vary_headers\n\n    def my_view(request):\n        ...\n        response = render(request, 'template_name', context)\n        patch_vary_headers(response, ['Cookie'])\n        return response\n\n``patch_vary_headers`` takes an :class:`~django.http.HttpResponse` instance as\nits first argument and a list/tuple of case-insensitive header names as its\nsecond argument.\n\nFor more on Vary headers, see the :rfc:`official Vary spec\n<7231#section-7.1.4>`.\n\nControlling cache: Using other headers\n======================================\n\nOther problems with caching are the privacy of data and the question of where\ndata should be stored in a cascade of caches.\n\nA user usually faces two kinds of caches: their own browser cache (a private\ncache) and their provider's cache (a public cache). A public cache is used by\nmultiple users and controlled by someone else. This poses problems with\nsensitive data--you don't want, say, your bank account number stored in a\npublic cache. So Web applications need a way to tell caches which data is\nprivate and which is public.\n\nThe solution is to indicate a page's cache should be \"private.\" To do this in\nDjango, use the :func:`~django.views.decorators.cache.cache_control` view\ndecorator. Example::\n\n    from django.views.decorators.cache import cache_control\n\n    @cache_control(private=True)\n    def my_view(request):\n        ...\n\nThis decorator takes care of sending out the appropriate HTTP header behind the\nscenes.\n\nNote that the cache control settings \"private\" and \"public\" are mutually\nexclusive. The decorator ensures that the \"public\" directive is removed if\n\"private\" should be set (and vice versa). An example use of the two directives\nwould be a blog site that offers both private and public entries. Public\nentries may be cached on any shared cache. The following code uses\n:func:`~django.utils.cache.patch_cache_control`, the manual way to modify the\ncache control header (it is internally called by the\n:func:`~django.views.decorators.cache.cache_control` decorator)::\n\n    from django.views.decorators.cache import patch_cache_control\n    from django.views.decorators.vary import vary_on_cookie\n\n    @vary_on_cookie\n    def list_blog_entries_view(request):\n        if request.user.is_anonymous:\n            response = render_only_public_entries()\n            patch_cache_control(response, public=True)\n        else:\n            response = render_private_and_public_entries(request.user)\n            patch_cache_control(response, private=True)\n\n        return response\n\nYou can control downstream caches in other ways as well (see :rfc:`7234` for\ndetails on HTTP caching). For example, even if you don't use Django's\nserver-side cache framework, you can still tell clients to cache a view for a\ncertain amount of time with the :rfc:`max-age <7234#section-5.2.2.8>`\ndirective::\n\n    from django.views.decorators.cache import cache_control\n\n    @cache_control(max_age=3600)\n    def my_view(request):\n        ...\n\n(If you *do* use the caching middleware, it already sets the ``max-age`` with\nthe value of the :setting:`CACHE_MIDDLEWARE_SECONDS` setting. In that case,\nthe custom ``max_age`` from the\n:func:`~django.views.decorators.cache.cache_control` decorator will take\nprecedence, and the header values will be merged correctly.)\n\nAny valid ``Cache-Control`` response directive is valid in ``cache_control()``.\nHere are some more examples:\n\n* ``no_transform=True``\n* ``must_revalidate=True``\n* ``stale_while_revalidate=num_seconds``\n* ``no_cache=True``\n\nThe full list of known directives can be found in the `IANA registry`_\n(note that not all of them apply to responses).\n\n.. _IANA registry: https://www.iana.org/assignments/http-cache-directives/http-cache-directives.xhtml\n\nIf you want to use headers to disable caching altogether,\n:func:`~django.views.decorators.cache.never_cache` is a view decorator that\nadds headers to ensure the response won't be cached by browsers or other\ncaches. Example::\n\n    from django.views.decorators.cache import never_cache\n\n    @never_cache\n    def myview(request):\n        ...\n\nOrder of ``MIDDLEWARE``\n=======================\n\nIf you use caching middleware, it's important to put each half in the right\nplace within the :setting:`MIDDLEWARE` setting. That's because the cache\nmiddleware needs to know which headers by which to vary the cache storage.\nMiddleware always adds something to the ``Vary`` response header when it can.\n\n``UpdateCacheMiddleware`` runs during the response phase, where middleware is\nrun in reverse order, so an item at the top of the list runs *last* during the\nresponse phase. Thus, you need to make sure that ``UpdateCacheMiddleware``\nappears *before* any other middleware that might add something to the ``Vary``\nheader. The following middleware modules do so:\n\n* ``SessionMiddleware`` adds ``Cookie``\n* ``GZipMiddleware`` adds ``Accept-Encoding``\n* ``LocaleMiddleware`` adds ``Accept-Language``\n\n``FetchFromCacheMiddleware``, on the other hand, runs during the request phase,\nwhere middleware is applied first-to-last, so an item at the top of the list\nruns *first* during the request phase. The ``FetchFromCacheMiddleware`` also\nneeds to run after other middleware updates the ``Vary`` header, so\n``FetchFromCacheMiddleware`` must be *after* any item that does so.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":266,"nodeType":"TextFile","repoName":null,"name":"checks.txt","path":"docs/topics","text":"======================\nSystem check framework\n======================\n\n.. module:: django.core.checks\n\nThe system check framework is a set of static checks for validating Django\nprojects. It detects common problems and provides hints for how to fix them.\nThe framework is extensible so you can easily add your own checks.\n\nChecks can be triggered explicitly via the :djadmin:`check` command. Checks are\ntriggered implicitly before most commands, including :djadmin:`runserver` and\n:djadmin:`migrate`. For performance reasons, checks are not run as part of the\nWSGI stack that is used in deployment. If you need to run system checks on your\ndeployment server, trigger them explicitly using :djadmin:`check`.\n\nSerious errors will prevent Django commands (such as :djadmin:`runserver`) from\nrunning at all. Minor problems are reported to the console. If you have inspected\nthe cause of a warning and are happy to ignore it, you can hide specific warnings\nusing the :setting:`SILENCED_SYSTEM_CHECKS` setting in your project settings file.\n\nA full list of all checks that can be raised by Django can be found in the\n:doc:`System check reference </ref/checks>`.\n\nWriting your own checks\n=======================\n\nThe framework is flexible and allows you to write functions that perform\nany other kind of check you may require. The following is an example stub\ncheck function::\n\n    from django.core.checks import Error, register\n\n    @register()\n    def example_check(app_configs, **kwargs):\n        errors = []\n        # ... your check logic here\n        if check_failed:\n            errors.append(\n                Error(\n                    'an error',\n                    hint='A hint.',\n                    obj=checked_object,\n                    id='myapp.E001',\n                )\n            )\n        return errors\n\nThe check function *must* accept an ``app_configs`` argument; this argument is\nthe list of applications that should be inspected. If None, the check must be\nrun on *all* installed apps in the project. The ``**kwargs`` argument is required\nfor future expansion.\n\nMessages\n--------\n\nThe function must return a list of messages. If no problems are found as a result\nof the check, the check function must return an empty list.\n\nThe warnings and errors raised by the check method must be instances of\n:class:`~django.core.checks.CheckMessage`. An instance of\n:class:`~django.core.checks.CheckMessage` encapsulates a single reportable\nerror or warning. It also provides context and hints applicable to the\nmessage, and a unique identifier that is used for filtering purposes.\n\nThe concept is very similar to messages from the :doc:`message framework\n</ref/contrib/messages>` or the :doc:`logging framework </topics/logging>`.\nMessages are tagged with a ``level`` indicating the severity of the message.\n\nThere are also shortcuts to make creating messages with common levels easier.\nWhen using these classes you can omit the ``level`` argument because it is\nimplied by the class name.\n\n* :class:`Debug`\n* :class:`Info`\n* :class:`Warning`\n* :class:`Error`\n* :class:`Critical`\n\nRegistering and labeling checks\n-------------------------------\n\nLastly, your check function must be registered explicitly with system check\nregistry. Checks should be registered in a file that's loaded when your\napplication is loaded; for example, in the :meth:`AppConfig.ready()\n<django.apps.AppConfig.ready>` method.\n\n.. function:: register(*tags)(function)\n\nYou can pass as many tags to ``register`` as you want in order to label your\ncheck. Tagging checks is useful since it allows you to run only a certain\ngroup of checks. For example, to register a compatibility check, you would\nmake the following call::\n\n    from django.core.checks import register, Tags\n\n    @register(Tags.compatibility)\n    def my_check(app_configs, **kwargs):\n        # ... perform compatibility checks and collect errors\n        return errors\n\nYou can register \"deployment checks\" that are only relevant to a production\nsettings file like this::\n\n    @register(Tags.security, deploy=True)\n    def my_check(app_configs, **kwargs):\n        ...\n\nThese checks will only be run if the :option:`check --deploy` option is used.\n\nYou can also use ``register`` as a function rather than a decorator by\npassing a callable object (usually a function) as the first argument\nto ``register``.\n\nThe code below is equivalent to the code above::\n\n    def my_check(app_configs, **kwargs):\n        ...\n    register(my_check, Tags.security, deploy=True)\n\n.. _field-checking:\n\nField, model, manager, and database checks\n------------------------------------------\n\nIn some cases, you won't need to register your check function -- you can\npiggyback on an existing registration.\n\nFields, models, model managers, and database backends all implement a\n``check()`` method that is already registered with the check framework. If you\nwant to add extra checks, you can extend the implementation on the base class,\nperform any extra checks you need, and append any messages to those generated\nby the base class. It's recommended that you delegate each check to separate\nmethods.\n\nConsider an example where you are implementing a custom field named\n``RangedIntegerField``. This field adds ``min`` and ``max`` arguments to the\nconstructor of ``IntegerField``. You may want to add a check to ensure that users\nprovide a min value that is less than or equal to the max value. The following\ncode snippet shows how you can implement this check::\n\n    from django.core import checks\n    from django.db import models\n\n    class RangedIntegerField(models.IntegerField):\n        def __init__(self, min=None, max=None, **kwargs):\n            super().__init__(**kwargs)\n            self.min = min\n            self.max = max\n\n        def check(self, **kwargs):\n            # Call the superclass\n            errors = super().check(**kwargs)\n\n            # Do some custom checks and add messages to `errors`:\n            errors.extend(self._check_min_max_values(**kwargs))\n\n            # Return all errors and warnings\n            return errors\n\n        def _check_min_max_values(self, **kwargs):\n            if (self.min is not None and\n                    self.max is not None and\n                    self.min > self.max):\n                return [\n                    checks.Error(\n                        'min greater than max.',\n                        hint='Decrease min or increase max.',\n                        obj=self,\n                        id='myapp.E001',\n                    )\n                ]\n            # When no error, return an empty list\n            return []\n\nIf you wanted to add checks to a model manager, you would take the same\napproach on your subclass of :class:`~django.db.models.Manager`.\n\nIf you want to add a check to a model class, the approach is *almost* the same:\nthe only difference is that the check is a classmethod, not an instance method::\n\n    class MyModel(models.Model):\n        @classmethod\n        def check(cls, **kwargs):\n            errors = super().check(**kwargs)\n            # ... your own checks ...\n            return errors\n\nWriting tests\n-------------\n\nMessages are comparable. That allows you to easily write tests::\n\n    from django.core.checks import Error\n    errors = checked_object.check()\n    expected_errors = [\n        Error(\n            'an error',\n            hint='A hint.',\n            obj=checked_object,\n            id='myapp.E001',\n        )\n    ]\n    self.assertEqual(errors, expected_errors)\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":267,"nodeType":"TextFile","repoName":null,"name":"templates.txt","path":"docs/topics","text":"=========\nTemplates\n=========\n\n.. module:: django.template\n    :synopsis: Django's template system\n\nBeing a web framework, Django needs a convenient way to generate HTML\ndynamically. The most common approach relies on templates. A template contains\nthe static parts of the desired HTML output as well as some special syntax\ndescribing how dynamic content will be inserted. For a hands-on example of\ncreating HTML pages with templates, see :doc:`Tutorial 3 </intro/tutorial03>`.\n\nA Django project can be configured with one or several template engines (or\neven zero if you don't use templates). Django ships built-in backends for its\nown template system, creatively called the Django template language (DTL), and\nfor the popular alternative Jinja2_. Backends for other template languages may\nbe available from third-parties. You can also write your own custom backend,\nsee :doc:`Custom template backend </howto/custom-template-backend>`\n\nDjango defines a standard API for loading and rendering templates regardless\nof the backend. Loading consists of finding the template for a given identifier\nand preprocessing it, usually compiling it to an in-memory representation.\nRendering means interpolating the template with context data and returning the\nresulting string.\n\nThe :doc:`Django template language </ref/templates/language>` is Django's own\ntemplate system. Until Django 1.8 it was the only built-in option available.\nIt's a good template library even though it's fairly opinionated and sports a\nfew idiosyncrasies. If you don't have a pressing reason to choose another\nbackend, you should use the DTL, especially if you're writing a pluggable\napplication and you intend to distribute templates. Django's contrib apps that\ninclude templates, like :doc:`django.contrib.admin </ref/contrib/admin/index>`,\nuse the DTL.\n\nFor historical reasons, both the generic support for template engines and the\nimplementation of the Django template language live in the ``django.template``\nnamespace.\n\n.. warning::\n\n    The template system isn't safe against untrusted template authors. For\n    example, a site shouldn't allow its users to provide their own templates,\n    since template authors can do things like perform XSS attacks and access\n    properties of template variables that may contain sensitive information.\n\n.. _template-language-intro:\n\nThe Django template language\n============================\n\n.. highlight:: html+django\n\nSyntax\n------\n\n.. admonition:: About this section\n\n    This is an overview of the Django template language's syntax. For details\n    see the :doc:`language syntax reference </ref/templates/language>`.\n\nA Django template is a text document or a Python string marked-up using the\nDjango template language. Some constructs are recognized and interpreted by the\ntemplate engine. The main ones are variables and tags.\n\nA template is rendered with a context. Rendering replaces variables with their\nvalues, which are looked up in the context, and executes tags. Everything else\nis output as is.\n\nThe syntax of the Django template language involves four constructs.\n\nVariables\n~~~~~~~~~\n\nA variable outputs a value from the context, which is a dict-like object\nmapping keys to values.\n\nVariables are surrounded by ``{{`` and ``}}`` like this::\n\n    My first name is {{ first_name }}. My last name is {{ last_name }}.\n\nWith a context of ``{'first_name': 'John', 'last_name': 'Doe'}``, this template\nrenders to::\n\n    My first name is John. My last name is Doe.\n\nDictionary lookup, attribute lookup and list-index lookups are implemented with\na dot notation::\n\n    {{ my_dict.key }}\n    {{ my_object.attribute }}\n    {{ my_list.0 }}\n\nIf a variable resolves to a callable, the template system will call it with no\narguments and use its result instead of the callable.\n\nTags\n~~~~\n\nTags provide arbitrary logic in the rendering process.\n\nThis definition is deliberately vague. For example, a tag can output content,\nserve as a control structure e.g. an \"if\" statement or a \"for\" loop, grab\ncontent from a database, or even enable access to other template tags.\n\nTags are surrounded by ``{%`` and ``%}`` like this::\n\n    {% csrf_token %}\n\nMost tags accept arguments::\n\n    {% cycle 'odd' 'even' %}\n\nSome tags require beginning and ending tags::\n\n    {% if user.is_authenticated %}Hello, {{ user.username }}.{% endif %}\n\nA :ref:`reference of built-in tags <ref-templates-builtins-tags>` is\navailable as well as :ref:`instructions for writing custom tags\n<howto-writing-custom-template-tags>`.\n\nFilters\n~~~~~~~\n\nFilters transform the values of variables and tag arguments.\n\nThey look like this::\n\n     {{ django|title }}\n\nWith a context of ``{'django': 'the web framework for perfectionists with\ndeadlines'}``, this template renders to::\n\n    The Web Framework For Perfectionists With Deadlines\n\nSome filters take an argument::\n\n    {{ my_date|date:\"Y-m-d\" }}\n\nA :ref:`reference of built-in filters <ref-templates-builtins-filters>` is\navailable as well as :ref:`instructions for writing custom filters\n<howto-writing-custom-template-filters>`.\n\nComments\n~~~~~~~~\n\nComments look like this::\n\n    {# this won't be rendered #}\n\nA :ttag:`{% comment %} <comment>` tag provides multi-line comments.\n\nComponents\n----------\n\n.. admonition:: About this section\n\n    This is an overview of the Django template language's APIs. For details\n    see the :doc:`API reference </ref/templates/api>`.\n\nEngine\n~~~~~~\n\n:class:`django.template.Engine` encapsulates an instance of the Django\ntemplate system. The main reason for instantiating an\n:class:`~django.template.Engine` directly is to use the Django template\nlanguage outside of a Django project.\n\n:class:`django.template.backends.django.DjangoTemplates` is a thin wrapper\nadapting :class:`django.template.Engine` to Django's template backend API.\n\nTemplate\n~~~~~~~~\n\n:class:`django.template.Template` represents a compiled template. Templates are\nobtained with :meth:`.Engine.get_template` or :meth:`.Engine.from_string`.\n\nLikewise ``django.template.backends.django.Template`` is a thin wrapper\nadapting :class:`django.template.Template` to the common template API.\n\nContext\n~~~~~~~\n\n:class:`django.template.Context` holds some metadata in addition to the context\ndata. It is passed to :meth:`.Template.render` for rendering a template.\n\n:class:`django.template.RequestContext` is a subclass of\n:class:`~django.template.Context` that stores the current\n:class:`~django.http.HttpRequest` and runs template context processors.\n\nThe common API doesn't have an equivalent concept. Context data is passed in a\nplain :class:`dict` and the current :class:`~django.http.HttpRequest` is passed\nseparately if needed.\n\nLoaders\n~~~~~~~\n\nTemplate loaders are responsible for locating templates, loading them, and\nreturning :class:`~django.template.Template` objects.\n\nDjango provides several :ref:`built-in template loaders <template-loaders>`\nand supports :ref:`custom template loaders <custom-template-loaders>`.\n\nContext processors\n~~~~~~~~~~~~~~~~~~\n\nContext processors are functions that receive the current\n:class:`~django.http.HttpRequest` as an argument and return a :class:`dict` of\ndata to be added to the rendering context.\n\nTheir main use is to add common data shared by all templates to the context\nwithout repeating code in every view.\n\nDjango provides many :ref:`built-in context processors <context-processors>`,\nand you can implement your own additional context processors, too.\n\n.. _template-engines:\n\nSupport for template engines\n============================\n\n.. highlight:: python\n\nConfiguration\n-------------\n\nTemplates engines are configured with the :setting:`TEMPLATES` setting. It's a\nlist of configurations, one for each engine. The default value is empty. The\n``settings.py`` generated by the :djadmin:`startproject` command defines a\nmore useful value::\n\n    TEMPLATES = [\n        {\n            'BACKEND': 'django.template.backends.django.DjangoTemplates',\n            'DIRS': [],\n            'APP_DIRS': True,\n            'OPTIONS': {\n                # ... some options here ...\n            },\n        },\n    ]\n\n:setting:`BACKEND <TEMPLATES-BACKEND>` is a dotted Python path to a template\nengine class implementing Django's template backend API. The built-in backends\nare :class:`django.template.backends.django.DjangoTemplates` and\n:class:`django.template.backends.jinja2.Jinja2`.\n\nSince most engines load templates from files, the top-level configuration for\neach engine contains two common settings:\n\n* :setting:`DIRS <TEMPLATES-DIRS>` defines a list of directories where the\n  engine should look for template source files, in search order.\n* :setting:`APP_DIRS <TEMPLATES-APP_DIRS>` tells whether the engine should\n  look for templates inside installed applications. Each backend defines a\n  conventional name for the subdirectory inside applications where its\n  templates should be stored.\n\nWhile uncommon, it's possible to configure several instances of the same\nbackend with different options. In that case you should define a unique\n:setting:`NAME <TEMPLATES-NAME>` for each engine.\n\n:setting:`OPTIONS <TEMPLATES-OPTIONS>` contains backend-specific settings.\n\nUsage\n-----\n\n.. _template-loading:\n\n.. module:: django.template.loader\n\nThe ``django.template.loader`` module defines two functions to load templates.\n\n.. function:: get_template(template_name, using=None)\n\n    This function loads the template with the given name and returns a\n    ``Template`` object.\n\n    The exact type of the return value depends on the backend that loaded the\n    template. Each backend has its own ``Template`` class.\n\n    ``get_template()`` tries each template engine in order until one succeeds.\n    If the template cannot be found, it raises\n    :exc:`~django.template.TemplateDoesNotExist`. If the template is found but\n    contains invalid syntax, it raises\n    :exc:`~django.template.TemplateSyntaxError`.\n\n    How templates are searched and loaded depends on each engine's backend and\n    configuration.\n\n    If you want to restrict the search to a particular template engine, pass\n    the engine's :setting:`NAME <TEMPLATES-NAME>` in the ``using`` argument.\n\n.. function:: select_template(template_name_list, using=None)\n\n    ``select_template()`` is just like ``get_template()``, except it takes a\n    list of template names. It tries each name in order and returns the first\n    template that exists.\n\n.. currentmodule:: django.template\n\nIf loading a template fails, the following two exceptions, defined in\n``django.template``, may be raised:\n\n.. exception:: TemplateDoesNotExist(msg, tried=None, backend=None, chain=None)\n\n    This exception is raised when a template cannot be found. It accepts the\n    following optional arguments for populating the :ref:`template postmortem\n    <template-postmortem>` on the debug page:\n\n    ``backend``\n        The template backend instance from which the exception originated.\n\n    ``tried``\n        A list of sources that were tried when finding the template. This is\n        formatted as a list of tuples containing ``(origin, status)``, where\n        ``origin`` is an :ref:`origin-like <template-origin-api>` object and\n        ``status`` is a string with the reason the template wasn't found.\n\n    ``chain``\n        A list of intermediate :exc:`~django.template.TemplateDoesNotExist`\n        exceptions raised when trying to load a template. This is used by\n        functions, such as :func:`~django.template.loader.get_template`, that\n        try to load a given template from multiple engines.\n\n.. exception:: TemplateSyntaxError(msg)\n\n    This exception is raised when a template was found but contains errors.\n\n``Template`` objects returned by ``get_template()`` and ``select_template()``\nmust provide a ``render()`` method with the following signature:\n\n.. currentmodule:: django.template.backends.base\n\n.. method:: Template.render(context=None, request=None)\n\n    Renders this template with a given context.\n\n    If ``context`` is provided, it must be a :class:`dict`. If it isn't\n    provided, the engine will render the template with an empty context.\n\n    If ``request`` is provided, it must be an :class:`~django.http.HttpRequest`.\n    Then the engine must make it, as well as the CSRF token, available in the\n    template. How this is achieved is up to each backend.\n\nHere's an example of the search algorithm. For this example the\n:setting:`TEMPLATES` setting is::\n\n    TEMPLATES = [\n        {\n            'BACKEND': 'django.template.backends.django.DjangoTemplates',\n            'DIRS': [\n                '/home/html/example.com',\n                '/home/html/default',\n            ],\n        },\n        {\n            'BACKEND': 'django.template.backends.jinja2.Jinja2',\n            'DIRS': [\n                '/home/html/jinja2',\n            ],\n        },\n    ]\n\nIf you call ``get_template('story_detail.html')``, here are the files Django\nwill look for, in order:\n\n* ``/home/html/example.com/story_detail.html`` (``'django'`` engine)\n* ``/home/html/default/story_detail.html`` (``'django'`` engine)\n* ``/home/html/jinja2/story_detail.html`` (``'jinja2'`` engine)\n\nIf you call ``select_template(['story_253_detail.html', 'story_detail.html'])``,\nhere's what Django will look for:\n\n* ``/home/html/example.com/story_253_detail.html`` (``'django'`` engine)\n* ``/home/html/default/story_253_detail.html`` (``'django'`` engine)\n* ``/home/html/jinja2/story_253_detail.html`` (``'jinja2'`` engine)\n* ``/home/html/example.com/story_detail.html`` (``'django'`` engine)\n* ``/home/html/default/story_detail.html`` (``'django'`` engine)\n* ``/home/html/jinja2/story_detail.html`` (``'jinja2'`` engine)\n\nWhen Django finds a template that exists, it stops looking.\n\n.. admonition:: Tip\n\n    You can use :func:`~django.template.loader.select_template()` for flexible\n    template loading. For example, if you've written a news story and want\n    some stories to have custom templates, use something like\n    ``select_template(['story_%s_detail.html' % story.id,\n    'story_detail.html'])``. That'll allow you to use a custom template for an\n    individual story, with a fallback template for stories that don't have\n    custom templates.\n\nIt's possible -- and preferable -- to organize templates in subdirectories\ninside each directory containing templates. The convention is to make a\nsubdirectory for each Django app, with subdirectories within those\nsubdirectories as needed.\n\nDo this for your own sanity. Storing all templates in the root level of a\nsingle directory gets messy.\n\nTo load a template that's within a subdirectory, use a slash, like so::\n\n    get_template('news/story_detail.html')\n\nUsing the same :setting:`TEMPLATES` option as above, this will attempt to load\nthe following templates:\n\n* ``/home/html/example.com/news/story_detail.html`` (``'django'`` engine)\n* ``/home/html/default/news/story_detail.html`` (``'django'`` engine)\n* ``/home/html/jinja2/news/story_detail.html`` (``'jinja2'`` engine)\n\n.. currentmodule:: django.template.loader\n\nIn addition, to cut down on the repetitive nature of loading and rendering\ntemplates, Django provides a shortcut function which automates the process.\n\n.. function:: render_to_string(template_name, context=None, request=None, using=None)\n\n    ``render_to_string()`` loads a template like :func:`get_template` and\n    calls its ``render()`` method immediately. It takes the following\n    arguments.\n\n    ``template_name``\n        The name of the template to load and render. If it's a list of template\n        names, Django uses :func:`select_template` instead of\n        :func:`get_template` to find the template.\n\n    ``context``\n        A :class:`dict` to be used as the template's context for rendering.\n\n    ``request``\n        An optional :class:`~django.http.HttpRequest` that will be available\n        during the template's rendering process.\n\n    ``using``\n        An optional template engine :setting:`NAME <TEMPLATES-NAME>`. The\n        search for the template will be restricted to that engine.\n\n    Usage example::\n\n        from django.template.loader import render_to_string\n        rendered = render_to_string('my_template.html', {'foo': 'bar'})\n\nSee also the :func:`~django.shortcuts.render()` shortcut which calls\n:func:`render_to_string()` and feeds the result into an\n:class:`~django.http.HttpResponse` suitable for returning from a view.\n\nFinally, you can use configured engines directly:\n\n.. data:: engines\n\n    Template engines are available in ``django.template.engines``::\n\n        from django.template import engines\n\n        django_engine = engines['django']\n        template = django_engine.from_string(\"Hello {{ name }}!\")\n\n    The lookup key — ``'django'`` in this example — is the engine's\n    :setting:`NAME <TEMPLATES-NAME>`.\n\n.. module:: django.template.backends\n\nBuilt-in backends\n-----------------\n\n.. module:: django.template.backends.django\n\n.. class:: DjangoTemplates\n\nSet :setting:`BACKEND <TEMPLATES-BACKEND>` to\n``'django.template.backends.django.DjangoTemplates'`` to configure a Django\ntemplate engine.\n\nWhen :setting:`APP_DIRS <TEMPLATES-APP_DIRS>` is ``True``, ``DjangoTemplates``\nengines look for templates in the ``templates`` subdirectory of installed\napplications. This generic name was kept for backwards-compatibility.\n\n``DjangoTemplates`` engines accept the following :setting:`OPTIONS\n<TEMPLATES-OPTIONS>`:\n\n* ``'autoescape'``: a boolean that controls whether HTML autoescaping is\n  enabled.\n\n  It defaults to ``True``.\n\n  .. warning::\n\n      Only set it to ``False`` if you're rendering non-HTML templates!\n\n* ``'context_processors'``: a list of dotted Python paths to callables that\n  are used to populate the context when a template is rendered with a request.\n  These callables take a request object as their argument and return a\n  :class:`dict` of items to be merged into the context.\n\n  It defaults to an empty list.\n\n  See :class:`~django.template.RequestContext` for more information.\n\n* ``'debug'``: a boolean that turns on/off template debug mode. If it is\n  ``True``, the fancy error page will display a detailed report for any\n  exception raised during template rendering. This report contains the\n  relevant snippet of the template with the appropriate line highlighted.\n\n  It defaults to the value of the :setting:`DEBUG` setting.\n\n* ``'loaders'``: a list of dotted Python paths to template loader classes.\n  Each ``Loader`` class knows how to import templates from a particular\n  source. Optionally, a tuple can be used instead of a string. The first item\n  in the tuple should be the ``Loader`` class name, and subsequent items are\n  passed to the ``Loader`` during initialization.\n\n  The default depends on the values of :setting:`DIRS <TEMPLATES-DIRS>` and\n  :setting:`APP_DIRS <TEMPLATES-APP_DIRS>`.\n\n  See :ref:`template-loaders` for details.\n\n* ``'string_if_invalid'``: the output, as a string, that the template system\n  should use for invalid (e.g. misspelled) variables.\n\n  It defaults to an empty string.\n\n  See :ref:`invalid-template-variables` for details.\n\n* ``'file_charset'``: the charset used to read template files on disk.\n\n  It defaults to ``'utf-8'``.\n\n* ``'libraries'``: A dictionary of labels and dotted Python paths of template\n  tag modules to register with the template engine. This can be used to add\n  new libraries or provide alternate labels for existing ones. For example::\n\n      OPTIONS={\n          'libraries': {\n              'myapp_tags': 'path.to.myapp.tags',\n              'admin.urls': 'django.contrib.admin.templatetags.admin_urls',\n          },\n      }\n\n  Libraries can be loaded by passing the corresponding dictionary key to\n  the :ttag:`{% load %}<load>` tag.\n\n* ``'builtins'``: A list of dotted Python paths of template tag modules to\n  add to :doc:`built-ins </ref/templates/builtins>`. For example::\n\n      OPTIONS={\n          'builtins': ['myapp.builtins'],\n      }\n\n  Tags and filters from built-in libraries can be used without first calling\n  the :ttag:`{% load %} <load>` tag.\n\n.. module:: django.template.backends.jinja2\n\n.. class:: Jinja2\n\nRequires Jinja2_ to be installed:\n\n.. console::\n\n    $ python -m pip install Jinja2\n\nSet :setting:`BACKEND <TEMPLATES-BACKEND>` to\n``'django.template.backends.jinja2.Jinja2'`` to configure a Jinja2_ engine.\n\nWhen :setting:`APP_DIRS <TEMPLATES-APP_DIRS>` is ``True``, ``Jinja2`` engines\nlook for templates in the ``jinja2`` subdirectory of installed applications.\n\nThe most important entry in :setting:`OPTIONS <TEMPLATES-OPTIONS>` is\n``'environment'``. It's a dotted Python path to a callable returning a Jinja2\nenvironment. It defaults to ``'jinja2.Environment'``. Django invokes that\ncallable and passes other options as keyword arguments. Furthermore, Django\nadds defaults that differ from Jinja2's for a few options:\n\n* ``'autoescape'``: ``True``\n* ``'loader'``: a loader configured for :setting:`DIRS <TEMPLATES-DIRS>` and\n  :setting:`APP_DIRS <TEMPLATES-APP_DIRS>`\n* ``'auto_reload'``: ``settings.DEBUG``\n* ``'undefined'``: ``DebugUndefined if settings.DEBUG else Undefined``\n\n``Jinja2`` engines also accept the following :setting:`OPTIONS\n<TEMPLATES-OPTIONS>`:\n\n* ``'context_processors'``: a list of dotted Python paths to callables that\n  are used to populate the context when a template is rendered with a request.\n  These callables take a request object as their argument and return a\n  :class:`dict` of items to be merged into the context.\n\n  It defaults to an empty list.\n\n  .. admonition:: Using context processors with Jinja2 templates is discouraged.\n\n    Context processors are useful with Django templates because Django templates\n    don't support calling functions with arguments. Since Jinja2 doesn't have\n    that limitation, it's recommended to put the function that you would use as a\n    context processor in the global variables available to the template using\n    ``jinja2.Environment`` as described below. You can then call that function in\n    the template:\n\n    .. code-block:: jinja\n\n      {{ function(request) }}\n\n    Some Django templates context processors return a fixed value. For Jinja2\n    templates, this layer of indirection isn't necessary since you can add\n    constants directly in ``jinja2.Environment``.\n\n    The original use case for adding context processors for Jinja2 involved:\n\n    * Making an expensive computation that depends on the request.\n    * Needing the result in every template.\n    * Using the result multiple times in each template.\n\n    Unless all of these conditions are met, passing a function to the template is\n    more in line with the design of Jinja2.\n\nThe default configuration is purposefully kept to a minimum. If a template is\nrendered with a request (e.g. when using :py:func:`~django.shortcuts.render`),\nthe ``Jinja2`` backend adds the globals ``request``, ``csrf_input``, and\n``csrf_token`` to the context. Apart from that, this backend doesn't create a\nDjango-flavored environment. It doesn't know about Django filters and tags.\nIn order to use Django-specific APIs, you must configure them into the\nenvironment.\n\nFor example, you can create ``myproject/jinja2.py`` with this content::\n\n    from django.templatetags.static import static\n    from django.urls import reverse\n\n    from jinja2 import Environment\n\n\n    def environment(**options):\n        env = Environment(**options)\n        env.globals.update({\n            'static': static,\n            'url': reverse,\n        })\n        return env\n\nand set the ``'environment'`` option to ``'myproject.jinja2.environment'``.\n\nThen you could use the following constructs in Jinja2 templates:\n\n.. code-block:: html+jinja\n\n    <img src=\"{{ static('path/to/company-logo.png') }}\" alt=\"Company Logo\">\n\n    <a href=\"{{ url('admin:index') }}\">Administration</a>\n\nThe concepts of tags and filters exist both in the Django template language\nand in Jinja2 but they're used differently. Since Jinja2 supports passing\narguments to callables in templates, many features that require a template tag\nor filter in Django templates can be achieved by calling a function in Jinja2\ntemplates, as shown in the example above. Jinja2's global namespace removes the\nneed for template context processors. The Django template language doesn't have\nan equivalent of Jinja2 tests.\n\n.. _Jinja2: https://jinja.palletsprojects.com/\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":268,"nodeType":"Package","repoName":null,"name":"docs/topics/db/examples","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":269,"nodeType":"TextFile","repoName":null,"name":"many_to_one.txt","path":"docs/topics/db/examples","text":"=========================\nMany-to-one relationships\n=========================\n\nTo define a many-to-one relationship, use :class:`~django.db.models.ForeignKey`::\n\n    from django.db import models\n\n    class Reporter(models.Model):\n        first_name = models.CharField(max_length=30)\n        last_name = models.CharField(max_length=30)\n        email = models.EmailField()\n\n        def __str__(self):\n            return \"%s %s\" % (self.first_name, self.last_name)\n\n    class Article(models.Model):\n        headline = models.CharField(max_length=100)\n        pub_date = models.DateField()\n        reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)\n\n        def __str__(self):\n            return self.headline\n\n        class Meta:\n            ordering = ['headline']\n\nWhat follows are examples of operations that can be performed using the Python\nAPI facilities.\n\n.. highlight:: pycon\n\nCreate a few Reporters::\n\n    >>> r = Reporter(first_name='John', last_name='Smith', email='john@example.com')\n    >>> r.save()\n\n    >>> r2 = Reporter(first_name='Paul', last_name='Jones', email='paul@example.com')\n    >>> r2.save()\n\nCreate an Article::\n\n    >>> from datetime import date\n    >>> a = Article(id=None, headline=\"This is a test\", pub_date=date(2005, 7, 27), reporter=r)\n    >>> a.save()\n\n    >>> a.reporter.id\n    1\n\n    >>> a.reporter\n    <Reporter: John Smith>\n\nNote that you must save an object before it can be assigned to a foreign key\nrelationship. For example, creating an ``Article`` with unsaved ``Reporter``\nraises ``ValueError``::\n\n    >>> r3 = Reporter(first_name='John', last_name='Smith', email='john@example.com')\n    >>> Article.objects.create(headline=\"This is a test\", pub_date=date(2005, 7, 27), reporter=r3)\n    Traceback (most recent call last):\n    ...\n    ValueError: save() prohibited to prevent data loss due to unsaved related object 'reporter'.\n\nArticle objects have access to their related Reporter objects::\n\n    >>> r = a.reporter\n\nCreate an Article via the Reporter object::\n\n    >>> new_article = r.article_set.create(headline=\"John's second story\", pub_date=date(2005, 7, 29))\n    >>> new_article\n    <Article: John's second story>\n    >>> new_article.reporter\n    <Reporter: John Smith>\n    >>> new_article.reporter.id\n    1\n\nCreate a new article::\n\n    >>> new_article2 = Article.objects.create(headline=\"Paul's story\", pub_date=date(2006, 1, 17), reporter=r)\n    >>> new_article2.reporter\n    <Reporter: John Smith>\n    >>> new_article2.reporter.id\n    1\n    >>> r.article_set.all()\n    <QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>\n\nAdd the same article to a different article set - check that it moves::\n\n    >>> r2.article_set.add(new_article2)\n    >>> new_article2.reporter.id\n    2\n    >>> new_article2.reporter\n    <Reporter: Paul Jones>\n\nAdding an object of the wrong type raises TypeError::\n\n    >>> r.article_set.add(r2)\n    Traceback (most recent call last):\n    ...\n    TypeError: 'Article' instance expected, got <Reporter: Paul Jones>\n\n    >>> r.article_set.all()\n    <QuerySet [<Article: John's second story>, <Article: This is a test>]>\n    >>> r2.article_set.all()\n    <QuerySet [<Article: Paul's story>]>\n\n    >>> r.article_set.count()\n    2\n\n    >>> r2.article_set.count()\n    1\n\nNote that in the last example the article has moved from John to Paul.\n\nRelated managers support field lookups as well.\nThe API automatically follows relationships as far as you need.\nUse double underscores to separate relationships.\nThis works as many levels deep as you want. There's no limit. For example::\n\n    >>> r.article_set.filter(headline__startswith='This')\n    <QuerySet [<Article: This is a test>]>\n\n    # Find all Articles for any Reporter whose first name is \"John\".\n    >>> Article.objects.filter(reporter__first_name='John')\n    <QuerySet [<Article: John's second story>, <Article: This is a test>]>\n\nExact match is implied here::\n\n    >>> Article.objects.filter(reporter__first_name='John')\n    <QuerySet [<Article: John's second story>, <Article: This is a test>]>\n\nQuery twice over the related field. This translates to an AND condition in the\nWHERE clause::\n\n    >>> Article.objects.filter(reporter__first_name='John', reporter__last_name='Smith')\n    <QuerySet [<Article: John's second story>, <Article: This is a test>]>\n\nFor the related lookup you can supply a primary key value or pass the related\nobject explicitly::\n\n    >>> Article.objects.filter(reporter__pk=1)\n    <QuerySet [<Article: John's second story>, <Article: This is a test>]>\n    >>> Article.objects.filter(reporter=1)\n    <QuerySet [<Article: John's second story>, <Article: This is a test>]>\n    >>> Article.objects.filter(reporter=r)\n    <QuerySet [<Article: John's second story>, <Article: This is a test>]>\n\n    >>> Article.objects.filter(reporter__in=[1,2]).distinct()\n    <QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>\n    >>> Article.objects.filter(reporter__in=[r,r2]).distinct()\n    <QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>\n\nYou can also use a queryset instead of a literal list of instances::\n\n    >>> Article.objects.filter(reporter__in=Reporter.objects.filter(first_name='John')).distinct()\n    <QuerySet [<Article: John's second story>, <Article: This is a test>]>\n\nQuerying in the opposite direction::\n\n    >>> Reporter.objects.filter(article__pk=1)\n    <QuerySet [<Reporter: John Smith>]>\n    >>> Reporter.objects.filter(article=1)\n    <QuerySet [<Reporter: John Smith>]>\n    >>> Reporter.objects.filter(article=a)\n    <QuerySet [<Reporter: John Smith>]>\n\n    >>> Reporter.objects.filter(article__headline__startswith='This')\n    <QuerySet [<Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>]>\n    >>> Reporter.objects.filter(article__headline__startswith='This').distinct()\n    <QuerySet [<Reporter: John Smith>]>\n\nCounting in the opposite direction works in conjunction with distinct()::\n\n    >>> Reporter.objects.filter(article__headline__startswith='This').count()\n    3\n    >>> Reporter.objects.filter(article__headline__startswith='This').distinct().count()\n    1\n\nQueries can go round in circles::\n\n    >>> Reporter.objects.filter(article__reporter__first_name__startswith='John')\n    <QuerySet [<Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>]>\n    >>> Reporter.objects.filter(article__reporter__first_name__startswith='John').distinct()\n    <QuerySet [<Reporter: John Smith>]>\n    >>> Reporter.objects.filter(article__reporter=r).distinct()\n    <QuerySet [<Reporter: John Smith>]>\n\nIf you delete a reporter, his articles will be deleted (assuming that the\nForeignKey was defined with :attr:`django.db.models.ForeignKey.on_delete` set to\n``CASCADE``, which is the default)::\n\n    >>> Article.objects.all()\n    <QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>\n    >>> Reporter.objects.order_by('first_name')\n    <QuerySet [<Reporter: John Smith>, <Reporter: Paul Jones>]>\n    >>> r2.delete()\n    >>> Article.objects.all()\n    <QuerySet [<Article: John's second story>, <Article: This is a test>]>\n    >>> Reporter.objects.order_by('first_name')\n    <QuerySet [<Reporter: John Smith>]>\n\nYou can delete using a JOIN in the query::\n\n    >>> Reporter.objects.filter(article__headline__startswith='This').delete()\n    >>> Reporter.objects.all()\n    <QuerySet []>\n    >>> Article.objects.all()\n    <QuerySet []>\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":270,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/topics/db/examples","text":"========================================\nExamples of model relationship API usage\n========================================\n\n.. toctree::\n   :maxdepth: 1\n\n   many_to_many\n   many_to_one\n   one_to_one\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":271,"nodeType":"TextFile","repoName":null,"name":"one_to_one.txt","path":"docs/topics/db/examples","text":"========================\nOne-to-one relationships\n========================\n\nTo define a one-to-one relationship, use\n:class:`~django.db.models.OneToOneField`.\n\nIn this example, a ``Place`` optionally can be a ``Restaurant``::\n\n    from django.db import models\n\n    class Place(models.Model):\n        name = models.CharField(max_length=50)\n        address = models.CharField(max_length=80)\n\n        def __str__(self):\n            return \"%s the place\" % self.name\n\n    class Restaurant(models.Model):\n        place = models.OneToOneField(\n            Place,\n            on_delete=models.CASCADE,\n            primary_key=True,\n        )\n        serves_hot_dogs = models.BooleanField(default=False)\n        serves_pizza = models.BooleanField(default=False)\n\n        def __str__(self):\n            return \"%s the restaurant\" % self.place.name\n\n    class Waiter(models.Model):\n        restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)\n        name = models.CharField(max_length=50)\n\n        def __str__(self):\n            return \"%s the waiter at %s\" % (self.name, self.restaurant)\n\nWhat follows are examples of operations that can be performed using the Python\nAPI facilities.\n\n.. highlight:: pycon\n\nCreate a couple of Places::\n\n    >>> p1 = Place(name='Demon Dogs', address='944 W. Fullerton')\n    >>> p1.save()\n    >>> p2 = Place(name='Ace Hardware', address='1013 N. Ashland')\n    >>> p2.save()\n\nCreate a Restaurant. Pass the \"parent\" object as this object's primary key::\n\n    >>> r = Restaurant(place=p1, serves_hot_dogs=True, serves_pizza=False)\n    >>> r.save()\n\nA Restaurant can access its place::\n\n    >>> r.place\n    <Place: Demon Dogs the place>\n\nA Place can access its restaurant, if available::\n\n    >>> p1.restaurant\n    <Restaurant: Demon Dogs the restaurant>\n\np2 doesn't have an associated restaurant::\n\n    >>> from django.core.exceptions import ObjectDoesNotExist\n    >>> try:\n    >>>     p2.restaurant\n    >>> except ObjectDoesNotExist:\n    >>>     print(\"There is no restaurant here.\")\n    There is no restaurant here.\n\nYou can also use ``hasattr`` to avoid the need for exception catching::\n\n    >>> hasattr(p2, 'restaurant')\n    False\n\nSet the place using assignment notation. Because place is the primary key on\nRestaurant, the save will create a new restaurant::\n\n    >>> r.place = p2\n    >>> r.save()\n    >>> p2.restaurant\n    <Restaurant: Ace Hardware the restaurant>\n    >>> r.place\n    <Place: Ace Hardware the place>\n\nSet the place back again, using assignment in the reverse direction::\n\n    >>> p1.restaurant = r\n    >>> p1.restaurant\n    <Restaurant: Demon Dogs the restaurant>\n\nNote that you must save an object before it can be assigned to a one-to-one\nrelationship. For example, creating a ``Restaurant`` with unsaved ``Place``\nraises ``ValueError``::\n\n    >>> p3 = Place(name='Demon Dogs', address='944 W. Fullerton')\n    >>> Restaurant.objects.create(place=p3, serves_hot_dogs=True, serves_pizza=False)\n    Traceback (most recent call last):\n    ...\n    ValueError: save() prohibited to prevent data loss due to unsaved related object 'place'.\n\nRestaurant.objects.all() returns the Restaurants, not the Places. Note that\nthere are two restaurants - Ace Hardware the Restaurant was created in the call\nto r.place = p2::\n\n    >>> Restaurant.objects.all()\n    <QuerySet [<Restaurant: Demon Dogs the restaurant>, <Restaurant: Ace Hardware the restaurant>]>\n\nPlace.objects.all() returns all Places, regardless of whether they have\nRestaurants::\n\n    >>> Place.objects.order_by('name')\n    <QuerySet [<Place: Ace Hardware the place>, <Place: Demon Dogs the place>]>\n\nYou can query the models using :ref:`lookups across relationships <lookups-that-span-relationships>`::\n\n    >>> Restaurant.objects.get(place=p1)\n    <Restaurant: Demon Dogs the restaurant>\n    >>> Restaurant.objects.get(place__pk=1)\n    <Restaurant: Demon Dogs the restaurant>\n    >>> Restaurant.objects.filter(place__name__startswith=\"Demon\")\n    <QuerySet [<Restaurant: Demon Dogs the restaurant>]>\n    >>> Restaurant.objects.exclude(place__address__contains=\"Ashland\")\n    <QuerySet [<Restaurant: Demon Dogs the restaurant>]>\n\nThis also works in reverse::\n\n    >>> Place.objects.get(pk=1)\n    <Place: Demon Dogs the place>\n    >>> Place.objects.get(restaurant__place=p1)\n    <Place: Demon Dogs the place>\n    >>> Place.objects.get(restaurant=r)\n    <Place: Demon Dogs the place>\n    >>> Place.objects.get(restaurant__place__name__startswith=\"Demon\")\n    <Place: Demon Dogs the place>\n\nAdd a Waiter to the Restaurant::\n\n    >>> w = r.waiter_set.create(name='Joe')\n    >>> w\n    <Waiter: Joe the waiter at Demon Dogs the restaurant>\n\nQuery the waiters::\n\n    >>> Waiter.objects.filter(restaurant__place=p1)\n    <QuerySet [<Waiter: Joe the waiter at Demon Dogs the restaurant>]>\n    >>> Waiter.objects.filter(restaurant__place__name__startswith=\"Demon\")\n    <QuerySet [<Waiter: Joe the waiter at Demon Dogs the restaurant>]>\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":272,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/topics/db","text":"====================\nModels and databases\n====================\n\n.. module:: django.db\n\nA model is the single, definitive source of data about your data. It contains\nthe essential fields and behaviors of the data you're storing. Generally, each\nmodel maps to a single database table.\n\n.. toctree::\n   :maxdepth: 1\n\n   models\n   queries\n   aggregation\n   search\n   managers\n   sql\n   transactions\n   multi-db\n   tablespaces\n   optimization\n   instrumentation\n   examples/index\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":273,"nodeType":"TextFile","repoName":null,"name":"files.txt","path":"docs/topics","text":"==============\nManaging files\n==============\n\nThis document describes Django's file access APIs for files such as those\nuploaded by a user. The lower level APIs are general enough that you could use\nthem for other purposes. If you want to handle \"static files\" (JS, CSS, etc.),\nsee :doc:`/howto/static-files/index`.\n\nBy default, Django stores files locally, using the :setting:`MEDIA_ROOT` and\n:setting:`MEDIA_URL` settings. The examples below assume that you're using these\ndefaults.\n\nHowever, Django provides ways to write custom `file storage systems`_ that\nallow you to completely customize where and how Django stores files. The\nsecond half of this document describes how these storage systems work.\n\n.. _file storage systems: `File storage`_\n\nUsing files in models\n=====================\n\nWhen you use a :class:`~django.db.models.FileField` or\n:class:`~django.db.models.ImageField`, Django provides a set of APIs you can use\nto deal with that file.\n\nConsider the following model, using an :class:`~django.db.models.ImageField` to\nstore a photo::\n\n    from django.db import models\n\n    class Car(models.Model):\n        name = models.CharField(max_length=255)\n        price = models.DecimalField(max_digits=5, decimal_places=2)\n        photo = models.ImageField(upload_to='cars')\n\nAny ``Car`` instance will have a ``photo`` attribute that you can use to get at\nthe details of the attached photo::\n\n    >>> car = Car.objects.get(name=\"57 Chevy\")\n    >>> car.photo\n    <ImageFieldFile: cars/chevy.jpg>\n    >>> car.photo.name\n    'cars/chevy.jpg'\n    >>> car.photo.path\n    '/media/cars/chevy.jpg'\n    >>> car.photo.url\n    'http://media.example.com/cars/chevy.jpg'\n\nThis object -- ``car.photo`` in the example -- is a ``File`` object, which means\nit has all the methods and attributes described below.\n\n.. note::\n    The file is saved as part of saving the model in the database, so the actual\n    file name used on disk cannot be relied on until after the model has been\n    saved.\n\nFor example, you can change the file name by setting the file's\n:attr:`~django.core.files.File.name` to a path relative to the file storage's\nlocation (:setting:`MEDIA_ROOT` if you are using the default\n:class:`~django.core.files.storage.FileSystemStorage`)::\n\n    >>> import os\n    >>> from django.conf import settings\n    >>> initial_path = car.photo.path\n    >>> car.photo.name = 'cars/chevy_ii.jpg'\n    >>> new_path = settings.MEDIA_ROOT + car.photo.name\n    >>> # Move the file on the filesystem\n    >>> os.rename(initial_path, new_path)\n    >>> car.save()\n    >>> car.photo.path\n    '/media/cars/chevy_ii.jpg'\n    >>> car.photo.path == new_path\n    True\n\n.. note::\n\n    Whilst :class:`~django.db.models.ImageField` non-image data attributes,\n    such as ``height``, ``width``, and ``size`` are available on the instance,\n    the underlying image data cannot be used without reopening the image. For\n    example::\n\n        >>> from PIL import Image\n        >>> car = Car.objects.get(name='57 Chevy')\n        >>> car.photo.width\n        191\n        >>> car.photo.height\n        287\n        >>> image = Image.open(car.photo)\n        # Raises ValueError: seek of closed file.\n        >>> car.photo.open()\n        <ImageFieldFile: cars/chevy.jpg>\n        >>> image = Image.open(car.photo)\n        >>> image\n        <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=191x287 at 0x7F99A94E9048>\n\nThe ``File`` object\n===================\n\nInternally, Django uses a :class:`django.core.files.File` instance any time it\nneeds to represent a file.\n\nMost of the time you'll use a ``File`` that Django's given you (i.e. a file\nattached to a model as above, or perhaps an uploaded file).\n\nIf you need to construct a ``File`` yourself, the easiest way is to create one\nusing a Python built-in ``file`` object::\n\n    >>> from django.core.files import File\n\n    # Create a Python file object using open()\n    >>> f = open('/path/to/hello.world', 'w')\n    >>> myfile = File(f)\n\nNow you can use any of the documented attributes and methods\nof the :class:`~django.core.files.File` class.\n\nBe aware that files created in this way are not automatically closed.\nThe following approach may be used to close files automatically::\n\n    >>> from django.core.files import File\n\n    # Create a Python file object using open() and the with statement\n    >>> with open('/path/to/hello.world', 'w') as f:\n    ...     myfile = File(f)\n    ...     myfile.write('Hello World')\n    ...\n    >>> myfile.closed\n    True\n    >>> f.closed\n    True\n\nClosing files is especially important when accessing file fields in a loop\nover a large number of objects. If files are not manually closed after\naccessing them, the risk of running out of file descriptors may arise. This\nmay lead to the following error::\n\n    OSError: [Errno 24] Too many open files\n\n\nFile storage\n============\n\nBehind the scenes, Django delegates decisions about how and where to store files\nto a file storage system. This is the object that actually understands things\nlike file systems, opening and reading files, etc.\n\nDjango's default file storage is given by the :setting:`DEFAULT_FILE_STORAGE`\nsetting; if you don't explicitly provide a storage system, this is the one that\nwill be used.\n\nSee below for details of the built-in default file storage system, and see\n:doc:`/howto/custom-file-storage` for information on writing your own file\nstorage system.\n\nStorage objects\n---------------\n\nThough most of the time you'll want to use a ``File`` object (which delegates to\nthe proper storage for that file), you can use file storage systems directly.\nYou can create an instance of some custom file storage class, or -- often more\nuseful -- you can use the global default storage system::\n\n    >>> from django.core.files.base import ContentFile\n    >>> from django.core.files.storage import default_storage\n\n    >>> path = default_storage.save('path/to/file', ContentFile(b'new content'))\n    >>> path\n    'path/to/file'\n\n    >>> default_storage.size(path)\n    11\n    >>> default_storage.open(path).read()\n    b'new content'\n\n    >>> default_storage.delete(path)\n    >>> default_storage.exists(path)\n    False\n\nSee :doc:`/ref/files/storage` for the file storage API.\n\n.. _builtin-fs-storage:\n\nThe built-in filesystem storage class\n-------------------------------------\n\nDjango ships with a :class:`django.core.files.storage.FileSystemStorage` class\nwhich implements basic local filesystem file storage.\n\nFor example, the following code will store uploaded files under\n``/media/photos`` regardless of what your :setting:`MEDIA_ROOT` setting is::\n\n    from django.core.files.storage import FileSystemStorage\n    from django.db import models\n\n    fs = FileSystemStorage(location='/media/photos')\n\n    class Car(models.Model):\n        ...\n        photo = models.ImageField(storage=fs)\n\n:doc:`Custom storage systems </howto/custom-file-storage>` work the same way:\nyou can pass them in as the ``storage`` argument to a\n:class:`~django.db.models.FileField`.\n\nUsing a callable\n----------------\n\n.. versionadded:: 3.1\n\nYou can use a callable as the :attr:`~django.db.models.FileField.storage`\nparameter for :class:`~django.db.models.FileField` or\n:class:`~django.db.models.ImageField`. This allows you to modify the used\nstorage at runtime, selecting different storages for different environments,\nfor example.\n\nYour callable will be evaluated when your models classes are loaded, and must\nreturn an instance of :class:`~django.core.files.storage.Storage`.\n\nFor example::\n\n    from django.conf import settings\n    from django.db import models\n    from .storages import MyLocalStorage, MyRemoteStorage\n\n\n    def select_storage():\n        return MyLocalStorage() if settings.DEBUG else MyRemoteStorage()\n\n\n    class MyModel(models.Model):\n        my_file = models.FileField(storage=select_storage)\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":274,"nodeType":"TextFile","repoName":null,"name":"migrations.txt","path":"docs/topics","text":"==========\nMigrations\n==========\n\n.. module:: django.db.migrations\n   :synopsis: Schema migration support for Django models\n\nMigrations are Django's way of propagating changes you make to your models\n(adding a field, deleting a model, etc.) into your database schema. They're\ndesigned to be mostly automatic, but you'll need to know when to make\nmigrations, when to run them, and the common problems you might run into.\n\nThe Commands\n============\n\nThere are several commands which you will use to interact with migrations\nand Django's handling of database schema:\n\n* :djadmin:`migrate`, which is responsible for applying and unapplying\n  migrations.\n\n* :djadmin:`makemigrations`, which is responsible for creating new migrations\n  based on the changes you have made to your models.\n\n* :djadmin:`sqlmigrate`, which displays the SQL statements for a migration.\n\n* :djadmin:`showmigrations`, which lists a project's migrations and their\n  status.\n\nYou should think of migrations as a version control system for your database\nschema. ``makemigrations`` is responsible for packaging up your model changes\ninto individual migration files - analogous to commits - and ``migrate`` is\nresponsible for applying those to your database.\n\nThe migration files for each app live in a \"migrations\" directory inside\nof that app, and are designed to be committed to, and distributed as part\nof, its codebase. You should be making them once on your development machine\nand then running the same migrations on your colleagues' machines, your\nstaging machines, and eventually your production machines.\n\n.. note::\n    It is possible to override the name of the package which contains the\n    migrations on a per-app basis by modifying the :setting:`MIGRATION_MODULES`\n    setting.\n\nMigrations will run the same way on the same dataset and produce consistent\nresults, meaning that what you see in development and staging is, under the\nsame circumstances, exactly what will happen in production.\n\nDjango will make migrations for any change to your models or fields - even\noptions that don't affect the database - as the only way it can reconstruct\na field correctly is to have all the changes in the history, and you might\nneed those options in some data migrations later on (for example, if you've\nset custom validators).\n\nBackend Support\n===============\n\nMigrations are supported on all backends that Django ships with, as well\nas any third-party backends if they have programmed in support for schema\nalteration (done via the :doc:`SchemaEditor </ref/schema-editor>` class).\n\nHowever, some databases are more capable than others when it comes to\nschema migrations; some of the caveats are covered below.\n\nPostgreSQL\n----------\n\nPostgreSQL is the most capable of all the databases here in terms of schema\nsupport.\n\nThe only caveat is that prior to PostgreSQL 11, adding columns with default\nvalues causes a full rewrite of the table, for a time proportional to its size.\nFor this reason, it's recommended you always create new columns with\n``null=True``, as this way they will be added immediately.\n\nMySQL\n-----\n\nMySQL lacks support for transactions around schema alteration operations,\nmeaning that if a migration fails to apply you will have to manually unpick\nthe changes in order to try again (it's impossible to roll back to an\nearlier point).\n\nIn addition, MySQL will fully rewrite tables for almost every schema operation\nand generally takes a time proportional to the number of rows in the table to\nadd or remove columns. On slower hardware this can be worse than a minute per\nmillion rows - adding a few columns to a table with just a few million rows\ncould lock your site up for over ten minutes.\n\nFinally, MySQL has relatively small limits on name lengths for columns, tables\nand indexes, as well as a limit on the combined size of all columns an index\ncovers. This means that indexes that are possible on other backends will\nfail to be created under MySQL.\n\nSQLite\n------\n\nSQLite has very little built-in schema alteration support, and so Django\nattempts to emulate it by:\n\n* Creating a new table with the new schema\n* Copying the data across\n* Dropping the old table\n* Renaming the new table to match the original name\n\nThis process generally works well, but it can be slow and occasionally\nbuggy. It is not recommended that you run and migrate SQLite in a\nproduction environment unless you are very aware of the risks and\nits limitations; the support Django ships with is designed to allow\ndevelopers to use SQLite on their local machines to develop less complex\nDjango projects without the need for a full database.\n\nWorkflow\n========\n\nDjango can create migrations for you. Make changes to your models - say, add a\nfield and remove a model - and then run :djadmin:`makemigrations`::\n\n    $ python manage.py makemigrations\n    Migrations for 'books':\n      books/migrations/0003_auto.py:\n        - Alter field author on book\n\nYour models will be scanned and compared to the versions currently\ncontained in your migration files, and then a new set of migrations\nwill be written out. Make sure to read the output to see what\n``makemigrations`` thinks you have changed - it's not perfect, and for\ncomplex changes it might not be detecting what you expect.\n\nOnce you have your new migration files, you should apply them to your\ndatabase to make sure they work as expected::\n\n    $ python manage.py migrate\n    Operations to perform:\n      Apply all migrations: books\n    Running migrations:\n      Rendering model states... DONE\n      Applying books.0003_auto... OK\n\nOnce the migration is applied, commit the migration and the models change\nto your version control system as a single commit - that way, when other\ndevelopers (or your production servers) check out the code, they'll\nget both the changes to your models and the accompanying migration at the\nsame time.\n\nIf you want to give the migration(s) a meaningful name instead of a generated\none, you can use the :option:`makemigrations --name` option::\n\n    $ python manage.py makemigrations --name changed_my_model your_app_label\n\nVersion control\n---------------\n\nBecause migrations are stored in version control, you'll occasionally\ncome across situations where you and another developer have both committed\na migration to the same app at the same time, resulting in two migrations\nwith the same number.\n\nDon't worry - the numbers are just there for developers' reference, Django\njust cares that each migration has a different name. Migrations specify which\nother migrations they depend on - including earlier migrations in the same\napp - in the file, so it's possible to detect when there's two new migrations\nfor the same app that aren't ordered.\n\nWhen this happens, Django will prompt you and give you some options. If it\nthinks it's safe enough, it will offer to automatically linearize the two\nmigrations for you. If not, you'll have to go in and modify the migrations\nyourself - don't worry, this isn't difficult, and is explained more in\n:ref:`migration-files` below.\n\nDependencies\n============\n\nWhile migrations are per-app, the tables and relationships implied by\nyour models are too complex to be created for one app at a time. When you make\na migration that requires something else to run - for example, you add a\n``ForeignKey`` in your ``books`` app to your ``authors`` app - the resulting\nmigration will contain a dependency on a migration in ``authors``.\n\nThis means that when you run the migrations, the ``authors`` migration runs\nfirst and creates the table the ``ForeignKey`` references, and then the migration\nthat makes the ``ForeignKey`` column runs afterwards and creates the constraint.\nIf this didn't happen, the migration would try to create the ``ForeignKey``\ncolumn without the table it's referencing existing and your database would\nthrow an error.\n\nThis dependency behavior affects most migration operations where you\nrestrict to a single app. Restricting to a single app (either in\n``makemigrations`` or ``migrate``) is a best-efforts promise, and not\na guarantee; any other apps that need to be used to get dependencies correct\nwill be.\n\nApps without migrations must not have relations (``ForeignKey``,\n``ManyToManyField``, etc.) to apps with migrations. Sometimes it may work, but\nit's not supported.\n\n.. _migration-files:\n\nMigration files\n===============\n\nMigrations are stored as an on-disk format, referred to here as\n\"migration files\". These files are actually normal Python files with an\nagreed-upon object layout, written in a declarative style.\n\nA basic migration file looks like this::\n\n    from django.db import migrations, models\n\n    class Migration(migrations.Migration):\n\n        dependencies = [('migrations', '0001_initial')]\n\n        operations = [\n            migrations.DeleteModel('Tribble'),\n            migrations.AddField('Author', 'rating', models.IntegerField(default=0)),\n        ]\n\nWhat Django looks for when it loads a migration file (as a Python module) is\na subclass of ``django.db.migrations.Migration`` called ``Migration``. It then\ninspects this object for four attributes, only two of which are used\nmost of the time:\n\n* ``dependencies``, a list of migrations this one depends on.\n* ``operations``, a list of ``Operation`` classes that define what this\n  migration does.\n\nThe operations are the key; they are a set of declarative instructions which\ntell Django what schema changes need to be made. Django scans them and\nbuilds an in-memory representation of all of the schema changes to all apps,\nand uses this to generate the SQL which makes the schema changes.\n\nThat in-memory structure is also used to work out what the differences are\nbetween your models and the current state of your migrations; Django runs\nthrough all the changes, in order, on an in-memory set of models to come\nup with the state of your models last time you ran ``makemigrations``. It\nthen uses these models to compare against the ones in your ``models.py`` files\nto work out what you have changed.\n\nYou should rarely, if ever, need to edit migration files by hand, but\nit's entirely possible to write them manually if you need to. Some of the\nmore complex operations are not autodetectable and are only available via\na hand-written migration, so don't be scared about editing them if you have to.\n\nCustom fields\n-------------\n\nYou can't modify the number of positional arguments in an already migrated\ncustom field without raising a ``TypeError``. The old migration will call the\nmodified ``__init__`` method with the old signature. So if you need a new\nargument, please create a keyword argument and add something like\n``assert 'argument_name' in kwargs`` in the constructor.\n\n.. _using-managers-in-migrations:\n\nModel managers\n--------------\n\nYou can optionally serialize managers into migrations and have them available\nin :class:`~django.db.migrations.operations.RunPython` operations. This is done\nby defining a ``use_in_migrations`` attribute on the manager class::\n\n    class MyManager(models.Manager):\n        use_in_migrations = True\n\n    class MyModel(models.Model):\n        objects = MyManager()\n\nIf you are using the :meth:`~django.db.models.from_queryset` function to\ndynamically generate a manager class, you need to inherit from the generated\nclass to make it importable::\n\n    class MyManager(MyBaseManager.from_queryset(CustomQuerySet)):\n        use_in_migrations = True\n\n    class MyModel(models.Model):\n        objects = MyManager()\n\nPlease refer to the notes about :ref:`historical-models` in migrations to see\nthe implications that come along.\n\nInitial migrations\n------------------\n\n.. attribute:: Migration.initial\n\nThe \"initial migrations\" for an app are the migrations that create the first\nversion of that app's tables. Usually an app will have one initial migration,\nbut in some cases of complex model interdependencies it may have two or more.\n\nInitial migrations are marked with an ``initial = True`` class attribute on the\nmigration class. If an ``initial`` class attribute isn't found, a migration\nwill be considered \"initial\" if it is the first migration in the app (i.e. if\nit has no dependencies on any other migration in the same app).\n\nWhen the :option:`migrate --fake-initial` option is used, these initial\nmigrations are treated specially. For an initial migration that creates one or\nmore tables (``CreateModel`` operation), Django checks that all of those tables\nalready exist in the database and fake-applies the migration if so. Similarly,\nfor an initial migration that adds one or more fields (``AddField`` operation),\nDjango checks that all of the respective columns already exist in the database\nand fake-applies the migration if so. Without ``--fake-initial``, initial\nmigrations are treated no differently from any other migration.\n\n.. _migration-history-consistency:\n\nHistory consistency\n-------------------\n\nAs previously discussed, you may need to linearize migrations manually when two\ndevelopment branches are joined. While editing migration dependencies, you can\ninadvertently create an inconsistent history state where a migration has been\napplied but some of its dependencies haven't. This is a strong indication that\nthe dependencies are incorrect, so Django will refuse to run migrations or make\nnew migrations until it's fixed. When using multiple databases, you can use the\n:meth:`allow_migrate` method of :ref:`database routers\n<topics-db-multi-db-routing>` to control which databases\n:djadmin:`makemigrations` checks for consistent history.\n\nAdding migrations to apps\n=========================\n\nNew apps come preconfigured to accept migrations, and so you can add migrations\nby running :djadmin:`makemigrations` once you've made some changes.\n\nIf your app already has models and database tables, and doesn't have migrations\nyet (for example, you created it against a previous Django version), you'll\nneed to convert it to use migrations by running::\n\n    $ python manage.py makemigrations your_app_label\n\nThis will make a new initial migration for your app. Now, run ``python\nmanage.py migrate --fake-initial``, and Django will detect that you have an\ninitial migration *and* that the tables it wants to create already exist, and\nwill mark the migration as already applied. (Without the :option:`migrate\n--fake-initial` flag, the command would error out because the tables it wants\nto create already exist.)\n\nNote that this only works given two things:\n\n* You have not changed your models since you made their tables. For migrations\n  to work, you must make the initial migration *first* and then make changes,\n  as Django compares changes against migration files, not the database.\n\n* You have not manually edited your database - Django won't be able to detect\n  that your database doesn't match your models, you'll just get errors when\n  migrations try to modify those tables.\n\n.. _reversing-migrations:\n\nReversing migrations\n====================\n\nMigrations can be reversed with :djadmin:`migrate` by passing the number of the\nprevious migration. For example, to reverse migration ``books.0003``:\n\n.. console::\n\n    $ python manage.py migrate books 0002\n    Operations to perform:\n      Target specific migration: 0002_auto, from books\n    Running migrations:\n      Rendering model states... DONE\n      Unapplying books.0003_auto... OK\n\nIf you want to reverse all migrations applied for an app, use the name\n``zero``:\n\n.. console::\n\n    $ python manage.py migrate books zero\n    Operations to perform:\n      Unapply all migrations: books\n    Running migrations:\n      Rendering model states... DONE\n      Unapplying books.0002_auto... OK\n      Unapplying books.0001_initial... OK\n\nA migration is irreversible if it contains any irreversible operations.\nAttempting to reverse such migrations will raise ``IrreversibleError``:\n\n.. console::\n\n    $ python manage.py migrate books 0002\n    Operations to perform:\n      Target specific migration: 0002_auto, from books\n    Running migrations:\n      Rendering model states... DONE\n      Unapplying books.0003_auto...Traceback (most recent call last):\n    django.db.migrations.exceptions.IrreversibleError: Operation <RunSQL  sql='DROP TABLE demo_books'> in books.0003_auto is not reversible\n\n.. _historical-models:\n\nHistorical models\n=================\n\nWhen you run migrations, Django is working from historical versions of your\nmodels stored in the migration files. If you write Python code using the\n:class:`~django.db.migrations.operations.RunPython` operation, or if you have\n``allow_migrate`` methods on your database routers, you **need to use** these\nhistorical model versions rather than importing them directly.\n\n.. warning::\n\n  If you import models directly rather than using the historical models,\n  your migrations *may work initially* but will fail in the future when you\n  try to re-run old migrations (commonly, when you set up a new installation\n  and run through all the migrations to set up the database).\n\n  This means that historical model problems may not be immediately obvious.\n  If you run into this kind of failure, it's OK to edit the migration to use\n  the historical models rather than direct imports and commit those changes.\n\nBecause it's impossible to serialize arbitrary Python code, these historical\nmodels will not have any custom methods that you have defined. They will,\nhowever, have the same fields, relationships, managers (limited to those with\n``use_in_migrations = True``) and ``Meta`` options (also versioned, so they may\nbe different from your current ones).\n\n.. warning::\n\n  This means that you will NOT have custom ``save()`` methods called on objects\n  when you access them in migrations, and you will NOT have any custom\n  constructors or instance methods. Plan appropriately!\n\nReferences to functions in field options such as ``upload_to`` and\n``limit_choices_to`` and model manager declarations with managers having\n``use_in_migrations = True`` are serialized in migrations, so the functions and\nclasses will need to be kept around for as long as there is a migration\nreferencing them. Any :doc:`custom model fields </howto/custom-model-fields>`\nwill also need to be kept, since these are imported directly by migrations.\n\nIn addition, the concrete base classes of the model are stored as pointers, so\nyou must always keep base classes around for as long as there is a migration\nthat contains a reference to them. On the plus side, methods and managers from\nthese base classes inherit normally, so if you absolutely need access to these\nyou can opt to move them into a superclass.\n\nTo remove old references, you can :ref:`squash migrations <migration-squashing>`\nor, if there aren't many references, copy them into the migration files.\n\n.. _migrations-removing-model-fields:\n\nConsiderations when removing model fields\n=========================================\n\nSimilar to the \"references to historical functions\" considerations described in\nthe previous section, removing custom model fields from your project or\nthird-party app will cause a problem if they are referenced in old migrations.\n\nTo help with this situation, Django provides some model field attributes to\nassist with model field deprecation using the :doc:`system checks framework\n</topics/checks>`.\n\nAdd the ``system_check_deprecated_details`` attribute to your model field\nsimilar to the following::\n\n    class IPAddressField(Field):\n        system_check_deprecated_details = {\n            'msg': (\n                'IPAddressField has been deprecated. Support for it (except '\n                'in historical migrations) will be removed in Django 1.9.'\n            ),\n            'hint': 'Use GenericIPAddressField instead.',  # optional\n            'id': 'fields.W900',  # pick a unique ID for your field.\n        }\n\nAfter a deprecation period of your choosing (two or three feature releases for\nfields in Django itself), change the ``system_check_deprecated_details``\nattribute to ``system_check_removed_details`` and update the dictionary similar\nto::\n\n    class IPAddressField(Field):\n        system_check_removed_details = {\n            'msg': (\n                'IPAddressField has been removed except for support in '\n                'historical migrations.'\n            ),\n            'hint': 'Use GenericIPAddressField instead.',\n            'id': 'fields.E900',  # pick a unique ID for your field.\n        }\n\nYou should keep the field's methods that are required for it to operate in\ndatabase migrations such as ``__init__()``, ``deconstruct()``, and\n``get_internal_type()``. Keep this stub field for as long as any migrations\nwhich reference the field exist. For example, after squashing migrations and\nremoving the old ones, you should be able to remove the field completely.\n\n.. _data-migrations:\n\nData Migrations\n===============\n\nAs well as changing the database schema, you can also use migrations to change\nthe data in the database itself, in conjunction with the schema if you want.\n\nMigrations that alter data are usually called \"data migrations\"; they're best\nwritten as separate migrations, sitting alongside your schema migrations.\n\nDjango can't automatically generate data migrations for you, as it does with\nschema migrations, but it's not very hard to write them. Migration files in\nDjango are made up of :doc:`Operations </ref/migration-operations>`, and\nthe main operation you use for data migrations is\n:class:`~django.db.migrations.operations.RunPython`.\n\nTo start, make an empty migration file you can work from (Django will put\nthe file in the right place, suggest a name, and add dependencies for you)::\n\n    python manage.py makemigrations --empty yourappname\n\nThen, open up the file; it should look something like this::\n\n    # Generated by Django A.B on YYYY-MM-DD HH:MM\n    from django.db import migrations\n\n    class Migration(migrations.Migration):\n\n        dependencies = [\n            ('yourappname', '0001_initial'),\n        ]\n\n        operations = [\n        ]\n\nNow, all you need to do is create a new function and have\n:class:`~django.db.migrations.operations.RunPython` use it.\n:class:`~django.db.migrations.operations.RunPython` expects a callable as its argument\nwhich takes two arguments - the first is an :doc:`app registry\n</ref/applications/>` that has the historical versions of all your models\nloaded into it to match where in your history the migration sits, and the\nsecond is a :doc:`SchemaEditor </ref/schema-editor>`, which you can use to\nmanually effect database schema changes (but beware, doing this can confuse\nthe migration autodetector!)\n\nLet's write a migration that populates our new ``name`` field with the combined\nvalues of ``first_name`` and ``last_name`` (we've come to our senses and\nrealized that not everyone has first and last names). All we need to do is use\nthe historical model and iterate over the rows::\n\n    from django.db import migrations\n\n    def combine_names(apps, schema_editor):\n        # We can't import the Person model directly as it may be a newer\n        # version than this migration expects. We use the historical version.\n        Person = apps.get_model('yourappname', 'Person')\n        for person in Person.objects.all():\n            person.name = '%s %s' % (person.first_name, person.last_name)\n            person.save()\n\n    class Migration(migrations.Migration):\n\n        dependencies = [\n            ('yourappname', '0001_initial'),\n        ]\n\n        operations = [\n            migrations.RunPython(combine_names),\n        ]\n\nOnce that's done, we can run ``python manage.py migrate`` as normal and the\ndata migration will run in place alongside other migrations.\n\nYou can pass a second callable to\n:class:`~django.db.migrations.operations.RunPython` to run whatever logic you\nwant executed when migrating backwards. If this callable is omitted, migrating\nbackwards will raise an exception.\n\nAccessing models from other apps\n--------------------------------\n\nWhen writing a ``RunPython`` function that uses models from apps other than the\none in which the migration is located, the migration's ``dependencies``\nattribute should include the latest migration of each app that is involved,\notherwise you may get an error similar to: ``LookupError: No installed app\nwith label 'myappname'`` when you try to retrieve the model in the ``RunPython``\nfunction using ``apps.get_model()``.\n\nIn the following example, we have a migration in ``app1`` which needs to use\nmodels in ``app2``. We aren't concerned with the details of ``move_m1`` other\nthan the fact it will need to access models from both apps. Therefore we've\nadded a dependency that specifies the last migration of ``app2``::\n\n    class Migration(migrations.Migration):\n\n        dependencies = [\n            ('app1', '0001_initial'),\n            # added dependency to enable using models from app2 in move_m1\n            ('app2', '0004_foobar'),\n        ]\n\n        operations = [\n            migrations.RunPython(move_m1),\n        ]\n\nMore advanced migrations\n------------------------\n\nIf you're interested in the more advanced migration operations, or want\nto be able to write your own, see the :doc:`migration operations reference\n</ref/migration-operations>` and the \"how-to\" on :doc:`writing migrations\n</howto/writing-migrations>`.\n\n.. _migration-squashing:\n\nSquashing migrations\n====================\n\nYou are encouraged to make migrations freely and not worry about how many you\nhave; the migration code is optimized to deal with hundreds at a time without\nmuch slowdown. However, eventually you will want to move back from having\nseveral hundred migrations to just a few, and that's where squashing comes in.\n\nSquashing is the act of reducing an existing set of many migrations down to\none (or sometimes a few) migrations which still represent the same changes.\n\nDjango does this by taking all of your existing migrations, extracting their\n``Operation``\\s and putting them all in sequence, and then running an optimizer\nover them to try and reduce the length of the list - for example, it knows\nthat :class:`~django.db.migrations.operations.CreateModel` and\n:class:`~django.db.migrations.operations.DeleteModel` cancel each other out,\nand it knows that :class:`~django.db.migrations.operations.AddField` can be\nrolled into :class:`~django.db.migrations.operations.CreateModel`.\n\nOnce the operation sequence has been reduced as much as possible - the amount\npossible depends on how closely intertwined your models are and if you have\nany :class:`~django.db.migrations.operations.RunSQL`\nor :class:`~django.db.migrations.operations.RunPython` operations (which can't\nbe optimized through unless they are marked as ``elidable``) - Django will then\nwrite it back out into a new set of migration files.\n\nThese files are marked to say they replace the previously-squashed migrations,\nso they can coexist with the old migration files, and Django will intelligently\nswitch between them depending where you are in the history. If you're still\npart-way through the set of migrations that you squashed, it will keep using\nthem until it hits the end and then switch to the squashed history, while new\ninstalls will use the new squashed migration and skip all the old ones.\n\nThis enables you to squash and not mess up systems currently in production\nthat aren't fully up-to-date yet. The recommended process is to squash, keeping\nthe old files, commit and release, wait until all systems are upgraded with\nthe new release (or if you're a third-party project, ensure your users upgrade\nreleases in order without skipping any), and then remove the old files, commit\nand do a second release.\n\nThe command that backs all this is :djadmin:`squashmigrations` - pass it the\napp label and migration name you want to squash up to, and it'll get to work::\n\n  $ ./manage.py squashmigrations myapp 0004\n  Will squash the following migrations:\n   - 0001_initial\n   - 0002_some_change\n   - 0003_another_change\n   - 0004_undo_something\n  Do you wish to proceed? [yN] y\n  Optimizing...\n    Optimized from 12 operations to 7 operations.\n  Created new squashed migration /home/andrew/Programs/DjangoTest/test/migrations/0001_squashed_0004_undo_somthing.py\n    You should commit this migration but leave the old ones in place;\n    the new migration will be used for new installs. Once you are sure\n    all instances of the codebase have applied the migrations you squashed,\n    you can delete them.\n\nUse the :option:`squashmigrations --squashed-name` option if you want to set\nthe name of the squashed migration rather than use an autogenerated one.\n\nNote that model interdependencies in Django can get very complex, and squashing\nmay result in migrations that do not run; either mis-optimized (in which case\nyou can try again with ``--no-optimize``, though you should also report an issue),\nor with a ``CircularDependencyError``, in which case you can manually resolve it.\n\nTo manually resolve a ``CircularDependencyError``, break out one of\nthe ForeignKeys in the circular dependency loop into a separate\nmigration, and move the dependency on the other app with it. If you're unsure,\nsee how :djadmin:`makemigrations` deals with the problem when asked to create\nbrand new migrations from your models. In a future release of Django,\n:djadmin:`squashmigrations` will be updated to attempt to resolve these errors\nitself.\n\nOnce you've squashed your migration, you should then commit it alongside the\nmigrations it replaces and distribute this change to all running instances\nof your application, making sure that they run ``migrate`` to store the change\nin their database.\n\nYou must then transition the squashed migration to a normal migration by:\n\n- Deleting all the migration files it replaces.\n- Updating all migrations that depend on the deleted migrations to depend on\n  the squashed migration instead.\n- Removing the ``replaces`` attribute in the ``Migration`` class of the\n  squashed migration (this is how Django tells that it is a squashed migration).\n\n.. note::\n    Once you've squashed a migration, you should not then re-squash that squashed\n    migration until you have fully transitioned it to a normal migration.\n\n\n.. _migration-serializing:\n\nSerializing values\n==================\n\nMigrations are Python files containing the old definitions of your models\n- thus, to write them, Django must take the current state of your models and\nserialize them out into a file.\n\nWhile Django can serialize most things, there are some things that we just\ncan't serialize out into a valid Python representation - there's no Python\nstandard for how a value can be turned back into code (``repr()`` only works\nfor basic values, and doesn't specify import paths).\n\nDjango can serialize the following:\n\n- ``int``, ``float``, ``bool``, ``str``, ``bytes``, ``None``, ``NoneType``\n- ``list``, ``set``, ``tuple``, ``dict``, ``range``.\n- ``datetime.date``, ``datetime.time``, and ``datetime.datetime`` instances\n  (include those that are timezone-aware)\n- ``decimal.Decimal`` instances\n- ``enum.Enum`` instances\n- ``uuid.UUID`` instances\n- :func:`functools.partial` and :class:`functools.partialmethod` instances\n  which have serializable ``func``, ``args``, and ``keywords`` values.\n- ``LazyObject`` instances which wrap a serializable value.\n- Enumeration types (e.g. ``TextChoices`` or ``IntegerChoices``) instances.\n- Any Django field\n- Any function or method reference (e.g. ``datetime.datetime.today``) (must be in module's top-level scope)\n- Unbound methods used from within the class body\n- Any class reference (must be in module's top-level scope)\n- Anything with a custom ``deconstruct()`` method (:ref:`see below <custom-deconstruct-method>`)\n\nDjango cannot serialize:\n\n- Nested classes\n- Arbitrary class instances (e.g. ``MyClass(4.3, 5.7)``)\n- Lambdas\n\n.. _custom-migration-serializers:\n\nCustom serializers\n------------------\n\nYou can serialize other types by writing a custom serializer. For example, if\nDjango didn't serialize :class:`~decimal.Decimal` by default, you could do\nthis::\n\n    from decimal import Decimal\n\n    from django.db.migrations.serializer import BaseSerializer\n    from django.db.migrations.writer import MigrationWriter\n\n    class DecimalSerializer(BaseSerializer):\n        def serialize(self):\n            return repr(self.value), {'from decimal import Decimal'}\n\n    MigrationWriter.register_serializer(Decimal, DecimalSerializer)\n\nThe first argument of ``MigrationWriter.register_serializer()`` is a type or\niterable of types that should use the serializer.\n\nThe ``serialize()`` method of your serializer must return a string of how the\nvalue should appear in migrations and a set of any imports that are needed in\nthe migration.\n\n.. _custom-deconstruct-method:\n\nAdding a ``deconstruct()`` method\n---------------------------------\n\nYou can let Django serialize your own custom class instances by giving the class\na ``deconstruct()`` method. It takes no arguments, and should return a tuple\nof three things ``(path, args, kwargs)``:\n\n* ``path`` should be the Python path to the class, with the class name included\n  as the last part (for example, ``myapp.custom_things.MyClass``). If your\n  class is not available at the top level of a module it is not serializable.\n\n* ``args`` should be a list of positional arguments to pass to your class'\n  ``__init__`` method. Everything in this list should itself be serializable.\n\n* ``kwargs`` should be a dict of keyword arguments to pass to your class'\n  ``__init__`` method. Every value should itself be serializable.\n\n.. note::\n\n    This return value is different from the ``deconstruct()`` method\n    :ref:`for custom fields <custom-field-deconstruct-method>` which returns a\n    tuple of four items.\n\nDjango will write out the value as an instantiation of your class with the\ngiven arguments, similar to the way it writes out references to Django fields.\n\nTo prevent a new migration from being created each time\n:djadmin:`makemigrations` is run, you should also add a ``__eq__()`` method to\nthe decorated class. This function will be called by Django's migration\nframework to detect changes between states.\n\nAs long as all of the arguments to your class' constructor are themselves\nserializable, you can use the ``@deconstructible`` class decorator from\n``django.utils.deconstruct`` to add the ``deconstruct()`` method::\n\n    from django.utils.deconstruct import deconstructible\n\n    @deconstructible\n    class MyCustomClass:\n\n        def __init__(self, foo=1):\n            self.foo = foo\n            ...\n\n        def __eq__(self, other):\n            return self.foo == other.foo\n\n\nThe decorator adds logic to capture and preserve the arguments on their\nway into your constructor, and then returns those arguments exactly when\ndeconstruct() is called.\n\nSupporting multiple Django versions\n===================================\n\nIf you are the maintainer of a third-party app with models, you may need to\nship migrations that support multiple Django versions. In this case, you should\nalways run :djadmin:`makemigrations` **with the lowest Django version you wish\nto support**.\n\nThe migrations system will maintain backwards-compatibility according to the\nsame policy as the rest of Django, so migration files generated on Django X.Y\nshould run unchanged on Django X.Y+1. The migrations system does not promise\nforwards-compatibility, however. New features may be added, and migration files\ngenerated with newer versions of Django may not work on older versions.\n\n.. seealso::\n\n    :doc:`The Migrations Operations Reference </ref/migration-operations>`\n        Covers the schema operations API, special operations, and writing your\n        own operations.\n\n    :doc:`The Writing Migrations \"how-to\" </howto/writing-migrations>`\n        Explains how to structure and write database migrations for different\n        scenarios you might encounter.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":275,"nodeType":"Package","repoName":null,"name":"docs/topics/auth","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":276,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/topics/auth","text":"=============================\nUser authentication in Django\n=============================\n\n.. toctree::\n   :hidden:\n\n   default\n   passwords\n   customizing\n\n.. module:: django.contrib.auth\n   :synopsis: Django's authentication framework.\n\nDjango comes with a user authentication system. It handles user accounts,\ngroups, permissions and cookie-based user sessions. This section of the\ndocumentation explains how the default implementation works out of the box, as\nwell as how to :doc:`extend and customize </topics/auth/customizing>` it to\nsuit your project's needs.\n\nOverview\n========\n\nThe Django authentication system handles both authentication and authorization.\nBriefly, authentication verifies a user is who they claim to be, and\nauthorization determines what an authenticated user is allowed to do. Here the\nterm authentication is used to refer to both tasks.\n\nThe auth system consists of:\n\n* Users\n* Permissions: Binary (yes/no) flags designating whether a user may perform\n  a certain task.\n* Groups: A generic way of applying labels and permissions to more than one\n  user.\n* A configurable password hashing system\n* Forms and view tools for logging in users, or restricting content\n* A pluggable backend system\n\nThe authentication system in Django aims to be very generic and doesn't provide\nsome features commonly found in web authentication systems. Solutions for some\nof these common problems have been implemented in third-party packages:\n\n* Password strength checking\n* Throttling of login attempts\n* Authentication against third-parties (OAuth, for example)\n* Object-level permissions\n\nInstallation\n============\n\nAuthentication support is bundled as a Django contrib module in\n``django.contrib.auth``. By default, the required configuration is already\nincluded in the :file:`settings.py` generated by :djadmin:`django-admin\nstartproject <startproject>`, these consist of two items listed in your\n:setting:`INSTALLED_APPS` setting:\n\n1. ``'django.contrib.auth'`` contains the core of the authentication framework,\n   and its default models.\n2. ``'django.contrib.contenttypes'`` is the Django :doc:`content type system\n   </ref/contrib/contenttypes>`, which allows permissions to be associated with\n   models you create.\n\nand these items in your :setting:`MIDDLEWARE` setting:\n\n#. :class:`~django.contrib.sessions.middleware.SessionMiddleware` manages\n   :doc:`sessions </topics/http/sessions>` across requests.\n#. :class:`~django.contrib.auth.middleware.AuthenticationMiddleware` associates\n   users with requests using sessions.\n\nWith these settings in place, running the command ``manage.py migrate`` creates\nthe necessary database tables for auth related models and permissions for any\nmodels defined in your installed apps.\n\nUsage\n=====\n\n:doc:`Using Django's default implementation <default>`\n\n* :ref:`Working with User objects <user-objects>`\n* :ref:`Permissions and authorization <topic-authorization>`\n* :ref:`Authentication in web requests <auth-web-requests>`\n* :ref:`Managing users in the admin <auth-admin>`\n\n:doc:`API reference for the default implementation </ref/contrib/auth>`\n\n:doc:`Customizing Users and authentication <customizing>`\n\n:doc:`Password management in Django <passwords>`\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":277,"nodeType":"Package","repoName":null,"name":"docs/topics/http","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":278,"nodeType":"TextFile","repoName":null,"name":"decorators.txt","path":"docs/topics/http","text":"===============\nView decorators\n===============\n\n.. module:: django.views.decorators.http\n\nDjango provides several decorators that can be applied to views to support\nvarious HTTP features.\n\nSee :ref:`decorating-class-based-views` for how to use these decorators with\nclass-based views.\n\nAllowed HTTP methods\n====================\n\nThe decorators in :mod:`django.views.decorators.http` can be used to restrict\naccess to views based on the request method. These decorators will return\na :class:`django.http.HttpResponseNotAllowed` if the conditions are not met.\n\n.. function:: require_http_methods(request_method_list)\n\n    Decorator to require that a view only accepts particular request\n    methods. Usage::\n\n        from django.views.decorators.http import require_http_methods\n\n        @require_http_methods([\"GET\", \"POST\"])\n        def my_view(request):\n            # I can assume now that only GET or POST requests make it this far\n            # ...\n            pass\n\n    Note that request methods should be in uppercase.\n\n.. function:: require_GET()\n\n    Decorator to require that a view only accepts the GET method.\n\n.. function:: require_POST()\n\n    Decorator to require that a view only accepts the POST method.\n\n.. function:: require_safe()\n\n    Decorator to require that a view only accepts the GET and HEAD methods.\n    These methods are commonly considered \"safe\" because they should not have\n    the significance of taking an action other than retrieving the requested\n    resource.\n\n    .. note::\n        Web servers should automatically strip the content of responses to HEAD\n        requests while leaving the headers unchanged, so you may handle HEAD\n        requests exactly like GET requests in your views. Since some software,\n        such as link checkers, rely on HEAD requests, you might prefer\n        using ``require_safe`` instead of ``require_GET``.\n\nConditional view processing\n===========================\n\nThe following decorators in :mod:`django.views.decorators.http` can be used to\ncontrol caching behavior on particular views.\n\n.. function:: condition(etag_func=None, last_modified_func=None)\n\n.. function:: etag(etag_func)\n\n.. function:: last_modified(last_modified_func)\n\n    These decorators can be used to generate ``ETag`` and ``Last-Modified``\n    headers; see\n    :doc:`conditional view processing </topics/conditional-view-processing>`.\n\n.. module:: django.views.decorators.gzip\n\nGZip compression\n================\n\nThe decorators in :mod:`django.views.decorators.gzip` control content\ncompression on a per-view basis.\n\n.. function:: gzip_page()\n\n    This decorator compresses content if the browser allows gzip compression.\n    It sets the ``Vary`` header accordingly, so that caches will base their\n    storage on the ``Accept-Encoding`` header.\n\n.. module:: django.views.decorators.vary\n\nVary headers\n============\n\nThe decorators in :mod:`django.views.decorators.vary` can be used to control\ncaching based on specific request headers.\n\n.. function:: vary_on_cookie(func)\n\n.. function:: vary_on_headers(*headers)\n\n    The ``Vary`` header defines which request headers a cache mechanism should take\n    into account when building its cache key.\n\n    See :ref:`using vary headers <using-vary-headers>`.\n\n.. module:: django.views.decorators.cache\n\nCaching\n=======\n\nThe decorators in :mod:`django.views.decorators.cache` control server and\nclient-side caching.\n\n.. function:: cache_control(**kwargs)\n\n    This decorator patches the response's ``Cache-Control`` header by adding\n    all of the keyword arguments to it. See\n    :func:`~django.utils.cache.patch_cache_control` for the details of the\n    transformation.\n\n.. function:: never_cache(view_func)\n\n    This decorator adds a ``Cache-Control: max-age=0, no-cache, no-store,\n    must-revalidate, private`` header to a response to indicate that a page\n    should never be cached.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":279,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/topics/http","text":"======================\nHandling HTTP requests\n======================\n\nInformation on handling HTTP requests in Django:\n\n.. toctree::\n   :maxdepth: 1\n\n   urls\n   views\n   decorators\n   file-uploads\n   shortcuts\n   generic-views\n   middleware\n   sessions\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":280,"nodeType":"TextFile","repoName":null,"name":"shortcuts.txt","path":"docs/topics/http","text":"=========================\nDjango shortcut functions\n=========================\n\n.. module:: django.shortcuts\n   :synopsis:\n       Convenience shortcuts that span multiple levels of Django's MVC stack.\n\n.. index:: shortcuts\n\nThe package ``django.shortcuts`` collects helper functions and classes that\n\"span\" multiple levels of MVC. In other words, these functions/classes\nintroduce controlled coupling for convenience's sake.\n\n``render()``\n============\n\n.. function:: render(request, template_name, context=None, content_type=None, status=None, using=None)\n\n   Combines a given template with a given context dictionary and returns an\n   :class:`~django.http.HttpResponse` object with that rendered text.\n\n   Django does not provide a shortcut function which returns a\n   :class:`~django.template.response.TemplateResponse` because the constructor\n   of :class:`~django.template.response.TemplateResponse` offers the same level\n   of convenience as :func:`render()`.\n\nRequired arguments\n------------------\n\n``request``\n    The request object used to generate this response.\n\n``template_name``\n    The full name of a template to use or sequence of template names. If a\n    sequence is given, the first template that exists will be used. See the\n    :ref:`template loading documentation <template-loading>` for more\n    information on how templates are found.\n\nOptional arguments\n------------------\n\n``context``\n    A dictionary of values to add to the template context. By default, this\n    is an empty dictionary. If a value in the dictionary is callable, the\n    view will call it just before rendering the template.\n\n``content_type``\n    The MIME type to use for the resulting document. Defaults to\n    ``'text/html'``.\n\n``status``\n    The status code for the response. Defaults to ``200``.\n\n``using``\n    The :setting:`NAME <TEMPLATES-NAME>` of a template engine to use for\n    loading the template.\n\nExample\n-------\n\nThe following example renders the template ``myapp/index.html`` with the\nMIME type :mimetype:`application/xhtml+xml`::\n\n    from django.shortcuts import render\n\n    def my_view(request):\n        # View code here...\n        return render(request, 'myapp/index.html', {\n            'foo': 'bar',\n        }, content_type='application/xhtml+xml')\n\nThis example is equivalent to::\n\n    from django.http import HttpResponse\n    from django.template import loader\n\n    def my_view(request):\n        # View code here...\n        t = loader.get_template('myapp/index.html')\n        c = {'foo': 'bar'}\n        return HttpResponse(t.render(c, request), content_type='application/xhtml+xml')\n\n``redirect()``\n==============\n\n.. function:: redirect(to, *args, permanent=False, **kwargs)\n\n   Returns an :class:`~django.http.HttpResponseRedirect` to the appropriate URL\n   for the arguments passed.\n\n   The arguments could be:\n\n   * A model: the model's :meth:`~django.db.models.Model.get_absolute_url()`\n     function will be called.\n\n   * A view name, possibly with arguments: :func:`~django.urls.reverse` will be\n     used to reverse-resolve the name.\n\n   * An absolute or relative URL, which will be used as-is for the redirect\n     location.\n\n   By default issues a temporary redirect; pass ``permanent=True`` to issue a\n   permanent redirect.\n\nExamples\n--------\n\nYou can use the :func:`redirect` function in a number of ways.\n\n#. By passing some object; that object's\n   :meth:`~django.db.models.Model.get_absolute_url` method will be called\n   to figure out the redirect URL::\n\n        from django.shortcuts import redirect\n\n        def my_view(request):\n            ...\n            obj = MyModel.objects.get(...)\n            return redirect(obj)\n\n#. By passing the name of a view and optionally some positional or\n   keyword arguments; the URL will be reverse resolved using the\n   :func:`~django.urls.reverse` method::\n\n        def my_view(request):\n            ...\n            return redirect('some-view-name', foo='bar')\n\n#. By passing a hardcoded URL to redirect to::\n\n        def my_view(request):\n            ...\n            return redirect('/some/url/')\n\n   This also works with full URLs::\n\n        def my_view(request):\n            ...\n            return redirect('https://example.com/')\n\nBy default, :func:`redirect` returns a temporary redirect. All of the above\nforms accept a ``permanent`` argument; if set to ``True`` a permanent redirect\nwill be returned::\n\n    def my_view(request):\n        ...\n        obj = MyModel.objects.get(...)\n        return redirect(obj, permanent=True)\n\n``get_object_or_404()``\n=======================\n\n.. function:: get_object_or_404(klass, *args, **kwargs)\n\n   Calls :meth:`~django.db.models.query.QuerySet.get()` on a given model manager,\n   but it raises :class:`~django.http.Http404` instead of the model's\n   :class:`~django.db.models.Model.DoesNotExist` exception.\n\nRequired arguments\n------------------\n\n``klass``\n    A :class:`~django.db.models.Model` class,\n    a :class:`~django.db.models.Manager`,\n    or a :class:`~django.db.models.query.QuerySet` instance from which to get\n    the object.\n\n``**kwargs``\n    Lookup parameters, which should be in the format accepted by ``get()`` and\n    ``filter()``.\n\nExample\n-------\n\nThe following example gets the object with the primary key of 1 from\n``MyModel``::\n\n    from django.shortcuts import get_object_or_404\n\n    def my_view(request):\n        obj = get_object_or_404(MyModel, pk=1)\n\nThis example is equivalent to::\n\n    from django.http import Http404\n\n    def my_view(request):\n        try:\n            obj = MyModel.objects.get(pk=1)\n        except MyModel.DoesNotExist:\n            raise Http404(\"No MyModel matches the given query.\")\n\nThe most common use case is to pass a :class:`~django.db.models.Model`, as\nshown above. However, you can also pass a\n:class:`~django.db.models.query.QuerySet` instance::\n\n    queryset = Book.objects.filter(title__startswith='M')\n    get_object_or_404(queryset, pk=1)\n\nThe above example is a bit contrived since it's equivalent to doing::\n\n    get_object_or_404(Book, title__startswith='M', pk=1)\n\nbut it can be useful if you are passed the ``queryset`` variable from somewhere\nelse.\n\nFinally, you can also use a :class:`~django.db.models.Manager`. This is useful\nfor example if you have a\n:ref:`custom manager<custom-managers>`::\n\n    get_object_or_404(Book.dahl_objects, title='Matilda')\n\nYou can also use\n:class:`related managers<django.db.models.fields.related.RelatedManager>`::\n\n    author = Author.objects.get(name='Roald Dahl')\n    get_object_or_404(author.book_set, title='Matilda')\n\nNote: As with ``get()``, a\n:class:`~django.core.exceptions.MultipleObjectsReturned` exception\nwill be raised if more than one object is found.\n\n``get_list_or_404()``\n=====================\n\n.. function:: get_list_or_404(klass, *args, **kwargs)\n\n   Returns the result of :meth:`~django.db.models.query.QuerySet.filter()` on a\n   given model manager cast to a list, raising :class:`~django.http.Http404` if\n   the resulting list is empty.\n\nRequired arguments\n------------------\n\n``klass``\n    A :class:`~django.db.models.Model`, :class:`~django.db.models.Manager` or\n    :class:`~django.db.models.query.QuerySet` instance from which to get the\n    list.\n\n``**kwargs``\n    Lookup parameters, which should be in the format accepted by ``get()`` and\n    ``filter()``.\n\nExample\n-------\n\nThe following example gets all published objects from ``MyModel``::\n\n    from django.shortcuts import get_list_or_404\n\n    def my_view(request):\n        my_objects = get_list_or_404(MyModel, published=True)\n\nThis example is equivalent to::\n\n    from django.http import Http404\n\n    def my_view(request):\n        my_objects = list(MyModel.objects.filter(published=True))\n        if not my_objects:\n            raise Http404(\"No MyModel matches the given query.\")\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":281,"nodeType":"TextFile","repoName":null,"name":"optimization.txt","path":"docs/topics/db","text":"============================\nDatabase access optimization\n============================\n\nDjango's database layer provides various ways to help developers get the most\nout of their databases. This document gathers together links to the relevant\ndocumentation, and adds various tips, organized under a number of headings that\noutline the steps to take when attempting to optimize your database usage.\n\nProfile first\n=============\n\nAs general programming practice, this goes without saying. Find out :ref:`what\nqueries you are doing and what they are costing you <faq-see-raw-sql-queries>`.\nUse :meth:`.QuerySet.explain` to understand how specific ``QuerySet``\\s are\nexecuted by your database. You may also want to use an external project like\ndjango-debug-toolbar_, or a tool that monitors your database directly.\n\nRemember that you may be optimizing for speed or memory or both, depending on\nyour requirements. Sometimes optimizing for one will be detrimental to the\nother, but sometimes they will help each other. Also, work that is done by the\ndatabase process might not have the same cost (to you) as the same amount of\nwork done in your Python process. It is up to you to decide what your\npriorities are, where the balance must lie, and profile all of these as required\nsince this will depend on your application and server.\n\nWith everything that follows, remember to profile after every change to ensure\nthat the change is a benefit, and a big enough benefit given the decrease in\nreadability of your code. **All** of the suggestions below come with the caveat\nthat in your circumstances the general principle might not apply, or might even\nbe reversed.\n\n.. _django-debug-toolbar: https://github.com/jazzband/django-debug-toolbar/\n\nUse standard DB optimization techniques\n=======================================\n\n...including:\n\n* Indexes_. This is a number one priority, *after* you have determined from\n  profiling what indexes should be added. Use\n  :attr:`Meta.indexes <django.db.models.Options.indexes>` or\n  :attr:`Field.db_index <django.db.models.Field.db_index>` to add these from\n  Django. Consider adding indexes to fields that you frequently query using\n  :meth:`~django.db.models.query.QuerySet.filter()`,\n  :meth:`~django.db.models.query.QuerySet.exclude()`,\n  :meth:`~django.db.models.query.QuerySet.order_by()`, etc. as indexes may help\n  to speed up lookups. Note that determining the best indexes is a complex\n  database-dependent topic that will depend on your particular application.\n  The overhead of maintaining an index may outweigh any gains in query speed.\n\n.. _Indexes: https://en.wikipedia.org/wiki/Database_index\n\n* Appropriate use of field types.\n\nWe will assume you have done the things listed above. The rest of this document\nfocuses on how to use Django in such a way that you are not doing unnecessary\nwork. This document also does not address other optimization techniques that\napply to all expensive operations, such as :doc:`general purpose caching\n</topics/cache>`.\n\nUnderstand ``QuerySet``\\s\n=========================\n\nUnderstanding :doc:`QuerySets </ref/models/querysets>` is vital to getting good\nperformance with simple code. In particular:\n\nUnderstand ``QuerySet`` evaluation\n----------------------------------\n\nTo avoid performance problems, it is important to understand:\n\n* that :ref:`QuerySets are lazy <querysets-are-lazy>`.\n\n* when :ref:`they are evaluated <when-querysets-are-evaluated>`.\n\n* how :ref:`the data is held in memory <caching-and-querysets>`.\n\nUnderstand cached attributes\n----------------------------\n\nAs well as caching of the whole ``QuerySet``, there is caching of the result of\nattributes on ORM objects. In general, attributes that are not callable will be\ncached. For example, assuming the :ref:`example Weblog models\n<queryset-model-example>`::\n\n  >>> entry = Entry.objects.get(id=1)\n  >>> entry.blog   # Blog object is retrieved at this point\n  >>> entry.blog   # cached version, no DB access\n\nBut in general, callable attributes cause DB lookups every time::\n\n  >>> entry = Entry.objects.get(id=1)\n  >>> entry.authors.all()   # query performed\n  >>> entry.authors.all()   # query performed again\n\nBe careful when reading template code - the template system does not allow use\nof parentheses, but will call callables automatically, hiding the above\ndistinction.\n\nBe careful with your own custom properties - it is up to you to implement\ncaching when required, for example using the\n:class:`~django.utils.functional.cached_property` decorator.\n\nUse the ``with`` template tag\n-----------------------------\n\nTo make use of the caching behavior of ``QuerySet``, you may need to use the\n:ttag:`with` template tag.\n\nUse ``iterator()``\n------------------\n\nWhen you have a lot of objects, the caching behavior of the ``QuerySet`` can\ncause a large amount of memory to be used. In this case,\n:meth:`~django.db.models.query.QuerySet.iterator()` may help.\n\nUse ``explain()``\n-----------------\n\n:meth:`.QuerySet.explain` gives you detailed information about how the database\nexecutes a query, including indexes and joins that are used. These details may\nhelp you find queries that could be rewritten more efficiently, or identify\nindexes that could be added to improve performance.\n\nDo database work in the database rather than in Python\n======================================================\n\nFor instance:\n\n* At the most basic level, use :ref:`filter and exclude <queryset-api>` to do\n  filtering in the database.\n\n* Use :class:`F expressions <django.db.models.F>` to filter\n  based on other fields within the same model.\n\n* Use :doc:`annotate to do aggregation in the database\n  </topics/db/aggregation>`.\n\nIf these aren't enough to generate the SQL you need:\n\nUse ``RawSQL``\n--------------\n\nA less portable but more powerful method is the\n:class:`~django.db.models.expressions.RawSQL` expression, which allows some SQL\nto be explicitly added to the query. If that still isn't powerful enough:\n\nUse raw SQL\n-----------\n\nWrite your own :doc:`custom SQL to retrieve data or populate models\n</topics/db/sql>`. Use ``django.db.connection.queries`` to find out what Django\nis writing for you and start from there.\n\nRetrieve individual objects using a unique, indexed column\n==========================================================\n\nThere are two reasons to use a column with\n:attr:`~django.db.models.Field.unique` or\n:attr:`~django.db.models.Field.db_index` when using\n:meth:`~django.db.models.query.QuerySet.get` to retrieve individual objects.\nFirst, the query will be quicker because of the underlying database index.\nAlso, the query could run much slower if multiple objects match the lookup;\nhaving a unique constraint on the column guarantees this will never happen.\n\nSo using the :ref:`example Weblog models <queryset-model-example>`::\n\n  >>> entry = Entry.objects.get(id=10)\n\nwill be quicker than:\n\n  >>> entry = Entry.objects.get(headline=\"News Item Title\")\n\nbecause ``id`` is indexed by the database and is guaranteed to be unique.\n\nDoing the following is potentially quite slow:\n\n  >>> entry = Entry.objects.get(headline__startswith=\"News\")\n\nFirst of all, ``headline`` is not indexed, which will make the underlying\ndatabase fetch slower.\n\nSecond, the lookup doesn't guarantee that only one object will be returned.\nIf the query matches more than one object, it will retrieve and transfer all of\nthem from the database. This penalty could be substantial if hundreds or\nthousands of records are returned. The penalty will be compounded if the\ndatabase lives on a separate server, where network overhead and latency also\nplay a factor.\n\nRetrieve everything at once if you know you will need it\n========================================================\n\nHitting the database multiple times for different parts of a single 'set' of\ndata that you will need all parts of is, in general, less efficient than\nretrieving it all in one query. This is particularly important if you have a\nquery that is executed in a loop, and could therefore end up doing many database\nqueries, when only one was needed. So:\n\nUse ``QuerySet.select_related()`` and ``prefetch_related()``\n------------------------------------------------------------\n\nUnderstand :meth:`~django.db.models.query.QuerySet.select_related` and\n:meth:`~django.db.models.query.QuerySet.prefetch_related` thoroughly, and use\nthem:\n\n* in :doc:`managers and default managers </topics/db/managers>` where\n  appropriate. Be aware when your manager is and is not used; sometimes this is\n  tricky so don't make assumptions.\n\n* in view code or other layers, possibly making use of\n  :func:`~django.db.models.prefetch_related_objects` where needed.\n\nDon't retrieve things you don't need\n====================================\n\nUse ``QuerySet.values()`` and ``values_list()``\n-----------------------------------------------\n\nWhen you only want a ``dict`` or ``list`` of values, and don't need ORM model\nobjects, make appropriate usage of\n:meth:`~django.db.models.query.QuerySet.values()`.\nThese can be useful for replacing model objects in template code - as long as\nthe dicts you supply have the same attributes as those used in the template,\nyou are fine.\n\nUse ``QuerySet.defer()`` and ``only()``\n---------------------------------------\n\nUse :meth:`~django.db.models.query.QuerySet.defer()` and\n:meth:`~django.db.models.query.QuerySet.only()` if there are database columns\nyou know that you won't need (or won't need in most cases) to avoid loading\nthem. Note that if you *do* use them, the ORM will have to go and get them in\na separate query, making this a pessimization if you use it inappropriately.\n\nDon't be too aggressive in deferring fields without profiling as the database\nhas to read most of the non-text, non-VARCHAR data from the disk for a single\nrow in the results, even if it ends up only using a few columns. The\n``defer()`` and ``only()`` methods are most useful when you can avoid loading a\nlot of text data or for fields that might take a lot of processing to convert\nback to Python. As always, profile first, then optimize.\n\nUse ``QuerySet.count()``\n------------------------\n\n...if you only want the count, rather than doing ``len(queryset)``.\n\nUse ``QuerySet.exists()``\n-------------------------\n\n...if you only want to find out if at least one result exists, rather than ``if\nqueryset``.\n\nBut:\n\n.. _overuse_of_count_and_exists:\n\nDon't overuse ``count()`` and ``exists()``\n------------------------------------------\n\nIf you are going to need other data from the QuerySet, evaluate it immediately.\n\nFor example, assuming an Email model that has a ``body`` attribute and a\nmany-to-many relation to User, the following template code is optimal:\n\n.. code-block:: html+django\n\n   {% if display_inbox %}\n     {% with emails=user.emails.all %}\n       {% if emails %}\n         <p>You have {{ emails|length }} email(s)</p>\n         {% for email in emails %}\n           <p>{{ email.body }}</p>\n         {% endfor %}\n       {% else %}\n         <p>No messages today.</p>\n       {% endif %}\n     {% endwith %}\n   {% endif %}\n\n\nIt is optimal because:\n\n#. Since QuerySets are lazy, this does no database queries if 'display_inbox'\n   is False.\n\n#. Use of :ttag:`with` means that we store ``user.emails.all`` in a variable\n   for later use, allowing its cache to be re-used.\n\n#. The line ``{% if emails %}`` causes ``QuerySet.__bool__()`` to be called,\n   which causes the ``user.emails.all()`` query to be run on the database, and\n   at the least the first line to be turned into an ORM object. If there aren't\n   any results, it will return False, otherwise True.\n\n#. The use of ``{{ emails|length }}`` calls ``QuerySet.__len__()``, filling\n   out the rest of the cache without doing another query.\n\n#. The :ttag:`for` loop iterates over the already filled cache.\n\nIn total, this code does either one or zero database queries. The only\ndeliberate optimization performed is the use of the :ttag:`with` tag. Using\n``QuerySet.exists()`` or ``QuerySet.count()`` at any point would cause\nadditional queries.\n\nUse ``QuerySet.update()`` and ``delete()``\n------------------------------------------\n\nRather than retrieve a load of objects, set some values, and save them\nindividual, use a bulk SQL UPDATE statement, via :ref:`QuerySet.update()\n<topics-db-queries-update>`. Similarly, do :ref:`bulk deletes\n<topics-db-queries-delete>` where possible.\n\nNote, however, that these bulk update methods cannot call the ``save()`` or\n``delete()`` methods of individual instances, which means that any custom\nbehavior you have added for these methods will not be executed, including\nanything driven from the normal database object :doc:`signals </ref/signals>`.\n\nUse foreign key values directly\n-------------------------------\n\nIf you only need a foreign key value, use the foreign key value that is already on\nthe object you've got, rather than getting the whole related object and taking\nits primary key. i.e. do::\n\n   entry.blog_id\n\ninstead of::\n\n   entry.blog.id\n\nDon't order results if you don't care\n-------------------------------------\n\nOrdering is not free; each field to order by is an operation the database must\nperform. If a model has a default ordering (:attr:`Meta.ordering\n<django.db.models.Options.ordering>`) and you don't need it, remove\nit on a ``QuerySet`` by calling\n:meth:`~django.db.models.query.QuerySet.order_by()` with no parameters.\n\nAdding an index to your database may help to improve ordering performance.\n\nUse bulk methods\n================\n\nUse bulk methods to reduce the number of SQL statements.\n\nCreate in bulk\n--------------\n\nWhen creating objects, where possible, use the\n:meth:`~django.db.models.query.QuerySet.bulk_create()` method to reduce the\nnumber of SQL queries. For example::\n\n    Entry.objects.bulk_create([\n        Entry(headline='This is a test'),\n        Entry(headline='This is only a test'),\n    ])\n\n...is preferable to::\n\n    Entry.objects.create(headline='This is a test')\n    Entry.objects.create(headline='This is only a test')\n\nNote that there are a number of :meth:`caveats to this method\n<django.db.models.query.QuerySet.bulk_create>`, so make sure it's appropriate\nfor your use case.\n\nUpdate in bulk\n--------------\n\nWhen updating objects, where possible, use the\n:meth:`~django.db.models.query.QuerySet.bulk_update()` method to reduce the\nnumber of SQL queries. Given a list or queryset of objects::\n\n    entries = Entry.objects.bulk_create([\n        Entry(headline='This is a test'),\n        Entry(headline='This is only a test'),\n    ])\n\nThe following example::\n\n    entries[0].headline = 'This is not a test'\n    entries[1].headline = 'This is no longer a test'\n    Entry.objects.bulk_update(entries, ['headline'])\n\n...is preferable to::\n\n    entries[0].headline = 'This is not a test'\n    entries[0].save()\n    entries[1].headline = 'This is no longer a test'\n    entries[1].save()\n\nNote that there are a number of :meth:`caveats to this method\n<django.db.models.query.QuerySet.bulk_update>`, so make sure it's appropriate\nfor your use case.\n\nInsert in bulk\n--------------\n\nWhen inserting objects into :class:`ManyToManyFields\n<django.db.models.ManyToManyField>`, use\n:meth:`~django.db.models.fields.related.RelatedManager.add` with multiple\nobjects to reduce the number of SQL queries. For example::\n\n    my_band.members.add(me, my_friend)\n\n...is preferable to::\n\n    my_band.members.add(me)\n    my_band.members.add(my_friend)\n\n...where ``Bands`` and ``Artists`` have a many-to-many relationship.\n\nWhen inserting different pairs of objects into\n:class:`~django.db.models.ManyToManyField` or when the custom\n:attr:`~django.db.models.ManyToManyField.through` table is defined, use\n:meth:`~django.db.models.query.QuerySet.bulk_create()` method to reduce the\nnumber of SQL queries. For example::\n\n    PizzaToppingRelationship = Pizza.toppings.through\n    PizzaToppingRelationship.objects.bulk_create([\n        PizzaToppingRelationship(pizza=my_pizza, topping=pepperoni),\n        PizzaToppingRelationship(pizza=your_pizza, topping=pepperoni),\n        PizzaToppingRelationship(pizza=your_pizza, topping=mushroom),\n    ], ignore_conflicts=True)\n\n...is preferable to::\n\n    my_pizza.toppings.add(pepperoni)\n    your_pizza.toppings.add(pepperoni, mushroom)\n\n...where ``Pizza`` and ``Topping`` have a many-to-many relationship. Note that\nthere are a number of :meth:`caveats to this method\n<django.db.models.query.QuerySet.bulk_create>`, so make sure it's appropriate\nfor your use case.\n\nRemove in bulk\n--------------\n\nWhen removing objects from :class:`ManyToManyFields\n<django.db.models.ManyToManyField>`, use\n:meth:`~django.db.models.fields.related.RelatedManager.remove` with multiple\nobjects to reduce the number of SQL queries. For example::\n\n    my_band.members.remove(me, my_friend)\n\n...is preferable to::\n\n    my_band.members.remove(me)\n    my_band.members.remove(my_friend)\n\n...where ``Bands`` and ``Artists`` have a many-to-many relationship.\n\nWhen removing different pairs of objects from :class:`ManyToManyFields\n<django.db.models.ManyToManyField>`, use\n:meth:`~django.db.models.query.QuerySet.delete` on a\n:class:`~django.db.models.Q` expression with multiple\n:attr:`~django.db.models.ManyToManyField.through`  model instances to reduce\nthe number of SQL queries. For example::\n\n    from django.db.models import Q\n    PizzaToppingRelationship = Pizza.toppings.through\n    PizzaToppingRelationship.objects.filter(\n        Q(pizza=my_pizza, topping=pepperoni) |\n        Q(pizza=your_pizza, topping=pepperoni) |\n        Q(pizza=your_pizza, topping=mushroom)\n    ).delete()\n\n...is preferable to::\n\n    my_pizza.toppings.remove(pepperoni)\n    your_pizza.toppings.remove(pepperoni, mushroom)\n\n...where ``Pizza`` and ``Topping`` have a many-to-many relationship.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":282,"nodeType":"TextFile","repoName":null,"name":"sql.txt","path":"docs/topics/db","text":"==========================\nPerforming raw SQL queries\n==========================\n\n.. currentmodule:: django.db.models\n\nDjango gives you two ways of performing raw SQL queries: you can use\n:meth:`Manager.raw()` to `perform raw queries and return model instances`__, or\nyou can avoid the model layer entirely and `execute custom SQL directly`__.\n\n__ `performing raw queries`_\n__ `executing custom SQL directly`_\n\n.. admonition:: Explore the ORM before using raw SQL!\n\n    The Django ORM provides many tools to express queries without writing raw\n    SQL. For example:\n\n    * The :doc:`QuerySet API </ref/models/querysets>` is extensive.\n    * You can :meth:`annotate <.QuerySet.annotate>` and :doc:`aggregate\n      </topics/db/aggregation>` using many built-in :doc:`database functions\n      </ref/models/database-functions>`. Beyond those, you can create\n      :doc:`custom query expressions </ref/models/expressions/>`.\n\n    Before using raw SQL, explore :doc:`the ORM </topics/db/index>`. Ask on\n    |django-users| or the `#django IRC channel\n    <https://webchat.freenode.net/#django>`_ to see if the ORM supports your\n    use case.\n\n.. warning::\n\n    You should be very careful whenever you write raw SQL. Every time you use\n    it, you should properly escape any parameters that the user can control\n    by using ``params`` in order to protect against SQL injection attacks.\n    Please read more about :ref:`SQL injection protection\n    <sql-injection-protection>`.\n\n.. _executing-raw-queries:\n\nPerforming raw queries\n======================\n\nThe ``raw()`` manager method can be used to perform raw SQL queries that\nreturn model instances:\n\n.. method:: Manager.raw(raw_query, params=None, translations=None)\n\nThis method takes a raw SQL query, executes it, and returns a\n``django.db.models.query.RawQuerySet`` instance. This ``RawQuerySet`` instance\ncan be iterated over like a normal :class:`~django.db.models.query.QuerySet` to\nprovide object instances.\n\nThis is best illustrated with an example. Suppose you have the following model::\n\n    class Person(models.Model):\n        first_name = models.CharField(...)\n        last_name = models.CharField(...)\n        birth_date = models.DateField(...)\n\nYou could then execute custom SQL like so::\n\n    >>> for p in Person.objects.raw('SELECT * FROM myapp_person'):\n    ...     print(p)\n    John Smith\n    Jane Jones\n\nThis example isn't very exciting -- it's exactly the same as running\n``Person.objects.all()``. However, ``raw()`` has a bunch of other options that\nmake it very powerful.\n\n.. admonition:: Model table names\n\n    Where did the name of the ``Person`` table come from in that example?\n\n    By default, Django figures out a database table name by joining the\n    model's \"app label\" -- the name you used in ``manage.py startapp`` -- to\n    the model's class name, with an underscore between them. In the example\n    we've assumed that the ``Person`` model lives in an app named ``myapp``,\n    so its table would be ``myapp_person``.\n\n    For more details check out the documentation for the\n    :attr:`~Options.db_table` option, which also lets you manually set the\n    database table name.\n\n.. warning::\n\n    No checking is done on the SQL statement that is passed in to ``.raw()``.\n    Django expects that the statement will return a set of rows from the\n    database, but does nothing to enforce that. If the query does not\n    return rows, a (possibly cryptic) error will result.\n\n.. warning::\n\n    If you are performing queries on MySQL, note that MySQL's silent type coercion\n    may cause unexpected results when mixing types. If you query on a string\n    type column, but with an integer value, MySQL will coerce the types of all values\n    in the table to an integer before performing the comparison. For example, if your\n    table contains the values ``'abc'``, ``'def'`` and you query for ``WHERE mycolumn=0``,\n    both rows will match. To prevent this, perform the correct typecasting\n    before using the value in a query.\n\nMapping query fields to model fields\n------------------------------------\n\n``raw()`` automatically maps fields in the query to fields on the model.\n\nThe order of fields in your query doesn't matter. In other words, both\nof the following queries work identically::\n\n    >>> Person.objects.raw('SELECT id, first_name, last_name, birth_date FROM myapp_person')\n    ...\n    >>> Person.objects.raw('SELECT last_name, birth_date, first_name, id FROM myapp_person')\n    ...\n\nMatching is done by name. This means that you can use SQL's ``AS`` clauses to\nmap fields in the query to model fields. So if you had some other table that\nhad ``Person`` data in it, you could easily map it into ``Person`` instances::\n\n    >>> Person.objects.raw('''SELECT first AS first_name,\n    ...                              last AS last_name,\n    ...                              bd AS birth_date,\n    ...                              pk AS id,\n    ...                       FROM some_other_table''')\n\nAs long as the names match, the model instances will be created correctly.\n\nAlternatively, you can map fields in the query to model fields using the\n``translations`` argument to ``raw()``. This is a dictionary mapping names of\nfields in the query to names of fields on the model. For example, the above\nquery could also be written::\n\n    >>> name_map = {'first': 'first_name', 'last': 'last_name', 'bd': 'birth_date', 'pk': 'id'}\n    >>> Person.objects.raw('SELECT * FROM some_other_table', translations=name_map)\n\nIndex lookups\n-------------\n\n``raw()`` supports indexing, so if you need only the first result you can\nwrite::\n\n    >>> first_person = Person.objects.raw('SELECT * FROM myapp_person')[0]\n\nHowever, the indexing and slicing are not performed at the database level. If\nyou have a large number of ``Person`` objects in your database, it is more\nefficient to limit the query at the SQL level::\n\n    >>> first_person = Person.objects.raw('SELECT * FROM myapp_person LIMIT 1')[0]\n\nDeferring model fields\n----------------------\n\nFields may also be left out::\n\n    >>> people = Person.objects.raw('SELECT id, first_name FROM myapp_person')\n\nThe ``Person`` objects returned by this query will be deferred model instances\n(see :meth:`~django.db.models.query.QuerySet.defer()`). This means that the\nfields that are omitted from the query will be loaded on demand. For example::\n\n    >>> for p in Person.objects.raw('SELECT id, first_name FROM myapp_person'):\n    ...     print(p.first_name, # This will be retrieved by the original query\n    ...           p.last_name) # This will be retrieved on demand\n    ...\n    John Smith\n    Jane Jones\n\nFrom outward appearances, this looks like the query has retrieved both\nthe first name and last name. However, this example actually issued 3\nqueries. Only the first names were retrieved by the raw() query -- the\nlast names were both retrieved on demand when they were printed.\n\nThere is only one field that you can't leave out - the primary key\nfield. Django uses the primary key to identify model instances, so it\nmust always be included in a raw query. A\n:class:`~django.core.exceptions.FieldDoesNotExist` exception will be raised if\nyou forget to include the primary key.\n\nAdding annotations\n------------------\n\nYou can also execute queries containing fields that aren't defined on the\nmodel. For example, we could use `PostgreSQL's age() function`__ to get a list\nof people with their ages calculated by the database::\n\n    >>> people = Person.objects.raw('SELECT *, age(birth_date) AS age FROM myapp_person')\n    >>> for p in people:\n    ...     print(\"%s is %s.\" % (p.first_name, p.age))\n    John is 37.\n    Jane is 42.\n    ...\n\nYou can often avoid using raw SQL to compute annotations by instead using a\n:ref:`Func() expression <func-expressions>`.\n\n__ https://www.postgresql.org/docs/current/functions-datetime.html\n\nPassing parameters into ``raw()``\n---------------------------------\n\nIf you need to perform parameterized queries, you can use the ``params``\nargument to ``raw()``::\n\n    >>> lname = 'Doe'\n    >>> Person.objects.raw('SELECT * FROM myapp_person WHERE last_name = %s', [lname])\n\n``params`` is a list or dictionary of parameters. You'll use ``%s``\nplaceholders in the query string for a list, or ``%(key)s``\nplaceholders for a dictionary (where ``key`` is replaced by a\ndictionary key), regardless of your database engine. Such placeholders will be\nreplaced with parameters from the ``params`` argument.\n\n.. note::\n\n   Dictionary params are not supported with the SQLite backend; with\n   this backend, you must pass parameters as a list.\n\n.. warning::\n\n    **Do not use string formatting on raw queries or quote placeholders in your\n    SQL strings!**\n\n    It's tempting to write the above query as::\n\n        >>> query = 'SELECT * FROM myapp_person WHERE last_name = %s' % lname\n        >>> Person.objects.raw(query)\n\n    You might also think you should write your query like this (with quotes\n    around ``%s``)::\n\n        >>> query = \"SELECT * FROM myapp_person WHERE last_name = '%s'\"\n\n    **Don't make either of these mistakes.**\n\n    As discussed in :ref:`sql-injection-protection`, using the ``params``\n    argument and leaving the placeholders unquoted protects you from `SQL\n    injection attacks`__, a common exploit where attackers inject arbitrary\n    SQL into your database. If you use string interpolation or quote the\n    placeholder, you're at risk for SQL injection.\n\n__ https://en.wikipedia.org/wiki/SQL_injection\n\n.. _executing-custom-sql:\n\nExecuting custom SQL directly\n=============================\n\nSometimes even :meth:`Manager.raw` isn't quite enough: you might need to\nperform queries that don't map cleanly to models, or directly execute\n``UPDATE``, ``INSERT``, or ``DELETE`` queries.\n\nIn these cases, you can always access the database directly, routing around\nthe model layer entirely.\n\nThe object ``django.db.connection`` represents the default database\nconnection. To use the database connection, call ``connection.cursor()`` to\nget a cursor object. Then, call ``cursor.execute(sql, [params])`` to execute\nthe SQL and ``cursor.fetchone()`` or ``cursor.fetchall()`` to return the\nresulting rows.\n\nFor example::\n\n    from django.db import connection\n\n    def my_custom_sql(self):\n        with connection.cursor() as cursor:\n            cursor.execute(\"UPDATE bar SET foo = 1 WHERE baz = %s\", [self.baz])\n            cursor.execute(\"SELECT foo FROM bar WHERE baz = %s\", [self.baz])\n            row = cursor.fetchone()\n\n        return row\n\nTo protect against SQL injection, you must not include quotes around the ``%s``\nplaceholders in the SQL string.\n\nNote that if you want to include literal percent signs in the query, you have to\ndouble them in the case you are passing parameters::\n\n     cursor.execute(\"SELECT foo FROM bar WHERE baz = '30%'\")\n     cursor.execute(\"SELECT foo FROM bar WHERE baz = '30%%' AND id = %s\", [self.id])\n\nIf you are using :doc:`more than one database </topics/db/multi-db>`, you can\nuse ``django.db.connections`` to obtain the connection (and cursor) for a\nspecific database. ``django.db.connections`` is a dictionary-like\nobject that allows you to retrieve a specific connection using its\nalias::\n\n    from django.db import connections\n    with connections['my_db_alias'].cursor() as cursor:\n        # Your code here...\n\nBy default, the Python DB API will return results without their field names,\nwhich means you end up with a ``list`` of values, rather than a ``dict``. At a\nsmall performance and memory cost, you can return results as a ``dict`` by\nusing something like this::\n\n    def dictfetchall(cursor):\n        \"Return all rows from a cursor as a dict\"\n        columns = [col[0] for col in cursor.description]\n        return [\n            dict(zip(columns, row))\n            for row in cursor.fetchall()\n        ]\n\nAnother option is to use :func:`collections.namedtuple` from the Python\nstandard library. A ``namedtuple`` is a tuple-like object that has fields\naccessible by attribute lookup; it's also indexable and iterable. Results are\nimmutable and accessible by field names or indices, which might be useful::\n\n    from collections import namedtuple\n\n    def namedtuplefetchall(cursor):\n        \"Return all rows from a cursor as a namedtuple\"\n        desc = cursor.description\n        nt_result = namedtuple('Result', [col[0] for col in desc])\n        return [nt_result(*row) for row in cursor.fetchall()]\n\nHere is an example of the difference between the three::\n\n    >>> cursor.execute(\"SELECT id, parent_id FROM test LIMIT 2\");\n    >>> cursor.fetchall()\n    ((54360982, None), (54360880, None))\n\n    >>> cursor.execute(\"SELECT id, parent_id FROM test LIMIT 2\");\n    >>> dictfetchall(cursor)\n    [{'parent_id': None, 'id': 54360982}, {'parent_id': None, 'id': 54360880}]\n\n    >>> cursor.execute(\"SELECT id, parent_id FROM test LIMIT 2\");\n    >>> results = namedtuplefetchall(cursor)\n    >>> results\n    [Result(id=54360982, parent_id=None), Result(id=54360880, parent_id=None)]\n    >>> results[0].id\n    54360982\n    >>> results[0][0]\n    54360982\n\nConnections and cursors\n-----------------------\n\n``connection`` and ``cursor`` mostly implement the standard Python DB-API\ndescribed in :pep:`249` — except when it comes to :doc:`transaction handling\n</topics/db/transactions>`.\n\nIf you're not familiar with the Python DB-API, note that the SQL statement in\n``cursor.execute()`` uses placeholders, ``\"%s\"``, rather than adding\nparameters directly within the SQL. If you use this technique, the underlying\ndatabase library will automatically escape your parameters as necessary.\n\nAlso note that Django expects the ``\"%s\"`` placeholder, *not* the ``\"?\"``\nplaceholder, which is used by the SQLite Python bindings. This is for the sake\nof consistency and sanity.\n\nUsing a cursor as a context manager::\n\n    with connection.cursor() as c:\n        c.execute(...)\n\nis equivalent to::\n\n    c = connection.cursor()\n    try:\n        c.execute(...)\n    finally:\n        c.close()\n\nCalling stored procedures\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. method:: CursorWrapper.callproc(procname, params=None, kparams=None)\n\n    Calls a database stored procedure with the given name. A sequence\n    (``params``) or dictionary (``kparams``) of input parameters may be\n    provided. Most databases don't support ``kparams``. Of Django's built-in\n    backends, only Oracle supports it.\n\n    For example, given this stored procedure in an Oracle database:\n\n    .. code-block:: sql\n\n        CREATE PROCEDURE \"TEST_PROCEDURE\"(v_i INTEGER, v_text NVARCHAR2(10)) AS\n            p_i INTEGER;\n            p_text NVARCHAR2(10);\n        BEGIN\n            p_i := v_i;\n            p_text := v_text;\n            ...\n        END;\n\n    This will call it::\n\n        with connection.cursor() as cursor:\n            cursor.callproc('test_procedure', [1, 'test'])\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":283,"nodeType":"TextFile","repoName":null,"name":"generic-views.txt","path":"docs/topics/http","text":"=============\nGeneric views\n=============\n\nSee :doc:`/ref/class-based-views/index`.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":284,"nodeType":"TextFile","repoName":null,"name":"managers.txt","path":"docs/topics/db","text":"========\nManagers\n========\n\n.. currentmodule:: django.db.models\n\n.. class:: Manager()\n\nA ``Manager`` is the interface through which database query operations are\nprovided to Django models. At least one ``Manager`` exists for every model in\na Django application.\n\nThe way ``Manager`` classes work is documented in :doc:`/topics/db/queries`;\nthis document specifically touches on model options that customize ``Manager``\nbehavior.\n\n.. _manager-names:\n\nManager names\n=============\n\nBy default, Django adds a ``Manager`` with the name ``objects`` to every Django\nmodel class. However, if you want to use ``objects`` as a field name, or if you\nwant to use a name other than ``objects`` for the ``Manager``, you can rename\nit on a per-model basis. To rename the ``Manager`` for a given class, define a\nclass attribute of type ``models.Manager()`` on that model. For example::\n\n    from django.db import models\n\n    class Person(models.Model):\n        #...\n        people = models.Manager()\n\nUsing this example model, ``Person.objects`` will generate an\n``AttributeError`` exception, but ``Person.people.all()`` will provide a list\nof all ``Person`` objects.\n\n.. _custom-managers:\n\nCustom managers\n===============\n\nYou can use a custom ``Manager`` in a particular model by extending the base\n``Manager`` class and instantiating your custom ``Manager`` in your model.\n\nThere are two reasons you might want to customize a ``Manager``: to add extra\n``Manager`` methods, and/or to modify the initial ``QuerySet`` the ``Manager``\nreturns.\n\nAdding extra manager methods\n----------------------------\n\nAdding extra ``Manager`` methods is the preferred way to add \"table-level\"\nfunctionality to your models. (For \"row-level\" functionality -- i.e., functions\nthat act on a single instance of a model object -- use :ref:`Model methods\n<model-methods>`, not custom ``Manager`` methods.)\n\nA custom ``Manager`` method can return anything you want. It doesn't have to\nreturn a ``QuerySet``.\n\nFor example, this custom ``Manager`` offers a method ``with_counts()``, which\nreturns a list of all ``OpinionPoll`` objects, each with an extra\n``num_responses`` attribute that is the result of an aggregate query::\n\n    from django.db import models\n\n    class PollManager(models.Manager):\n        def with_counts(self):\n            from django.db import connection\n            with connection.cursor() as cursor:\n                cursor.execute(\"\"\"\n                    SELECT p.id, p.question, p.poll_date, COUNT(*)\n                    FROM polls_opinionpoll p, polls_response r\n                    WHERE p.id = r.poll_id\n                    GROUP BY p.id, p.question, p.poll_date\n                    ORDER BY p.poll_date DESC\"\"\")\n                result_list = []\n                for row in cursor.fetchall():\n                    p = self.model(id=row[0], question=row[1], poll_date=row[2])\n                    p.num_responses = row[3]\n                    result_list.append(p)\n            return result_list\n\n    class OpinionPoll(models.Model):\n        question = models.CharField(max_length=200)\n        poll_date = models.DateField()\n        objects = PollManager()\n\n    class Response(models.Model):\n        poll = models.ForeignKey(OpinionPoll, on_delete=models.CASCADE)\n        person_name = models.CharField(max_length=50)\n        response = models.TextField()\n\nWith this example, you'd use ``OpinionPoll.objects.with_counts()`` to return\nthat list of ``OpinionPoll`` objects with ``num_responses`` attributes.\n\nAnother thing to note about this example is that ``Manager`` methods can\naccess ``self.model`` to get the model class to which they're attached.\n\nModifying a manager's initial ``QuerySet``\n------------------------------------------\n\nA ``Manager``’s base ``QuerySet`` returns all objects in the system. For\nexample, using this model::\n\n    from django.db import models\n\n    class Book(models.Model):\n        title = models.CharField(max_length=100)\n        author = models.CharField(max_length=50)\n\n...the statement ``Book.objects.all()`` will return all books in the database.\n\nYou can override a ``Manager``’s base ``QuerySet`` by overriding the\n``Manager.get_queryset()`` method. ``get_queryset()`` should return a\n``QuerySet`` with the properties you require.\n\nFor example, the following model has *two* ``Manager``\\s -- one that returns\nall objects, and one that returns only the books by Roald Dahl::\n\n    # First, define the Manager subclass.\n    class DahlBookManager(models.Manager):\n        def get_queryset(self):\n            return super().get_queryset().filter(author='Roald Dahl')\n\n    # Then hook it into the Book model explicitly.\n    class Book(models.Model):\n        title = models.CharField(max_length=100)\n        author = models.CharField(max_length=50)\n\n        objects = models.Manager() # The default manager.\n        dahl_objects = DahlBookManager() # The Dahl-specific manager.\n\nWith this sample model, ``Book.objects.all()`` will return all books in the\ndatabase, but ``Book.dahl_objects.all()`` will only return the ones written by\nRoald Dahl.\n\nBecause ``get_queryset()`` returns a ``QuerySet`` object, you can use\n``filter()``, ``exclude()`` and all the other ``QuerySet`` methods on it. So\nthese statements are all legal::\n\n    Book.dahl_objects.all()\n    Book.dahl_objects.filter(title='Matilda')\n    Book.dahl_objects.count()\n\nThis example also pointed out another interesting technique: using multiple\nmanagers on the same model. You can attach as many ``Manager()`` instances to\na model as you'd like. This is a non-repetitive way to define common \"filters\"\nfor your models.\n\nFor example::\n\n    class AuthorManager(models.Manager):\n        def get_queryset(self):\n            return super().get_queryset().filter(role='A')\n\n    class EditorManager(models.Manager):\n        def get_queryset(self):\n            return super().get_queryset().filter(role='E')\n\n    class Person(models.Model):\n        first_name = models.CharField(max_length=50)\n        last_name = models.CharField(max_length=50)\n        role = models.CharField(max_length=1, choices=[('A', _('Author')), ('E', _('Editor'))])\n        people = models.Manager()\n        authors = AuthorManager()\n        editors = EditorManager()\n\nThis example allows you to request ``Person.authors.all()``, ``Person.editors.all()``,\nand ``Person.people.all()``, yielding predictable results.\n\n.. _default-managers:\n\nDefault managers\n----------------\n\n.. attribute:: Model._default_manager\n\nIf you use custom ``Manager`` objects, take note that the first ``Manager``\nDjango encounters (in the order in which they're defined in the model) has a\nspecial status. Django interprets the first ``Manager`` defined in a class as\nthe \"default\" ``Manager``, and several parts of Django (including\n:djadmin:`dumpdata`) will use that ``Manager`` exclusively for that model. As a\nresult, it's a good idea to be careful in your choice of default manager in\norder to avoid a situation where overriding ``get_queryset()`` results in an\ninability to retrieve objects you'd like to work with.\n\nYou can specify a custom default manager using :attr:`Meta.default_manager_name\n<django.db.models.Options.default_manager_name>`.\n\nIf you're writing some code that must handle an unknown model, for example, in\na third-party app that implements a generic view, use this manager (or\n:attr:`~Model._base_manager`) rather than assuming the model has an ``objects``\nmanager.\n\nBase managers\n-------------\n\n.. attribute:: Model._base_manager\n\n.. _managers-for-related-objects:\n\nUsing managers for related object access\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nBy default, Django uses an instance of the ``Model._base_manager`` manager\nclass when accessing related objects (i.e. ``choice.question``), not the\n``_default_manager`` on the related object. This is because Django needs to be\nable to retrieve the related object, even if it would otherwise be filtered out\n(and hence be inaccessible) by the default manager.\n\nIf the normal base manager class (:class:`django.db.models.Manager`) isn't\nappropriate for your circumstances, you can tell Django which class to use by\nsetting :attr:`Meta.base_manager_name\n<django.db.models.Options.base_manager_name>`.\n\nBase managers aren't used when querying on related models, or when\n:ref:`accessing a one-to-many or many-to-many relationship\n<backwards-related-objects>`. For example, if the ``Question`` model\n:ref:`from the tutorial <creating-models>` had a ``deleted`` field and a base\nmanager that filters out instances with ``deleted=True``, a queryset like\n``Choice.objects.filter(question__name__startswith='What')`` would include\nchoices related to deleted questions.\n\nDon't filter away any results in this type of manager subclass\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThis manager is used to access objects that are related to from some other\nmodel. In those situations, Django has to be able to see all the objects for\nthe model it is fetching, so that *anything* which is referred to can be\nretrieved.\n\nTherefore, you should not override ``get_queryset()`` to filter out any rows.\nIf you do so, Django will return incomplete results.\n\n.. _calling-custom-queryset-methods-from-manager:\n\nCalling custom ``QuerySet`` methods from the manager\n----------------------------------------------------\n\nWhile most methods from the standard ``QuerySet`` are accessible directly from\nthe ``Manager``, this is only the case for the extra methods defined on a\ncustom ``QuerySet`` if you also implement them on the ``Manager``::\n\n    class PersonQuerySet(models.QuerySet):\n        def authors(self):\n            return self.filter(role='A')\n\n        def editors(self):\n            return self.filter(role='E')\n\n    class PersonManager(models.Manager):\n        def get_queryset(self):\n            return PersonQuerySet(self.model, using=self._db)\n\n        def authors(self):\n            return self.get_queryset().authors()\n\n        def editors(self):\n            return self.get_queryset().editors()\n\n    class Person(models.Model):\n        first_name = models.CharField(max_length=50)\n        last_name = models.CharField(max_length=50)\n        role = models.CharField(max_length=1, choices=[('A', _('Author')), ('E', _('Editor'))])\n        people = PersonManager()\n\nThis example allows you to call both ``authors()`` and ``editors()`` directly from\nthe manager ``Person.people``.\n\n.. _create-manager-with-queryset-methods:\n\nCreating a manager with ``QuerySet`` methods\n--------------------------------------------\n\nIn lieu of the above approach which requires duplicating methods on both the\n``QuerySet`` and the ``Manager``, :meth:`QuerySet.as_manager()\n<django.db.models.query.QuerySet.as_manager>` can be used to create an instance\nof ``Manager`` with a copy of a custom ``QuerySet``’s methods::\n\n    class Person(models.Model):\n        ...\n        people = PersonQuerySet.as_manager()\n\nThe ``Manager`` instance created by :meth:`QuerySet.as_manager()\n<django.db.models.query.QuerySet.as_manager>` will be virtually\nidentical to the ``PersonManager`` from the previous example.\n\nNot every ``QuerySet`` method makes sense at the ``Manager`` level; for\ninstance we intentionally prevent the :meth:`QuerySet.delete()\n<django.db.models.query.QuerySet.delete>` method from being copied onto\nthe ``Manager`` class.\n\nMethods are copied according to the following rules:\n\n- Public methods are copied by default.\n- Private methods (starting with an underscore) are not copied by default.\n- Methods with a ``queryset_only`` attribute set to ``False`` are always copied.\n- Methods with a ``queryset_only`` attribute set to ``True`` are never copied.\n\nFor example::\n\n    class CustomQuerySet(models.QuerySet):\n        # Available on both Manager and QuerySet.\n        def public_method(self):\n            return\n\n        # Available only on QuerySet.\n        def _private_method(self):\n            return\n\n        # Available only on QuerySet.\n        def opted_out_public_method(self):\n            return\n        opted_out_public_method.queryset_only = True\n\n        # Available on both Manager and QuerySet.\n        def _opted_in_private_method(self):\n            return\n        _opted_in_private_method.queryset_only = False\n\n``from_queryset()``\n~~~~~~~~~~~~~~~~~~~\n\n.. classmethod:: from_queryset(queryset_class)\n\nFor advanced usage you might want both a custom ``Manager`` and a custom\n``QuerySet``. You can do that by calling ``Manager.from_queryset()`` which\nreturns a *subclass* of your base ``Manager`` with a copy of the custom\n``QuerySet`` methods::\n\n    class CustomManager(models.Manager):\n        def manager_only_method(self):\n            return\n\n    class CustomQuerySet(models.QuerySet):\n        def manager_and_queryset_method(self):\n            return\n\n    class MyModel(models.Model):\n        objects = CustomManager.from_queryset(CustomQuerySet)()\n\nYou may also store the generated class into a variable::\n\n    MyManager = CustomManager.from_queryset(CustomQuerySet)\n\n    class MyModel(models.Model):\n        objects = MyManager()\n\n.. _custom-managers-and-inheritance:\n\nCustom managers and model inheritance\n-------------------------------------\n\nHere's how Django handles custom managers and :ref:`model inheritance\n<model-inheritance>`:\n\n#. Managers from base classes are always inherited by the child class,\n   using Python's normal name resolution order (names on the child\n   class override all others; then come names on the first parent class,\n   and so on).\n\n#. If no managers are declared on a model and/or its parents, Django\n   automatically creates the ``objects`` manager.\n\n#. The default manager on a class is either the one chosen with\n   :attr:`Meta.default_manager_name\n   <django.db.models.Options.default_manager_name>`, or the first manager\n   declared on the model, or the default manager of the first parent model.\n\nThese rules provide the necessary flexibility if you want to install a\ncollection of custom managers on a group of models, via an abstract base\nclass, but still customize the default manager. For example, suppose you have\nthis base class::\n\n    class AbstractBase(models.Model):\n        # ...\n        objects = CustomManager()\n\n        class Meta:\n            abstract = True\n\nIf you use this directly in a subclass, ``objects`` will be the default\nmanager if you declare no managers in the base class::\n\n    class ChildA(AbstractBase):\n        # ...\n        # This class has CustomManager as the default manager.\n        pass\n\nIf you want to inherit from ``AbstractBase``, but provide a different default\nmanager, you can provide the default manager on the child class::\n\n    class ChildB(AbstractBase):\n        # ...\n        # An explicit default manager.\n        default_manager = OtherManager()\n\nHere, ``default_manager`` is the default. The ``objects`` manager is\nstill available, since it's inherited, but isn't used as the default.\n\nFinally for this example, suppose you want to add extra managers to the child\nclass, but still use the default from ``AbstractBase``. You can't add the new\nmanager directly in the child class, as that would override the default and you would\nhave to also explicitly include all the managers from the abstract base class.\nThe solution is to put the extra managers in another base class and introduce\nit into the inheritance hierarchy *after* the defaults::\n\n    class ExtraManager(models.Model):\n        extra_manager = OtherManager()\n\n        class Meta:\n            abstract = True\n\n    class ChildC(AbstractBase, ExtraManager):\n        # ...\n        # Default manager is CustomManager, but OtherManager is\n        # also available via the \"extra_manager\" attribute.\n        pass\n\nNote that while you can *define* a custom manager on the abstract model, you\ncan't *invoke* any methods using the abstract model. That is::\n\n    ClassA.objects.do_something()\n\nis legal, but::\n\n    AbstractBase.objects.do_something()\n\nwill raise an exception. This is because managers are intended to encapsulate\nlogic for managing collections of objects. Since you can't have a collection of\nabstract objects, it doesn't make sense to be managing them. If you have\nfunctionality that applies to the abstract model, you should put that functionality\nin a ``staticmethod`` or ``classmethod`` on the abstract model.\n\nImplementation concerns\n-----------------------\n\nWhatever features you add to your custom ``Manager``, it must be\npossible to make a shallow copy of a ``Manager`` instance; i.e., the\nfollowing code must work::\n\n    >>> import copy\n    >>> manager = MyManager()\n    >>> my_copy = copy.copy(manager)\n\nDjango makes shallow copies of manager objects during certain queries;\nif your Manager cannot be copied, those queries will fail.\n\nThis won't be an issue for most custom managers. If you are just\nadding simple methods to your ``Manager``, it is unlikely that you\nwill inadvertently make instances of your ``Manager`` uncopyable.\nHowever, if you're overriding ``__getattr__`` or some other private\nmethod of your ``Manager`` object that controls object state, you\nshould ensure that you don't affect the ability of your ``Manager`` to\nbe copied.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":285,"nodeType":"TextFile","repoName":null,"name":"views.txt","path":"docs/topics/http","text":"=============\nWriting views\n=============\n\nA view function, or *view* for short, is a Python function that takes a\nWeb request and returns a Web response. This response can be the HTML contents\nof a Web page, or a redirect, or a 404 error, or an XML document, or an image .\n. . or anything, really. The view itself contains whatever arbitrary logic is\nnecessary to return that response. This code can live anywhere you want, as long\nas it's on your Python path. There's no other requirement--no \"magic,\" so to\nspeak. For the sake of putting the code *somewhere*, the convention is to\nput views in a file called ``views.py``, placed in your project or\napplication directory.\n\nA simple view\n=============\n\nHere's a view that returns the current date and time, as an HTML document::\n\n    from django.http import HttpResponse\n    import datetime\n\n    def current_datetime(request):\n        now = datetime.datetime.now()\n        html = \"<html><body>It is now %s.</body></html>\" % now\n        return HttpResponse(html)\n\nLet's step through this code one line at a time:\n\n* First, we import the class :class:`~django.http.HttpResponse` from the\n  :mod:`django.http` module, along with Python's ``datetime`` library.\n\n* Next, we define a function called ``current_datetime``. This is the view\n  function. Each view function takes an :class:`~django.http.HttpRequest`\n  object as its first parameter, which is typically named ``request``.\n\n  Note that the name of the view function doesn't matter; it doesn't have to\n  be named in a certain way in order for Django to recognize it. We're\n  calling it ``current_datetime`` here, because that name clearly indicates\n  what it does.\n\n* The view returns an :class:`~django.http.HttpResponse` object that\n  contains the generated response. Each view function is responsible for\n  returning an :class:`~django.http.HttpResponse` object. (There are\n  exceptions, but we'll get to those later.)\n\n.. admonition:: Django's Time Zone\n\n    Django includes a :setting:`TIME_ZONE` setting that defaults to\n    ``America/Chicago``. This probably isn't where you live, so you might want\n    to change it in your settings file.\n\nMapping URLs to views\n=====================\n\nSo, to recap, this view function returns an HTML page that includes the current\ndate and time. To display this view at a particular URL, you'll need to create a\n*URLconf*; see :doc:`/topics/http/urls` for instructions.\n\nReturning errors\n================\n\nDjango provides help for returning HTTP error codes. There are subclasses of\n:class:`~django.http.HttpResponse` for a number of common HTTP status codes\nother than 200 (which means *\"OK\"*). You can find the full list of available\nsubclasses in the :ref:`request/response <ref-httpresponse-subclasses>`\ndocumentation. Return an instance of one of those subclasses instead of a\nnormal :class:`~django.http.HttpResponse` in order to signify an error. For\nexample::\n\n    from django.http import HttpResponse, HttpResponseNotFound\n\n    def my_view(request):\n        # ...\n        if foo:\n            return HttpResponseNotFound('<h1>Page not found</h1>')\n        else:\n            return HttpResponse('<h1>Page was found</h1>')\n\nThere isn't a specialized subclass for every possible HTTP response code,\nsince many of them aren't going to be that common. However, as documented in\nthe :class:`~django.http.HttpResponse` documentation, you can also pass the\nHTTP status code into the constructor for :class:`~django.http.HttpResponse`\nto create a return class for any status code you like. For example::\n\n    from django.http import HttpResponse\n\n    def my_view(request):\n        # ...\n\n        # Return a \"created\" (201) response code.\n        return HttpResponse(status=201)\n\nBecause 404 errors are by far the most common HTTP error, there's an easier way\nto handle those errors.\n\nThe ``Http404`` exception\n-------------------------\n\n.. class:: django.http.Http404()\n\nWhen you return an error such as :class:`~django.http.HttpResponseNotFound`,\nyou're responsible for defining the HTML of the resulting error page::\n\n    return HttpResponseNotFound('<h1>Page not found</h1>')\n\nFor convenience, and because it's a good idea to have a consistent 404 error page\nacross your site, Django provides an ``Http404`` exception. If you raise\n``Http404`` at any point in a view function, Django will catch it and return the\nstandard error page for your application, along with an HTTP error code 404.\n\nExample usage::\n\n    from django.http import Http404\n    from django.shortcuts import render\n    from polls.models import Poll\n\n    def detail(request, poll_id):\n        try:\n            p = Poll.objects.get(pk=poll_id)\n        except Poll.DoesNotExist:\n            raise Http404(\"Poll does not exist\")\n        return render(request, 'polls/detail.html', {'poll': p})\n\nIn order to show customized HTML when Django returns a 404, you can create an\nHTML template named ``404.html`` and place it in the top level of your\ntemplate tree. This template will then be served when :setting:`DEBUG` is set\nto ``False``.\n\nWhen :setting:`DEBUG` is ``True``, you can provide a message to ``Http404`` and\nit will appear in the standard 404 debug template. Use these messages for\ndebugging purposes; they generally aren't suitable for use in a production 404\ntemplate.\n\n.. _customizing-error-views:\n\nCustomizing error views\n=======================\n\nThe default error views in Django should suffice for most Web applications,\nbut can easily be overridden if you need any custom behavior. Specify the\nhandlers as seen below in your URLconf (setting them anywhere else will have no\neffect).\n\nThe :func:`~django.views.defaults.page_not_found` view is overridden by\n:data:`~django.conf.urls.handler404`::\n\n    handler404 = 'mysite.views.my_custom_page_not_found_view'\n\nThe :func:`~django.views.defaults.server_error` view is overridden by\n:data:`~django.conf.urls.handler500`::\n\n    handler500 = 'mysite.views.my_custom_error_view'\n\nThe :func:`~django.views.defaults.permission_denied` view is overridden by\n:data:`~django.conf.urls.handler403`::\n\n    handler403 = 'mysite.views.my_custom_permission_denied_view'\n\nThe :func:`~django.views.defaults.bad_request` view is overridden by\n:data:`~django.conf.urls.handler400`::\n\n    handler400 = 'mysite.views.my_custom_bad_request_view'\n\n.. seealso::\n\n    Use the :setting:`CSRF_FAILURE_VIEW` setting to override the CSRF error\n    view.\n\nTesting custom error views\n--------------------------\n\nTo test the response of a custom error handler, raise the appropriate exception\nin a test view. For example::\n\n    from django.core.exceptions import PermissionDenied\n    from django.http import HttpResponse\n    from django.test import SimpleTestCase, override_settings\n    from django.urls import path\n\n\n    def response_error_handler(request, exception=None):\n        return HttpResponse('Error handler content', status=403)\n\n\n    def permission_denied_view(request):\n        raise PermissionDenied\n\n\n    urlpatterns = [\n        path('403/', permission_denied_view),\n    ]\n\n    handler403 = response_error_handler\n\n\n    # ROOT_URLCONF must specify the module that contains handler403 = ...\n    @override_settings(ROOT_URLCONF=__name__)\n    class CustomErrorHandlerTests(SimpleTestCase):\n\n        def test_handler_renders_template_response(self):\n            response = self.client.get('/403/')\n            # Make assertions on the response here. For example:\n            self.assertContains(response, 'Error handler content', status_code=403)\n\n.. _async-views:\n\nAsync views\n===========\n\n.. versionadded:: 3.1\n\nAs well as being synchronous functions, views can also be asynchronous\n(\"async\") functions, normally defined using Python's ``async def`` syntax.\nDjango will automatically detect these and run them in an async context.\nHowever, you will need to use an async server based on ASGI to get their\nperformance benefits.\n\nHere's an example of an async view::\n\n    import datetime\n    from django.http import HttpResponse\n\n    async def current_datetime(request):\n        now = datetime.datetime.now()\n        html = '<html><body>It is now %s.</body></html>' % now\n        return HttpResponse(html)\n\nYou can read more about Django's async support, and how to best use async\nviews, in :doc:`/topics/async`.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":286,"nodeType":"Package","repoName":null,"name":"docs/topics/i18n","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":287,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/topics/i18n","text":"=====================================\nInternationalization and localization\n=====================================\n\n.. toctree::\n   :hidden:\n   :maxdepth: 1\n\n   translation\n   formatting\n   timezones\n\nOverview\n========\n\nThe goal of internationalization and localization is to allow a single Web\napplication to offer its content in languages and formats tailored to the\naudience.\n\nDjango has full support for :doc:`translation of text\n</topics/i18n/translation>`, :doc:`formatting of dates, times and numbers\n</topics/i18n/formatting>`, and :doc:`time zones </topics/i18n/timezones>`.\n\nEssentially, Django does two things:\n\n* It allows developers and template authors to specify which parts of their apps\n  should be translated or formatted for local languages and cultures.\n* It uses these hooks to localize Web apps for particular users according to\n  their preferences.\n\nTranslation depends on the target language, and formatting usually depends on\nthe target country. This information is provided by browsers in the\n``Accept-Language`` header. However, the time zone isn't readily available.\n\nDefinitions\n===========\n\nThe words \"internationalization\" and \"localization\" often cause confusion;\nhere's a simplified definition:\n\n.. glossary::\n\n    internationalization\n      Preparing the software for localization. Usually done by developers.\n\n    localization\n      Writing the translations and local formats. Usually done by translators.\n\nMore details can be found in the `W3C Web Internationalization FAQ`_, the `Wikipedia article`_ or the `GNU gettext documentation`_.\n\n.. _W3C Web Internationalization FAQ: https://www.w3.org/International/questions/qa-i18n\n.. _GNU gettext documentation: https://www.gnu.org/software/gettext/manual/gettext.html#Concepts\n.. _Wikipedia article: https://en.wikipedia.org/wiki/Internationalization_and_localization\n\n.. warning::\n\n    Translation and formatting are controlled by :setting:`USE_I18N` and\n    :setting:`USE_L10N` settings respectively. However, both features involve\n    internationalization and localization. The names of the settings are an\n    unfortunate result of Django's history.\n\nHere are some other terms that will help us to handle a common language:\n\n.. glossary::\n\n    locale name\n      A locale name, either a language specification of the form ``ll`` or a\n      combined language and country specification of the form ``ll_CC``.\n      Examples: ``it``, ``de_AT``, ``es``, ``pt_BR``, ``sr_Latn``. The language\n      part is always in lowercase. The country part is in titlecase if it has\n      more than 2 characters, otherwise it's in uppercase. The separator is an\n      underscore.\n\n    language code\n      Represents the name of a language. Browsers send the names of the\n      languages they accept in the ``Accept-Language`` HTTP header using this\n      format. Examples: ``it``, ``de-at``, ``es``, ``pt-br``. Language codes\n      are generally represented in lowercase, but the HTTP ``Accept-Language``\n      header is case-insensitive. The separator is a dash.\n\n    message file\n      A message file is a plain-text file, representing a single language,\n      that contains all available :term:`translation strings\n      <translation string>` and how they should be represented in the given\n      language. Message files have a ``.po`` file extension.\n\n    translation string\n      A literal that can be translated.\n\n    format file\n      A format file is a Python module that defines the data formats for a given\n      locale.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":288,"nodeType":"TextFile","repoName":null,"name":"formatting.txt","path":"docs/topics/i18n","text":"===================\nFormat localization\n===================\n\nOverview\n========\n\nDjango's formatting system is capable of displaying dates, times and numbers in\ntemplates using the format specified for the current\n:term:`locale <locale name>`. It also handles localized input in forms.\n\nWhen it's enabled, two users accessing the same content may see dates, times and\nnumbers formatted in different ways, depending on the formats for their current\nlocale.\n\nThe formatting system is disabled by default. To enable it, it's\nnecessary to set :setting:`USE_L10N = True <USE_L10N>` in your settings file.\n\n.. note::\n\n    The default :file:`settings.py` file created by :djadmin:`django-admin\n    startproject <startproject>` includes :setting:`USE_L10N = True <USE_L10N>`\n    for convenience.  Note, however, that to enable number formatting with\n    thousand separators it is necessary to set :setting:`USE_THOUSAND_SEPARATOR\n    = True <USE_THOUSAND_SEPARATOR>` in your settings file. Alternatively, you\n    could use :tfilter:`intcomma` to format numbers in your template.\n\n.. note::\n\n    There is also an independent but related :setting:`USE_I18N` setting that\n    controls if Django should activate translation. See\n    :doc:`/topics/i18n/translation` for more details.\n\nLocale aware input in forms\n===========================\n\nWhen formatting is enabled, Django can use localized formats when parsing dates,\ntimes and numbers in forms. That means it tries different formats for different\nlocales when guessing the format used by the user when inputting data on forms.\n\n.. note::\n    Django uses different formats for displaying data to those it uses for\n    parsing data. Most notably, the formats for parsing dates can't use the\n    ``%a`` (abbreviated weekday name), ``%A`` (full weekday name),\n    ``%b`` (abbreviated month name), ``%B`` (full month name),\n    or ``%p`` (AM/PM).\n\nTo enable a form field to localize input and output data use its ``localize``\nargument::\n\n    class CashRegisterForm(forms.Form):\n       product = forms.CharField()\n       revenue = forms.DecimalField(max_digits=4, decimal_places=2, localize=True)\n\n.. _topic-l10n-templates:\n\nControlling localization in templates\n=====================================\n\nWhen you have enabled formatting with :setting:`USE_L10N`, Django\nwill try to use a locale specific format whenever it outputs a value\nin a template.\n\nHowever, it may not always be appropriate to use localized values --\nfor example, if you're outputting JavaScript or XML that is designed\nto be machine-readable, you will always want unlocalized values. You\nmay also want to use localization in selected templates, rather than\nusing localization everywhere.\n\nTo allow for fine control over the use of localization, Django\nprovides the ``l10n`` template library that contains the following\ntags and filters.\n\nTemplate tags\n-------------\n\n.. templatetag:: localize\n\n``localize``\n~~~~~~~~~~~~\n\nEnables or disables localization of template variables in the\ncontained block.\n\nThis tag allows a more fine grained control of localization than\n:setting:`USE_L10N`.\n\nTo activate or deactivate localization for a template block, use::\n\n    {% load l10n %}\n\n    {% localize on %}\n        {{ value }}\n    {% endlocalize %}\n\n    {% localize off %}\n        {{ value }}\n    {% endlocalize %}\n\n.. note::\n\n    The value of :setting:`USE_L10N` isn't respected inside of a\n    ``{% localize %}`` block.\n\nSee :tfilter:`localize` and :tfilter:`unlocalize` for template filters that will\ndo the same job on a per-variable basis.\n\nTemplate filters\n----------------\n\n.. templatefilter:: localize\n\n``localize``\n~~~~~~~~~~~~\n\nForces localization of a single value.\n\nFor example::\n\n    {% load l10n %}\n\n    {{ value|localize }}\n\nTo disable localization on a single value, use :tfilter:`unlocalize`. To control\nlocalization over a large section of a template, use the :ttag:`localize` template\ntag.\n\n.. templatefilter:: unlocalize\n\n``unlocalize``\n~~~~~~~~~~~~~~\n\nForces a single value to be printed without localization.\n\nFor example::\n\n    {% load l10n %}\n\n    {{ value|unlocalize }}\n\nTo force localization of a single value, use :tfilter:`localize`. To\ncontrol localization over a large section of a template, use the\n:ttag:`localize` template tag.\n\n.. _custom-format-files:\n\nCreating custom format files\n============================\n\nDjango provides format definitions for many locales, but sometimes you might\nwant to create your own, because a format files doesn't exist for your locale,\nor because you want to overwrite some of the values.\n\nTo use custom formats, specify the path where you'll place format files\nfirst.  To do that, set your :setting:`FORMAT_MODULE_PATH` setting to the\npackage where format files will exist, for instance::\n\n    FORMAT_MODULE_PATH = [\n        'mysite.formats',\n        'some_app.formats',\n    ]\n\nFiles are not placed directly in this directory, but in a directory named as\nthe locale, and must be named ``formats.py``. Be careful not to put sensitive\ninformation in these files as values inside can be exposed if you pass the\nstring to ``django.utils.formats.get_format()`` (used by the :tfilter:`date`\ntemplate filter).\n\nTo customize the English formats, a structure like this would be needed::\n\n    mysite/\n        formats/\n            __init__.py\n            en/\n                __init__.py\n                formats.py\n\nwhere :file:`formats.py` contains custom format definitions. For example::\n\n    THOUSAND_SEPARATOR = '\\xa0'\n\nto use a non-breaking space (Unicode ``00A0``) as a thousand separator,\ninstead of the default for English, a comma.\n\nLimitations of the provided locale formats\n==========================================\n\nSome locales use context-sensitive formats for numbers, which Django's\nlocalization system cannot handle automatically.\n\nSwitzerland (German)\n--------------------\n\nThe Swiss number formatting depends on the type of number that is being\nformatted. For monetary values, a comma is used as the thousand separator and\na decimal point for the decimal separator. For all other numbers, a comma is\nused as decimal separator and a space as thousand separator. The locale format\nprovided by Django uses the generic separators, a comma for decimal and a space\nfor thousand separators.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":289,"nodeType":"TextFile","repoName":null,"name":"aggregation.txt","path":"docs/topics/db","text":"===========\nAggregation\n===========\n\n.. currentmodule:: django.db.models\n\nThe topic guide on :doc:`Django's database-abstraction API </topics/db/queries>`\ndescribed the way that you can use Django queries that create,\nretrieve, update and delete individual objects. However, sometimes you will\nneed to retrieve values that are derived by summarizing or *aggregating* a\ncollection of objects. This topic guide describes the ways that aggregate values\ncan be generated and returned using Django queries.\n\nThroughout this guide, we'll refer to the following models. These models are\nused to track the inventory for a series of online bookstores:\n\n.. _queryset-model-example:\n\n.. code-block:: python\n\n    from django.db import models\n\n    class Author(models.Model):\n        name = models.CharField(max_length=100)\n        age = models.IntegerField()\n\n    class Publisher(models.Model):\n        name = models.CharField(max_length=300)\n\n    class Book(models.Model):\n        name = models.CharField(max_length=300)\n        pages = models.IntegerField()\n        price = models.DecimalField(max_digits=10, decimal_places=2)\n        rating = models.FloatField()\n        authors = models.ManyToManyField(Author)\n        publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)\n        pubdate = models.DateField()\n\n    class Store(models.Model):\n        name = models.CharField(max_length=300)\n        books = models.ManyToManyField(Book)\n\nCheat sheet\n===========\n\nIn a hurry? Here's how to do common aggregate queries, assuming the models\nabove::\n\n    # Total number of books.\n    >>> Book.objects.count()\n    2452\n\n    # Total number of books with publisher=BaloneyPress\n    >>> Book.objects.filter(publisher__name='BaloneyPress').count()\n    73\n\n    # Average price across all books.\n    >>> from django.db.models import Avg\n    >>> Book.objects.all().aggregate(Avg('price'))\n    {'price__avg': 34.35}\n\n    # Max price across all books.\n    >>> from django.db.models import Max\n    >>> Book.objects.all().aggregate(Max('price'))\n    {'price__max': Decimal('81.20')}\n\n    # Difference between the highest priced book and the average price of all books.\n    >>> from django.db.models import FloatField\n    >>> Book.objects.aggregate(\n    ...     price_diff=Max('price', output_field=FloatField()) - Avg('price'))\n    {'price_diff': 46.85}\n\n    # All the following queries involve traversing the Book<->Publisher\n    # foreign key relationship backwards.\n\n    # Each publisher, each with a count of books as a \"num_books\" attribute.\n    >>> from django.db.models import Count\n    >>> pubs = Publisher.objects.annotate(num_books=Count('book'))\n    >>> pubs\n    <QuerySet [<Publisher: BaloneyPress>, <Publisher: SalamiPress>, ...]>\n    >>> pubs[0].num_books\n    73\n\n    # Each publisher, with a separate count of books with a rating above and below 5\n    >>> from django.db.models import Q\n    >>> above_5 = Count('book', filter=Q(book__rating__gt=5))\n    >>> below_5 = Count('book', filter=Q(book__rating__lte=5))\n    >>> pubs = Publisher.objects.annotate(below_5=below_5).annotate(above_5=above_5)\n    >>> pubs[0].above_5\n    23\n    >>> pubs[0].below_5\n    12\n\n    # The top 5 publishers, in order by number of books.\n    >>> pubs = Publisher.objects.annotate(num_books=Count('book')).order_by('-num_books')[:5]\n    >>> pubs[0].num_books\n    1323\n\nGenerating aggregates over a ``QuerySet``\n=========================================\n\nDjango provides two ways to generate aggregates. The first way is to generate\nsummary values over an entire ``QuerySet``. For example, say you wanted to\ncalculate the average price of all books available for sale. Django's query\nsyntax provides a means for describing the set of all books::\n\n    >>> Book.objects.all()\n\nWhat we need is a way to calculate summary values over the objects that\nbelong to this ``QuerySet``. This is done by appending an ``aggregate()``\nclause onto the ``QuerySet``::\n\n    >>> from django.db.models import Avg\n    >>> Book.objects.all().aggregate(Avg('price'))\n    {'price__avg': 34.35}\n\nThe ``all()`` is redundant in this example, so this could be simplified to::\n\n    >>> Book.objects.aggregate(Avg('price'))\n    {'price__avg': 34.35}\n\nThe argument to the ``aggregate()`` clause describes the aggregate value that\nwe want to compute - in this case, the average of the ``price`` field on the\n``Book`` model. A list of the aggregate functions that are available can be\nfound in the :ref:`QuerySet reference <aggregation-functions>`.\n\n``aggregate()`` is a terminal clause for a ``QuerySet`` that, when invoked,\nreturns a dictionary of name-value pairs. The name is an identifier for the\naggregate value; the value is the computed aggregate. The name is\nautomatically generated from the name of the field and the aggregate function.\nIf you want to manually specify a name for the aggregate value, you can do so\nby providing that name when you specify the aggregate clause::\n\n    >>> Book.objects.aggregate(average_price=Avg('price'))\n    {'average_price': 34.35}\n\nIf you want to generate more than one aggregate, you add another argument to\nthe ``aggregate()`` clause. So, if we also wanted to know the maximum and\nminimum price of all books, we would issue the query::\n\n    >>> from django.db.models import Avg, Max, Min\n    >>> Book.objects.aggregate(Avg('price'), Max('price'), Min('price'))\n    {'price__avg': 34.35, 'price__max': Decimal('81.20'), 'price__min': Decimal('12.99')}\n\nGenerating aggregates for each item in a ``QuerySet``\n=====================================================\n\nThe second way to generate summary values is to generate an independent\nsummary for each object in a :class:`.QuerySet`. For example, if you are\nretrieving a list of books, you may want to know how many authors contributed\nto each book. Each Book has a many-to-many relationship with the Author; we\nwant to summarize this relationship for each book in the ``QuerySet``.\n\nPer-object summaries can be generated using the\n:meth:`~.QuerySet.annotate` clause. When an ``annotate()`` clause is\nspecified, each object in the ``QuerySet`` will be annotated with the\nspecified values.\n\nThe syntax for these annotations is identical to that used for the\n:meth:`~.QuerySet.aggregate` clause. Each argument to ``annotate()`` describes\nan aggregate that is to be calculated. For example, to annotate books with the\nnumber of authors::\n\n    # Build an annotated queryset\n    >>> from django.db.models import Count\n    >>> q = Book.objects.annotate(Count('authors'))\n    # Interrogate the first object in the queryset\n    >>> q[0]\n    <Book: The Definitive Guide to Django>\n    >>> q[0].authors__count\n    2\n    # Interrogate the second object in the queryset\n    >>> q[1]\n    <Book: Practical Django Projects>\n    >>> q[1].authors__count\n    1\n\nAs with ``aggregate()``, the name for the annotation is automatically derived\nfrom the name of the aggregate function and the name of the field being\naggregated. You can override this default name by providing an alias when you\nspecify the annotation::\n\n    >>> q = Book.objects.annotate(num_authors=Count('authors'))\n    >>> q[0].num_authors\n    2\n    >>> q[1].num_authors\n    1\n\nUnlike ``aggregate()``, ``annotate()`` is *not* a terminal clause. The output\nof the ``annotate()`` clause is a ``QuerySet``; this ``QuerySet`` can be\nmodified using any other ``QuerySet`` operation, including ``filter()``,\n``order_by()``, or even additional calls to ``annotate()``.\n\n.. _combining-multiple-aggregations:\n\nCombining multiple aggregations\n-------------------------------\n\nCombining multiple aggregations with ``annotate()`` will :ticket:`yield the\nwrong results <10060>` because joins are used instead of subqueries:\n\n    >>> book = Book.objects.first()\n    >>> book.authors.count()\n    2\n    >>> book.store_set.count()\n    3\n    >>> q = Book.objects.annotate(Count('authors'), Count('store'))\n    >>> q[0].authors__count\n    6\n    >>> q[0].store__count\n    6\n\nFor most aggregates, there is no way to avoid this problem, however, the\n:class:`~django.db.models.Count` aggregate has a ``distinct`` parameter that\nmay help:\n\n    >>> q = Book.objects.annotate(Count('authors', distinct=True), Count('store', distinct=True))\n    >>> q[0].authors__count\n    2\n    >>> q[0].store__count\n    3\n\n.. admonition:: If in doubt, inspect the SQL query!\n\n    In order to understand what happens in your query, consider inspecting the\n    ``query`` property of your ``QuerySet``.\n\nJoins and aggregates\n====================\n\nSo far, we have dealt with aggregates over fields that belong to the\nmodel being queried. However, sometimes the value you want to aggregate\nwill belong to a model that is related to the model you are querying.\n\nWhen specifying the field to be aggregated in an aggregate function, Django\nwill allow you to use the same :ref:`double underscore notation\n<field-lookups-intro>` that is used when referring to related fields in\nfilters. Django will then handle any table joins that are required to retrieve\nand aggregate the related value.\n\nFor example, to find the price range of books offered in each store,\nyou could use the annotation::\n\n    >>> from django.db.models import Max, Min\n    >>> Store.objects.annotate(min_price=Min('books__price'), max_price=Max('books__price'))\n\nThis tells Django to retrieve the ``Store`` model, join (through the\nmany-to-many relationship) with the ``Book`` model, and aggregate on the\nprice field of the book model to produce a minimum and maximum value.\n\nThe same rules apply to the ``aggregate()`` clause. If you wanted to\nknow the lowest and highest price of any book that is available for sale\nin any of the stores, you could use the aggregate::\n\n    >>> Store.objects.aggregate(min_price=Min('books__price'), max_price=Max('books__price'))\n\nJoin chains can be as deep as you require. For example, to extract the\nage of the youngest author of any book available for sale, you could\nissue the query::\n\n    >>> Store.objects.aggregate(youngest_age=Min('books__authors__age'))\n\nFollowing relationships backwards\n---------------------------------\n\nIn a way similar to :ref:`lookups-that-span-relationships`, aggregations and\nannotations on fields of models or models that are related to the one you are\nquerying can include traversing \"reverse\" relationships. The lowercase name\nof related models and double-underscores are used here too.\n\nFor example, we can ask for all publishers, annotated with their respective\ntotal book stock counters (note how we use ``'book'`` to specify the\n``Publisher`` -> ``Book`` reverse foreign key hop)::\n\n    >>> from django.db.models import Avg, Count, Min, Sum\n    >>> Publisher.objects.annotate(Count('book'))\n\n(Every ``Publisher`` in the resulting ``QuerySet`` will have an extra attribute\ncalled ``book__count``.)\n\nWe can also ask for the oldest book of any of those managed by every publisher::\n\n    >>> Publisher.objects.aggregate(oldest_pubdate=Min('book__pubdate'))\n\n(The resulting dictionary will have a key called ``'oldest_pubdate'``. If no\nsuch alias were specified, it would be the rather long ``'book__pubdate__min'``.)\n\nThis doesn't apply just to foreign keys. It also works with many-to-many\nrelations. For example, we can ask for every author, annotated with the total\nnumber of pages considering all the books the author has (co-)authored (note how we\nuse ``'book'`` to specify the ``Author`` -> ``Book`` reverse many-to-many hop)::\n\n    >>> Author.objects.annotate(total_pages=Sum('book__pages'))\n\n(Every ``Author`` in the resulting ``QuerySet`` will have an extra attribute\ncalled ``total_pages``. If no such alias were specified, it would be the rather\nlong ``book__pages__sum``.)\n\nOr ask for the average rating of all the books written by author(s) we have on\nfile::\n\n    >>> Author.objects.aggregate(average_rating=Avg('book__rating'))\n\n(The resulting dictionary will have a key called ``'average_rating'``. If no\nsuch alias were specified, it would be the rather long ``'book__rating__avg'``.)\n\nAggregations and other ``QuerySet`` clauses\n===========================================\n\n``filter()`` and ``exclude()``\n------------------------------\n\nAggregates can also participate in filters. Any ``filter()`` (or\n``exclude()``) applied to normal model fields will have the effect of\nconstraining the objects that are considered for aggregation.\n\nWhen used with an ``annotate()`` clause, a filter has the effect of\nconstraining the objects for which an annotation is calculated. For example,\nyou can generate an annotated list of all books that have a title starting\nwith \"Django\" using the query::\n\n    >>> from django.db.models import Avg, Count\n    >>> Book.objects.filter(name__startswith=\"Django\").annotate(num_authors=Count('authors'))\n\nWhen used with an ``aggregate()`` clause, a filter has the effect of\nconstraining the objects over which the aggregate is calculated.\nFor example, you can generate the average price of all books with a\ntitle that starts with \"Django\" using the query::\n\n    >>> Book.objects.filter(name__startswith=\"Django\").aggregate(Avg('price'))\n\n.. _filtering-on-annotations:\n\nFiltering on annotations\n~~~~~~~~~~~~~~~~~~~~~~~~\n\nAnnotated values can also be filtered. The alias for the annotation can be\nused in ``filter()`` and ``exclude()`` clauses in the same way as any other\nmodel field.\n\nFor example, to generate a list of books that have more than one author,\nyou can issue the query::\n\n    >>> Book.objects.annotate(num_authors=Count('authors')).filter(num_authors__gt=1)\n\nThis query generates an annotated result set, and then generates a filter\nbased upon that annotation.\n\nIf you need two annotations with two separate filters you can use the\n``filter`` argument with any aggregate. For example, to generate a list of\nauthors with a count of highly rated books::\n\n    >>> highly_rated = Count('book', filter=Q(book__rating__gte=7))\n    >>> Author.objects.annotate(num_books=Count('book'), highly_rated_books=highly_rated)\n\nEach ``Author`` in the result set will have the ``num_books`` and\n``highly_rated_books`` attributes.\n\n.. admonition:: Choosing between ``filter`` and ``QuerySet.filter()``\n\n    Avoid using the ``filter`` argument with a single annotation or\n    aggregation. It's more efficient to use ``QuerySet.filter()`` to exclude\n    rows. The aggregation ``filter`` argument is only useful when using two or\n    more aggregations over the same relations with different conditionals.\n\nOrder of ``annotate()`` and ``filter()`` clauses\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nWhen developing a complex query that involves both ``annotate()`` and\n``filter()`` clauses, pay particular attention to the order in which the\nclauses are applied to the ``QuerySet``.\n\nWhen an ``annotate()`` clause is applied to a query, the annotation is computed\nover the state of the query up to the point where the annotation is requested.\nThe practical implication of this is that ``filter()`` and ``annotate()`` are\nnot commutative operations.\n\nGiven:\n\n* Publisher A has two books with ratings 4 and 5.\n* Publisher B has two books with ratings 1 and 4.\n* Publisher C has one book with rating 1.\n\nHere's an example with the ``Count`` aggregate::\n\n    >>> a, b = Publisher.objects.annotate(num_books=Count('book', distinct=True)).filter(book__rating__gt=3.0)\n    >>> a, a.num_books\n    (<Publisher: A>, 2)\n    >>> b, b.num_books\n    (<Publisher: B>, 2)\n\n    >>> a, b = Publisher.objects.filter(book__rating__gt=3.0).annotate(num_books=Count('book'))\n    >>> a, a.num_books\n    (<Publisher: A>, 2)\n    >>> b, b.num_books\n    (<Publisher: B>, 1)\n\nBoth queries return a list of publishers that have at least one book with a\nrating exceeding 3.0, hence publisher C is excluded.\n\nIn the first query, the annotation precedes the filter, so the filter has no\neffect on the annotation. ``distinct=True`` is required to avoid a :ref:`query\nbug <combining-multiple-aggregations>`.\n\nThe second query counts the number of books that have a rating exceeding 3.0\nfor each publisher. The filter precedes the annotation, so the filter\nconstrains the objects considered when calculating the annotation.\n\nHere's another example with the ``Avg`` aggregate::\n\n    >>> a, b = Publisher.objects.annotate(avg_rating=Avg('book__rating')).filter(book__rating__gt=3.0)\n    >>> a, a.avg_rating\n    (<Publisher: A>, 4.5)  # (5+4)/2\n    >>> b, b.avg_rating\n    (<Publisher: B>, 2.5)  # (1+4)/2\n\n    >>> a, b = Publisher.objects.filter(book__rating__gt=3.0).annotate(avg_rating=Avg('book__rating'))\n    >>> a, a.avg_rating\n    (<Publisher: A>, 4.5)  # (5+4)/2\n    >>> b, b.avg_rating\n    (<Publisher: B>, 4.0)  # 4/1 (book with rating 1 excluded)\n\nThe first query asks for the average rating of all a publisher's books for\npublisher's that have at least one book with a rating exceeding 3.0. The second\nquery asks for the average of a publisher's book's ratings for only those\nratings exceeding 3.0.\n\nIt's difficult to intuit how the ORM will translate complex querysets into SQL\nqueries so when in doubt, inspect the SQL with ``str(queryset.query)`` and\nwrite plenty of tests.\n\n``order_by()``\n--------------\n\nAnnotations can be used as a basis for ordering. When you\ndefine an ``order_by()`` clause, the aggregates you provide can reference\nany alias defined as part of an ``annotate()`` clause in the query.\n\nFor example, to order a ``QuerySet`` of books by the number of authors\nthat have contributed to the book, you could use the following query::\n\n    >>> Book.objects.annotate(num_authors=Count('authors')).order_by('num_authors')\n\n``values()``\n------------\n\nOrdinarily, annotations are generated on a per-object basis - an annotated\n``QuerySet`` will return one result for each object in the original\n``QuerySet``. However, when a ``values()`` clause is used to constrain the\ncolumns that are returned in the result set, the method for evaluating\nannotations is slightly different. Instead of returning an annotated result\nfor each result in the original ``QuerySet``, the original results are\ngrouped according to the unique combinations of the fields specified in the\n``values()`` clause. An annotation is then provided for each unique group;\nthe annotation is computed over all members of the group.\n\nFor example, consider an author query that attempts to find out the average\nrating of books written by each author:\n\n    >>> Author.objects.annotate(average_rating=Avg('book__rating'))\n\nThis will return one result for each author in the database, annotated with\ntheir average book rating.\n\nHowever, the result will be slightly different if you use a ``values()`` clause::\n\n    >>> Author.objects.values('name').annotate(average_rating=Avg('book__rating'))\n\nIn this example, the authors will be grouped by name, so you will only get\nan annotated result for each *unique* author name. This means if you have\ntwo authors with the same name, their results will be merged into a single\nresult in the output of the query; the average will be computed as the\naverage over the books written by both authors.\n\nOrder of ``annotate()`` and ``values()`` clauses\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nAs with the ``filter()`` clause, the order in which ``annotate()`` and\n``values()`` clauses are applied to a query is significant. If the\n``values()`` clause precedes the ``annotate()``, the annotation will be\ncomputed using the grouping described by the ``values()`` clause.\n\nHowever, if the ``annotate()`` clause precedes the ``values()`` clause,\nthe annotations will be generated over the entire query set. In this case,\nthe ``values()`` clause only constrains the fields that are generated on\noutput.\n\nFor example, if we reverse the order of the ``values()`` and ``annotate()``\nclause from our previous example::\n\n    >>> Author.objects.annotate(average_rating=Avg('book__rating')).values('name', 'average_rating')\n\nThis will now yield one unique result for each author; however, only\nthe author's name and the ``average_rating`` annotation will be returned\nin the output data.\n\nYou should also note that ``average_rating`` has been explicitly included\nin the list of values to be returned. This is required because of the\nordering of the ``values()`` and ``annotate()`` clause.\n\nIf the ``values()`` clause precedes the ``annotate()`` clause, any annotations\nwill be automatically added to the result set. However, if the ``values()``\nclause is applied after the ``annotate()`` clause, you need to explicitly\ninclude the aggregate column.\n\n.. _aggregation-ordering-interaction:\n\nInteraction with default ordering or ``order_by()``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nFields that are mentioned in the ``order_by()`` part of a queryset (or which\nare used in the default ordering on a model) are used when selecting the\noutput data, even if they are not otherwise specified in the ``values()``\ncall. These extra fields are used to group \"like\" results together and they\ncan make otherwise identical result rows appear to be separate. This shows up,\nparticularly, when counting things.\n\nBy way of example, suppose you have a model like this::\n\n    from django.db import models\n\n    class Item(models.Model):\n        name = models.CharField(max_length=10)\n        data = models.IntegerField()\n\n        class Meta:\n            ordering = [\"name\"]\n\nThe important part here is the default ordering on the ``name`` field. If you\nwant to count how many times each distinct ``data`` value appears, you might\ntry this::\n\n    # Warning: not quite correct!\n    Item.objects.values(\"data\").annotate(Count(\"id\"))\n\n...which will group the ``Item`` objects by their common ``data`` values and\nthen count the number of ``id`` values in each group. Except that it won't\nquite work. The default ordering by ``name`` will also play a part in the\ngrouping, so this query will group by distinct ``(data, name)`` pairs, which\nisn't what you want. Instead, you should construct this queryset::\n\n    Item.objects.values(\"data\").annotate(Count(\"id\")).order_by()\n\n...clearing any ordering in the query. You could also order by, say, ``data``\nwithout any harmful effects, since that is already playing a role in the\nquery.\n\nThis behavior is the same as that noted in the queryset documentation for\n:meth:`~django.db.models.query.QuerySet.distinct` and the general rule is the\nsame: normally you won't want extra columns playing a part in the result, so\nclear out the ordering, or at least make sure it's restricted only to those\nfields you also select in a ``values()`` call.\n\n.. note::\n    You might reasonably ask why Django doesn't remove the extraneous columns\n    for you. The main reason is consistency with ``distinct()`` and other\n    places: Django **never** removes ordering constraints that you have\n    specified (and we can't change those other methods' behavior, as that\n    would violate our :doc:`/misc/api-stability` policy).\n\nAggregating annotations\n-----------------------\n\nYou can also generate an aggregate on the result of an annotation. When you\ndefine an ``aggregate()`` clause, the aggregates you provide can reference\nany alias defined as part of an ``annotate()`` clause in the query.\n\nFor example, if you wanted to calculate the average number of authors per\nbook you first annotate the set of books with the author count, then\naggregate that author count, referencing the annotation field::\n\n    >>> from django.db.models import Avg, Count\n    >>> Book.objects.annotate(num_authors=Count('authors')).aggregate(Avg('num_authors'))\n    {'num_authors__avg': 1.66}\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":290,"nodeType":"TextFile","repoName":null,"name":"logging.txt","path":"docs/topics","text":"=======\nLogging\n=======\n\n.. module:: django.utils.log\n   :synopsis: Logging tools for Django applications\n\nA quick logging primer\n======================\n\nDjango uses Python's builtin :mod:`logging` module to perform system logging.\nThe usage of this module is discussed in detail in Python's own documentation.\nHowever, if you've never used Python's logging framework (or even if you have),\nhere's a quick primer.\n\nThe cast of players\n-------------------\n\nA Python logging configuration consists of four parts:\n\n* :ref:`topic-logging-parts-loggers`\n* :ref:`topic-logging-parts-handlers`\n* :ref:`topic-logging-parts-filters`\n* :ref:`topic-logging-parts-formatters`\n\n.. _topic-logging-parts-loggers:\n\nLoggers\n~~~~~~~\n\nA logger is the entry point into the logging system. Each logger is\na named bucket to which messages can be written for processing.\n\nA logger is configured to have a *log level*. This log level describes\nthe severity of the messages that the logger will handle. Python\ndefines the following log levels:\n\n* ``DEBUG``: Low level system information for debugging purposes\n\n* ``INFO``: General system information\n\n* ``WARNING``: Information describing a minor problem that has\n  occurred.\n\n* ``ERROR``: Information describing a major problem that has\n  occurred.\n\n* ``CRITICAL``: Information describing a critical problem that has\n  occurred.\n\nEach message that is written to the logger is a *Log Record*. Each log\nrecord also has a *log level* indicating the severity of that specific\nmessage. A log record can also contain useful metadata that describes\nthe event that is being logged. This can include details such as a\nstack trace or an error code.\n\nWhen a message is given to the logger, the log level of the message is\ncompared to the log level of the logger. If the log level of the\nmessage meets or exceeds the log level of the logger itself, the\nmessage will undergo further processing. If it doesn't, the message\nwill be ignored.\n\nOnce a logger has determined that a message needs to be processed,\nit is passed to a *Handler*.\n\n.. _topic-logging-parts-handlers:\n\nHandlers\n~~~~~~~~\n\nThe handler is the engine that determines what happens to each message\nin a logger. It describes a particular logging behavior, such as\nwriting a message to the screen, to a file, or to a network socket.\n\nLike loggers, handlers also have a log level. If the log level of a\nlog record doesn't meet or exceed the level of the handler, the\nhandler will ignore the message.\n\nA logger can have multiple handlers, and each handler can have a\ndifferent log level. In this way, it is possible to provide different\nforms of notification depending on the importance of a message. For\nexample, you could install one handler that forwards ``ERROR`` and\n``CRITICAL`` messages to a paging service, while a second handler\nlogs all messages (including ``ERROR`` and ``CRITICAL`` messages) to a\nfile for later analysis.\n\n.. _topic-logging-parts-filters:\n\nFilters\n~~~~~~~\n\nA filter is used to provide additional control over which log records\nare passed from logger to handler.\n\nBy default, any log message that meets log level requirements will be\nhandled. However, by installing a filter, you can place additional\ncriteria on the logging process. For example, you could install a\nfilter that only allows ``ERROR`` messages from a particular source to\nbe emitted.\n\nFilters can also be used to modify the logging record prior to being\nemitted. For example, you could write a filter that downgrades\n``ERROR`` log records to ``WARNING`` records if a particular set of\ncriteria are met.\n\nFilters can be installed on loggers or on handlers; multiple filters\ncan be used in a chain to perform multiple filtering actions.\n\n.. _topic-logging-parts-formatters:\n\nFormatters\n~~~~~~~~~~\n\nUltimately, a log record needs to be rendered as text. Formatters\ndescribe the exact format of that text. A formatter usually consists\nof a Python formatting string containing\n:ref:`LogRecord attributes <python:logrecord-attributes>`; however,\nyou can also write custom formatters to implement specific formatting behavior.\n\nUsing logging\n=============\n\nOnce you have configured your loggers, handlers, filters and\nformatters, you need to place logging calls into your code. Using the\nlogging framework works like this::\n\n    # import the logging library\n    import logging\n\n    # Get an instance of a logger\n    logger = logging.getLogger(__name__)\n\n    def my_view(request, arg1, arg):\n        ...\n        if bad_mojo:\n            # Log an error message\n            logger.error('Something went wrong!')\n\nAnd that's it! Every time the ``bad_mojo`` condition is activated, an\nerror log record will be written.\n\nNaming loggers\n--------------\n\nThe call to :func:`logging.getLogger()` obtains (creating, if\nnecessary) an instance of a logger. The logger instance is identified\nby a name. This name is used to identify the logger for configuration\npurposes.\n\nBy convention, the logger name is usually ``__name__``, the name of\nthe Python module that contains the logger. This allows you to filter\nand handle logging calls on a per-module basis. However, if you have\nsome other way of organizing your logging messages, you can provide\nany dot-separated name to identify your logger::\n\n    # Get an instance of a specific named logger\n    logger = logging.getLogger('project.interesting.stuff')\n\nThe dotted paths of logger names define a hierarchy. The\n``project.interesting`` logger is considered to be a parent of the\n``project.interesting.stuff`` logger; the ``project`` logger\nis a parent of the ``project.interesting`` logger.\n\nWhy is the hierarchy important? Well, because loggers can be set to\n*propagate* their logging calls to their parents. In this way, you can\ndefine a single set of handlers at the root of a logger tree, and\ncapture all logging calls in the subtree of loggers. A logger defined\nin the ``project`` namespace will catch all logging messages issued on\nthe ``project.interesting`` and ``project.interesting.stuff`` loggers.\n\nThis propagation can be controlled on a per-logger basis. If\nyou don't want a particular logger to propagate to its parents, you\ncan turn off this behavior.\n\nMaking logging calls\n--------------------\n\nThe logger instance contains an entry method for each of the default\nlog levels:\n\n* ``logger.debug()``\n* ``logger.info()``\n* ``logger.warning()``\n* ``logger.error()``\n* ``logger.critical()``\n\nThere are two other logging calls available:\n\n* ``logger.log()``: Manually emits a logging message with a\n  specific log level.\n\n* ``logger.exception()``: Creates an ``ERROR`` level logging\n  message wrapping the current exception stack frame.\n\n.. _configuring-logging:\n\nConfiguring logging\n===================\n\nIt isn't enough to just put logging calls into your code. You also need to\nconfigure the loggers, handlers, filters, and formatters to ensure you can use\nthe logging output.\n\nPython's logging library provides several techniques to configure\nlogging, ranging from a programmatic interface to configuration files.\nBy default, Django uses the :ref:`dictConfig format\n<logging-config-dictschema>`.\n\nIn order to configure logging, you use :setting:`LOGGING` to define a\ndictionary of logging settings. These settings describes the loggers,\nhandlers, filters and formatters that you want in your logging setup,\nand the log levels and other properties that you want those components\nto have.\n\nBy default, the :setting:`LOGGING` setting is merged with :ref:`Django's\ndefault logging configuration <default-logging-configuration>` using the\nfollowing scheme.\n\nIf the ``disable_existing_loggers`` key in the :setting:`LOGGING` dictConfig is\nset to ``True`` (which is the ``dictConfig`` default if the key is missing)\nthen all loggers from the default configuration will be disabled. Disabled\nloggers are not the same as removed; the logger will still exist, but will\nsilently discard anything logged to it, not even propagating entries to a\nparent logger. Thus you should be very careful using\n``'disable_existing_loggers': True``; it's probably not what you want. Instead,\nyou can set ``disable_existing_loggers`` to ``False`` and redefine some or all\nof the default loggers; or you can set :setting:`LOGGING_CONFIG` to ``None``\nand :ref:`handle logging config yourself <disabling-logging-configuration>`.\n\nLogging is configured as part of the general Django ``setup()`` function.\nTherefore, you can be certain that loggers are always ready for use in your\nproject code.\n\nExamples\n--------\n\nThe full documentation for :ref:`dictConfig format <logging-config-dictschema>`\nis the best source of information about logging configuration dictionaries.\nHowever, to give you a taste of what is possible, here are several examples.\n\nTo begin, here's a small configuration that will allow you to output all log\nmessages to the console:\n\n.. code-block:: python\n    :caption: settings.py\n\n    import os\n\n    LOGGING = {\n        'version': 1,\n        'disable_existing_loggers': False,\n        'handlers': {\n            'console': {\n                'class': 'logging.StreamHandler',\n            },\n        },\n        'root': {\n            'handlers': ['console'],\n            'level': 'WARNING',\n        },\n    }\n\nThis configures the parent ``root`` logger to send messages with the\n``WARNING`` level and higher to the console handler. By adjusting the level to\n``INFO`` or ``DEBUG`` you can display more messages. This may be useful during\ndevelopment.\n\nNext we can add more fine-grained logging. Here's an example of how to make the\nlogging system print more messages from just the :ref:`django-logger` named\nlogger:\n\n.. code-block:: python\n    :caption: settings.py\n\n    import os\n\n    LOGGING = {\n        'version': 1,\n        'disable_existing_loggers': False,\n        'handlers': {\n            'console': {\n                'class': 'logging.StreamHandler',\n            },\n        },\n        'root': {\n            'handlers': ['console'],\n            'level': 'WARNING',\n        },\n        'loggers': {\n            'django': {\n                'handlers': ['console'],\n                'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),\n                'propagate': False,\n            },\n        },\n    }\n\nBy default, this config sends messages from the ``django`` logger of level\n``INFO`` or higher to the console. This is the same level as Django's default\nlogging config, except that the default config only displays log records when\n``DEBUG=True``. Django does not log many such ``INFO`` level messages. With\nthis config, however, you can also set the environment variable\n``DJANGO_LOG_LEVEL=DEBUG`` to see all of Django's debug logging which is very\nverbose as it includes all database queries.\n\nYou don't have to log to the console. Here's a configuration which writes all\nlogging from the :ref:`django-logger` named logger to a local file:\n\n.. code-block:: python\n    :caption: settings.py\n\n    LOGGING = {\n        'version': 1,\n        'disable_existing_loggers': False,\n        'handlers': {\n            'file': {\n                'level': 'DEBUG',\n                'class': 'logging.FileHandler',\n                'filename': '/path/to/django/debug.log',\n            },\n        },\n        'loggers': {\n            'django': {\n                'handlers': ['file'],\n                'level': 'DEBUG',\n                'propagate': True,\n            },\n        },\n    }\n\nIf you use this example, be sure to change the ``'filename'`` path to a\nlocation that's writable by the user that's running the Django application.\n\nFinally, here's an example of a fairly complex logging setup:\n\n.. code-block:: python\n    :caption: settings.py\n\n    LOGGING = {\n        'version': 1,\n        'disable_existing_loggers': False,\n        'formatters': {\n            'verbose': {\n                'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',\n                'style': '{',\n            },\n            'simple': {\n                'format': '{levelname} {message}',\n                'style': '{',\n            },\n        },\n        'filters': {\n            'special': {\n                '()': 'project.logging.SpecialFilter',\n                'foo': 'bar',\n            },\n            'require_debug_true': {\n                '()': 'django.utils.log.RequireDebugTrue',\n            },\n        },\n        'handlers': {\n            'console': {\n                'level': 'INFO',\n                'filters': ['require_debug_true'],\n                'class': 'logging.StreamHandler',\n                'formatter': 'simple'\n            },\n            'mail_admins': {\n                'level': 'ERROR',\n                'class': 'django.utils.log.AdminEmailHandler',\n                'filters': ['special']\n            }\n        },\n        'loggers': {\n            'django': {\n                'handlers': ['console'],\n                'propagate': True,\n            },\n            'django.request': {\n                'handlers': ['mail_admins'],\n                'level': 'ERROR',\n                'propagate': False,\n            },\n            'myproject.custom': {\n                'handlers': ['console', 'mail_admins'],\n                'level': 'INFO',\n                'filters': ['special']\n            }\n        }\n    }\n\nThis logging configuration does the following things:\n\n* Identifies the configuration as being in 'dictConfig version 1'\n  format. At present, this is the only dictConfig format version.\n\n* Defines two formatters:\n\n  * ``simple``, that outputs the log level name (e.g., ``DEBUG``) and the log\n    message.\n\n    The ``format`` string is a normal Python formatting string\n    describing the details that are to be output on each logging\n    line. The full list of detail that can be output can be\n    found in :ref:`formatter-objects`.\n\n  * ``verbose``, that outputs the log level name, the log\n    message, plus the time, process, thread and module that\n    generate the log message.\n\n* Defines two filters:\n\n  * ``project.logging.SpecialFilter``, using the alias ``special``. If this\n    filter required additional arguments, they can be provided as additional\n    keys in the filter configuration dictionary. In this case, the argument\n    ``foo`` will be given a value of ``bar`` when instantiating\n    ``SpecialFilter``.\n\n  * ``django.utils.log.RequireDebugTrue``, which passes on records when\n    :setting:`DEBUG` is ``True``.\n\n* Defines two handlers:\n\n  * ``console``, a :class:`~logging.StreamHandler`, which prints any ``INFO``\n    (or higher) message to ``sys.stderr``. This handler uses the ``simple``\n    output format.\n\n  * ``mail_admins``, an :class:`AdminEmailHandler`, which emails any ``ERROR``\n    (or higher) message to the site :setting:`ADMINS`. This handler uses the\n    ``special`` filter.\n\n* Configures three loggers:\n\n  * ``django``, which passes all messages to the ``console`` handler.\n\n  * ``django.request``, which passes all ``ERROR`` messages to\n    the ``mail_admins`` handler. In addition, this logger is\n    marked to *not* propagate messages. This means that log\n    messages written to ``django.request`` will not be handled\n    by the ``django`` logger.\n\n  * ``myproject.custom``, which passes all messages at ``INFO``\n    or higher that also pass the ``special`` filter to two\n    handlers -- the ``console``, and ``mail_admins``. This\n    means that all ``INFO`` level messages (or higher) will be\n    printed to the console; ``ERROR`` and ``CRITICAL``\n    messages will also be output via email.\n\nCustom logging configuration\n----------------------------\n\nIf you don't want to use Python's dictConfig format to configure your\nlogger, you can specify your own configuration scheme.\n\nThe :setting:`LOGGING_CONFIG` setting defines the callable that will\nbe used to configure Django's loggers. By default, it points at\nPython's :func:`logging.config.dictConfig()` function. However, if you want to\nuse a different configuration process, you can use any other callable\nthat takes a single argument. The contents of :setting:`LOGGING` will\nbe provided as the value of that argument when logging is configured.\n\n.. _disabling-logging-configuration:\n\nDisabling logging configuration\n-------------------------------\n\nIf you don't want to configure logging at all (or you want to manually\nconfigure logging using your own approach), you can set\n:setting:`LOGGING_CONFIG` to ``None``. This will disable the\nconfiguration process for :ref:`Django's default logging\n<default-logging-configuration>`. Here's an example that disables Django's\nlogging configuration and then manually configures logging:\n\n.. code-block:: python\n    :caption: settings.py\n\n    LOGGING_CONFIG = None\n\n    import logging.config\n    logging.config.dictConfig(...)\n\nSetting :setting:`LOGGING_CONFIG` to ``None`` only means that the automatic\nconfiguration process is disabled, not logging itself. If you disable the\nconfiguration process, Django will still make logging calls, falling back to\nwhatever default logging behavior is defined.\n\nDjango's logging extensions\n===========================\n\nDjango provides a number of utilities to handle the unique\nrequirements of logging in Web server environment.\n\nLoggers\n-------\n\nDjango provides several built-in loggers.\n\n.. _django-logger:\n\n``django``\n~~~~~~~~~~\n\nThe catch-all logger for messages in the  ``django`` hierarchy. No messages are\nposted using this name but instead using one of the loggers below.\n\n.. _django-request-logger:\n\n``django.request``\n~~~~~~~~~~~~~~~~~~\n\nLog messages related to the handling of requests. 5XX responses are\nraised as ``ERROR`` messages; 4XX responses are raised as ``WARNING``\nmessages. Requests that are logged to the ``django.security`` logger aren't\nlogged to ``django.request``.\n\nMessages to this logger have the following extra context:\n\n* ``status_code``: The HTTP response code associated with the\n  request.\n\n* ``request``: The request object that generated the logging\n  message.\n\n.. _django-server-logger:\n\n``django.server``\n~~~~~~~~~~~~~~~~~\n\nLog messages related to the handling of requests received by the server invoked\nby the :djadmin:`runserver` command. HTTP 5XX responses are logged as ``ERROR``\nmessages, 4XX responses are logged as ``WARNING`` messages, and everything else\nis logged as ``INFO``.\n\nMessages to this logger have the following extra context:\n\n* ``status_code``: The HTTP response code associated with the request.\n\n* ``request``: The request object that generated the logging message.\n\n.. _django-template-logger:\n\n``django.template``\n~~~~~~~~~~~~~~~~~~~\n\nLog messages related to the rendering of templates.\n\n* Missing context variables are logged as ``DEBUG`` messages.\n\n.. _django-db-logger:\n\n``django.db.backends``\n~~~~~~~~~~~~~~~~~~~~~~\n\nMessages relating to the interaction of code with the database. For example,\nevery application-level SQL statement executed by a request is logged at the\n``DEBUG`` level to this logger.\n\nMessages to this logger have the following extra context:\n\n* ``duration``: The time taken to execute the SQL statement.\n* ``sql``: The SQL statement that was executed.\n* ``params``: The parameters that were used in the SQL call.\n\nFor performance reasons, SQL logging is only enabled when\n``settings.DEBUG`` is set to ``True``, regardless of the logging\nlevel or handlers that are installed.\n\nThis logging does not include framework-level initialization (e.g.\n``SET TIMEZONE``) or transaction management queries (e.g. ``BEGIN``,\n``COMMIT``, and ``ROLLBACK``). Turn on query logging in your database if you\nwish to view all database queries.\n\n.. _django-security-logger:\n\n``django.security.*``\n~~~~~~~~~~~~~~~~~~~~~~\n\nThe security loggers will receive messages on any occurrence of\n:exc:`~django.core.exceptions.SuspiciousOperation` and other security-related\nerrors. There is a sub-logger for each subtype of security error, including all\n``SuspiciousOperation``\\s. The level of the log event depends on where the\nexception is handled.  Most occurrences are logged as a warning, while\nany ``SuspiciousOperation`` that reaches the WSGI handler will be logged as an\nerror. For example, when an HTTP ``Host`` header is included in a request from\na client that does not match :setting:`ALLOWED_HOSTS`, Django will return a 400\nresponse, and an error message will be logged to the\n``django.security.DisallowedHost`` logger.\n\nThese log events will reach the ``django`` logger by default, which mails error\nevents to admins when ``DEBUG=False``. Requests resulting in a 400 response due\nto a ``SuspiciousOperation`` will not be logged to the ``django.request``\nlogger, but only to the ``django.security`` logger.\n\nTo silence a particular type of ``SuspiciousOperation``, you can override that\nspecific logger following this example::\n\n    'handlers': {\n        'null': {\n            'class': 'logging.NullHandler',\n        },\n    },\n    'loggers': {\n        'django.security.DisallowedHost': {\n            'handlers': ['null'],\n            'propagate': False,\n        },\n    },\n\nOther ``django.security`` loggers not based on ``SuspiciousOperation`` are:\n\n* ``django.security.csrf``: For :ref:`CSRF failures <csrf-rejected-requests>`.\n\n``django.db.backends.schema``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nLogs the SQL queries that are executed during schema changes to the database by\nthe :doc:`migrations framework </topics/migrations>`. Note that it won't log the\nqueries executed by :class:`~django.db.migrations.operations.RunPython`.\nMessages to this logger have ``params`` and ``sql`` in their extra context (but\nunlike ``django.db.backends``, not duration). The values have the same meaning\nas explained in :ref:`django-db-logger`.\n\nHandlers\n--------\n\nDjango provides one log handler in addition to those provided by the\nPython logging module.\n\n.. class:: AdminEmailHandler(include_html=False, email_backend=None, reporter_class=None)\n\n    This handler sends an email to the site :setting:`ADMINS` for each log\n    message it receives.\n\n    If the log record contains a ``request`` attribute, the full details\n    of the request will be included in the email. The email subject will\n    include the phrase \"internal IP\" if the client's IP address is in the\n    :setting:`INTERNAL_IPS` setting; if not, it will include \"EXTERNAL IP\".\n\n    If the log record contains stack trace information, that stack\n    trace will be included in the email.\n\n    The ``include_html`` argument of ``AdminEmailHandler`` is used to\n    control whether the traceback email includes an HTML attachment\n    containing the full content of the debug Web page that would have been\n    produced if :setting:`DEBUG` were ``True``. To set this value in your\n    configuration, include it in the handler definition for\n    ``django.utils.log.AdminEmailHandler``, like this::\n\n        'handlers': {\n            'mail_admins': {\n                'level': 'ERROR',\n                'class': 'django.utils.log.AdminEmailHandler',\n                'include_html': True,\n            }\n        },\n\n    Note that this HTML version of the email contains a full traceback,\n    with names and values of local variables at each level of the stack, plus\n    the values of your Django settings. This information is potentially very\n    sensitive, and you may not want to send it over email. Consider using\n    something such as `Sentry`_ to get the best of both worlds -- the\n    rich information of full tracebacks plus the security of *not* sending the\n    information over email. You may also explicitly designate certain\n    sensitive information to be filtered out of error reports -- learn more on\n    :ref:`Filtering error reports<filtering-error-reports>`.\n\n    By setting the ``email_backend`` argument of ``AdminEmailHandler``, the\n    :ref:`email backend <topic-email-backends>` that is being used by the\n    handler can be overridden, like this::\n\n        'handlers': {\n            'mail_admins': {\n                'level': 'ERROR',\n                'class': 'django.utils.log.AdminEmailHandler',\n                'email_backend': 'django.core.mail.backends.filebased.EmailBackend',\n            }\n        },\n\n    By default, an instance of the email backend specified in\n    :setting:`EMAIL_BACKEND` will be used.\n\n    The ``reporter_class`` argument of ``AdminEmailHandler`` allows providing\n    an ``django.views.debug.ExceptionReporter`` subclass to customize the\n    traceback text sent in the email body. You provide a string import path to\n    the class you wish to use, like this::\n\n        'handlers': {\n            'mail_admins': {\n                'level': 'ERROR',\n                'class': 'django.utils.log.AdminEmailHandler',\n                'include_html': True,\n                'reporter_class': 'somepackage.error_reporter.CustomErrorReporter'\n            }\n        },\n\n    .. method:: send_mail(subject, message, *args, **kwargs)\n\n        Sends emails to admin users. To customize this behavior, you can\n        subclass the :class:`~django.utils.log.AdminEmailHandler` class and\n        override this method.\n\n.. _Sentry: https://pypi.org/project/sentry/\n\nFilters\n-------\n\nDjango provides some log filters in addition to those provided by the Python\nlogging module.\n\n.. class:: CallbackFilter(callback)\n\n    This filter accepts a callback function (which should accept a single\n    argument, the record to be logged), and calls it for each record that\n    passes through the filter. Handling of that record will not proceed if the\n    callback returns False.\n\n    For instance, to filter out :exc:`~django.http.UnreadablePostError`\n    (raised when a user cancels an upload) from the admin emails, you would\n    create a filter function::\n\n        from django.http import UnreadablePostError\n\n        def skip_unreadable_post(record):\n            if record.exc_info:\n                exc_type, exc_value = record.exc_info[:2]\n                if isinstance(exc_value, UnreadablePostError):\n                    return False\n            return True\n\n    and then add it to your logging config::\n\n        'filters': {\n            'skip_unreadable_posts': {\n                '()': 'django.utils.log.CallbackFilter',\n                'callback': skip_unreadable_post,\n            }\n        },\n        'handlers': {\n            'mail_admins': {\n                'level': 'ERROR',\n                'filters': ['skip_unreadable_posts'],\n                'class': 'django.utils.log.AdminEmailHandler'\n            }\n        },\n\n.. class:: RequireDebugFalse()\n\n    This filter will only pass on records when settings.DEBUG is False.\n\n    This filter is used as follows in the default :setting:`LOGGING`\n    configuration to ensure that the :class:`AdminEmailHandler` only sends\n    error emails to admins when :setting:`DEBUG` is ``False``::\n\n        'filters': {\n            'require_debug_false': {\n                '()': 'django.utils.log.RequireDebugFalse',\n            }\n        },\n        'handlers': {\n            'mail_admins': {\n                'level': 'ERROR',\n                'filters': ['require_debug_false'],\n                'class': 'django.utils.log.AdminEmailHandler'\n            }\n        },\n\n.. class:: RequireDebugTrue()\n\n    This filter is similar to :class:`RequireDebugFalse`, except that records are\n    passed only when :setting:`DEBUG` is ``True``.\n\n.. _default-logging-configuration:\n\nDjango's default logging configuration\n======================================\n\nBy default, Django configures the following logging:\n\nWhen :setting:`DEBUG` is ``True``:\n\n* The ``django`` logger sends messages in the ``django`` hierarchy (except\n  ``django.server``) at the ``INFO`` level or higher to the console.\n\nWhen :setting:`DEBUG` is ``False``:\n\n* The ``django`` logger sends messages in the ``django`` hierarchy (except\n  ``django.server``)  with ``ERROR`` or ``CRITICAL`` level to\n  :class:`AdminEmailHandler`.\n\nIndependent of the value of :setting:`DEBUG`:\n\n* The :ref:`django-server-logger` logger sends messages at the ``INFO`` level\n  or higher to the console.\n\nAll loggers except :ref:`django-server-logger` propagate logging to their\nparents, up to the root ``django`` logger. The ``console`` and ``mail_admins``\nhandlers are attached to the root logger to provide the behavior described\nabove.\n\nSee also :ref:`Configuring logging <configuring-logging>` to learn how you can\ncomplement or replace this default logging configuration defined in\n:source:`django/utils/log.py`.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":291,"nodeType":"TextFile","repoName":null,"name":"CONTRIBUTING.rst","path":"","text":"======================\nContributing to Django\n======================\n\nAs an open source project, Django welcomes contributions of many forms.\n\nExamples of contributions include:\n\n* Code patches\n* Documentation improvements\n* Bug reports and patch reviews\n\nExtensive contribution guidelines are available in the repository at\n``docs/internals/contributing/``, or online at:\n\nhttps://docs.djangoproject.com/en/dev/internals/contributing/\n\n**Warning: non-trivial pull requests (anything more than fixing a typo) without\nTrac tickets will be closed!** `Please file a ticket`__ to suggest changes.\n\n__ https://code.djangoproject.com/newticket\n\nDjango uses Trac to keep track of bugs, feature requests, and associated\npatches because GitHub doesn't provide adequate tooling for its community.\nPatches can be submitted as pull requests, but if you don't file a ticket,\nit's unlikely that we'll notice your contribution.\n\nCode of Conduct\n===============\n\nAs a contributor, you can help us keep the Django community open and inclusive.\nPlease read and follow our `Code of Conduct <https://www.djangoproject.com/conduct/>`_.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":292,"nodeType":"TextFile","repoName":null,"name":"README.rst","path":"docs","text":"The documentation in this tree is in plain text files and can be viewed using\nany text file viewer.\n\nIt uses `ReST`_ (reStructuredText), and the `Sphinx`_ documentation system.\nThis allows it to be built into other forms for easier viewing and browsing.\n\nTo create an HTML version of the docs:\n\n* Install Sphinx (using ``python -m pip install Sphinx`` or some other method).\n\n* In this docs/ directory, type ``make html`` (or ``make.bat html`` on\n  Windows) at a shell prompt.\n\nThe documentation in ``_build/html/index.html`` can then be viewed in a web\nbrowser.\n\n.. _ReST: https://docutils.sourceforge.io/rst.html\n.. _Sphinx: https://www.sphinx-doc.org/\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":293,"nodeType":"TextFile","repoName":null,"name":"file-uploads.txt","path":"docs/topics/http","text":"============\nFile Uploads\n============\n\n.. currentmodule:: django.core.files.uploadedfile\n\nWhen Django handles a file upload, the file data ends up placed in\n:attr:`request.FILES <django.http.HttpRequest.FILES>` (for more on the\n``request`` object see the documentation for :doc:`request and response objects\n</ref/request-response>`). This document explains how files are stored on disk\nand in memory, and how to customize the default behavior.\n\n.. warning::\n\n    There are security risks if you are accepting uploaded content from\n    untrusted users! See the security guide's topic on\n    :ref:`user-uploaded-content-security` for mitigation details.\n\nBasic file uploads\n==================\n\nConsider a form containing a :class:`~django.forms.FileField`:\n\n.. code-block:: python\n    :caption: forms.py\n\n    from django import forms\n\n    class UploadFileForm(forms.Form):\n        title = forms.CharField(max_length=50)\n        file = forms.FileField()\n\nA view handling this form will receive the file data in\n:attr:`request.FILES <django.http.HttpRequest.FILES>`, which is a dictionary\ncontaining a key for each :class:`~django.forms.FileField` (or\n:class:`~django.forms.ImageField`, or other :class:`~django.forms.FileField`\nsubclass) in the form. So the data from the above form would\nbe accessible as ``request.FILES['file']``.\n\nNote that :attr:`request.FILES <django.http.HttpRequest.FILES>` will only\ncontain data if the request method was ``POST`` and the ``<form>`` that posted\nthe request has the attribute ``enctype=\"multipart/form-data\"``. Otherwise,\n``request.FILES`` will be empty.\n\nMost of the time, you'll pass the file data from ``request`` into the form as\ndescribed in :ref:`binding-uploaded-files`. This would look something like:\n\n.. code-block:: python\n    :caption: views.py\n\n    from django.http import HttpResponseRedirect\n    from django.shortcuts import render\n    from .forms import UploadFileForm\n\n    # Imaginary function to handle an uploaded file.\n    from somewhere import handle_uploaded_file\n\n    def upload_file(request):\n        if request.method == 'POST':\n            form = UploadFileForm(request.POST, request.FILES)\n            if form.is_valid():\n                handle_uploaded_file(request.FILES['file'])\n                return HttpResponseRedirect('/success/url/')\n        else:\n            form = UploadFileForm()\n        return render(request, 'upload.html', {'form': form})\n\nNotice that we have to pass :attr:`request.FILES <django.http.HttpRequest.FILES>`\ninto the form's constructor; this is how file data gets bound into a form.\n\nHere's a common way you might handle an uploaded file::\n\n    def handle_uploaded_file(f):\n        with open('some/file/name.txt', 'wb+') as destination:\n            for chunk in f.chunks():\n                destination.write(chunk)\n\nLooping over ``UploadedFile.chunks()`` instead of using ``read()`` ensures that\nlarge files don't overwhelm your system's memory.\n\nThere are a few other methods and attributes available on ``UploadedFile``\nobjects; see :class:`UploadedFile` for a complete reference.\n\nHandling uploaded files with a model\n------------------------------------\n\nIf you're saving a file on a :class:`~django.db.models.Model` with a\n:class:`~django.db.models.FileField`, using a :class:`~django.forms.ModelForm`\nmakes this process much easier. The file object will be saved to the location\nspecified by the :attr:`~django.db.models.FileField.upload_to` argument of the\ncorresponding :class:`~django.db.models.FileField` when calling\n``form.save()``::\n\n    from django.http import HttpResponseRedirect\n    from django.shortcuts import render\n    from .forms import ModelFormWithFileField\n\n    def upload_file(request):\n        if request.method == 'POST':\n            form = ModelFormWithFileField(request.POST, request.FILES)\n            if form.is_valid():\n                # file is saved\n                form.save()\n                return HttpResponseRedirect('/success/url/')\n        else:\n            form = ModelFormWithFileField()\n        return render(request, 'upload.html', {'form': form})\n\nIf you are constructing an object manually, you can assign the file object from\n:attr:`request.FILES <django.http.HttpRequest.FILES>` to the file field in the\nmodel::\n\n    from django.http import HttpResponseRedirect\n    from django.shortcuts import render\n    from .forms import UploadFileForm\n    from .models import ModelWithFileField\n\n    def upload_file(request):\n        if request.method == 'POST':\n            form = UploadFileForm(request.POST, request.FILES)\n            if form.is_valid():\n                instance = ModelWithFileField(file_field=request.FILES['file'])\n                instance.save()\n                return HttpResponseRedirect('/success/url/')\n        else:\n            form = UploadFileForm()\n        return render(request, 'upload.html', {'form': form})\n\nUploading multiple files\n------------------------\n\nIf you want to upload multiple files using one form field, set the ``multiple``\nHTML attribute of field's widget:\n\n.. code-block:: python\n    :caption: forms.py\n\n    from django import forms\n\n    class FileFieldForm(forms.Form):\n        file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))\n\nThen override the ``post`` method of your\n:class:`~django.views.generic.edit.FormView` subclass to handle multiple file\nuploads:\n\n.. code-block:: python\n    :caption: views.py\n\n    from django.views.generic.edit import FormView\n    from .forms import FileFieldForm\n\n    class FileFieldView(FormView):\n        form_class = FileFieldForm\n        template_name = 'upload.html'  # Replace with your template.\n        success_url = '...'  # Replace with your URL or reverse().\n\n        def post(self, request, *args, **kwargs):\n            form_class = self.get_form_class()\n            form = self.get_form(form_class)\n            files = request.FILES.getlist('file_field')\n            if form.is_valid():\n                for f in files:\n                    ...  # Do something with each file.\n                return self.form_valid(form)\n            else:\n                return self.form_invalid(form)\n\nUpload Handlers\n===============\n\n.. currentmodule:: django.core.files.uploadhandler\n\nWhen a user uploads a file, Django passes off the file data to an *upload\nhandler* -- a small class that handles file data as it gets uploaded. Upload\nhandlers are initially defined in the :setting:`FILE_UPLOAD_HANDLERS` setting,\nwhich defaults to::\n\n    [\"django.core.files.uploadhandler.MemoryFileUploadHandler\",\n     \"django.core.files.uploadhandler.TemporaryFileUploadHandler\"]\n\nTogether :class:`MemoryFileUploadHandler` and\n:class:`TemporaryFileUploadHandler` provide Django's default file upload\nbehavior of reading small files into memory and large ones onto disk.\n\nYou can write custom handlers that customize how Django handles files. You\ncould, for example, use custom handlers to enforce user-level quotas, compress\ndata on the fly, render progress bars, and even send data to another storage\nlocation directly without storing it locally. See :ref:`custom_upload_handlers`\nfor details on how you can customize or completely replace upload behavior.\n\nWhere uploaded data is stored\n-----------------------------\n\nBefore you save uploaded files, the data needs to be stored somewhere.\n\nBy default, if an uploaded file is smaller than 2.5 megabytes, Django will hold\nthe entire contents of the upload in memory. This means that saving the file\ninvolves only a read from memory and a write to disk and thus is very fast.\n\nHowever, if an uploaded file is too large, Django will write the uploaded file\nto a temporary file stored in your system's temporary directory. On a Unix-like\nplatform this means you can expect Django to generate a file called something\nlike ``/tmp/tmpzfp6I6.upload``. If an upload is large enough, you can watch this\nfile grow in size as Django streams the data onto disk.\n\nThese specifics -- 2.5 megabytes; ``/tmp``; etc. -- are \"reasonable defaults\"\nwhich can be customized as described in the next section.\n\nChanging upload handler behavior\n--------------------------------\n\nThere are a few settings which control Django's file upload behavior. See\n:ref:`File Upload Settings <file-upload-settings>` for details.\n\n.. _modifying_upload_handlers_on_the_fly:\n\nModifying upload handlers on the fly\n------------------------------------\n\nSometimes particular views require different upload behavior. In these cases,\nyou can override upload handlers on a per-request basis by modifying\n``request.upload_handlers``. By default, this list will contain the upload\nhandlers given by :setting:`FILE_UPLOAD_HANDLERS`, but you can modify the list\nas you would any other list.\n\nFor instance, suppose you've written a ``ProgressBarUploadHandler`` that\nprovides feedback on upload progress to some sort of AJAX widget. You'd add this\nhandler to your upload handlers like this::\n\n    request.upload_handlers.insert(0, ProgressBarUploadHandler(request))\n\nYou'd probably want to use ``list.insert()`` in this case (instead of\n``append()``) because a progress bar handler would need to run *before* any\nother handlers. Remember, the upload handlers are processed in order.\n\nIf you want to replace the upload handlers completely, you can assign a new\nlist::\n\n   request.upload_handlers = [ProgressBarUploadHandler(request)]\n\n.. note::\n\n    You can only modify upload handlers *before* accessing\n    ``request.POST`` or ``request.FILES`` -- it doesn't make sense to\n    change upload handlers after upload handling has already\n    started. If you try to modify ``request.upload_handlers`` after\n    reading from ``request.POST`` or ``request.FILES`` Django will\n    throw an error.\n\n    Thus, you should always modify uploading handlers as early in your view as\n    possible.\n\n    Also, ``request.POST`` is accessed by\n    :class:`~django.middleware.csrf.CsrfViewMiddleware` which is enabled by\n    default. This means you will need to use\n    :func:`~django.views.decorators.csrf.csrf_exempt` on your view to allow you\n    to change the upload handlers.  You will then need to use\n    :func:`~django.views.decorators.csrf.csrf_protect` on the function that\n    actually processes the request.  Note that this means that the handlers may\n    start receiving the file upload before the CSRF checks have been done.\n    Example code::\n\n        from django.views.decorators.csrf import csrf_exempt, csrf_protect\n\n        @csrf_exempt\n        def upload_file_view(request):\n            request.upload_handlers.insert(0, ProgressBarUploadHandler(request))\n            return _upload_file_view(request)\n\n        @csrf_protect\n        def _upload_file_view(request):\n            ... # Process request\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":294,"nodeType":"TextFile","repoName":null,"name":"transactions.txt","path":"docs/topics/db","text":"=====================\nDatabase transactions\n=====================\n\n.. module:: django.db.transaction\n\nDjango gives you a few ways to control how database transactions are managed.\n\nManaging database transactions\n==============================\n\nDjango's default transaction behavior\n-------------------------------------\n\nDjango's default behavior is to run in autocommit mode. Each query is\nimmediately committed to the database, unless a transaction is active.\n:ref:`See below for details <autocommit-details>`.\n\nDjango uses transactions or savepoints automatically to guarantee the\nintegrity of ORM operations that require multiple queries, especially\n:ref:`delete() <topics-db-queries-delete>` and :ref:`update()\n<topics-db-queries-update>` queries.\n\nDjango's :class:`~django.test.TestCase` class also wraps each test in a\ntransaction for performance reasons.\n\n.. _tying-transactions-to-http-requests:\n\nTying transactions to HTTP requests\n-----------------------------------\n\nA common way to handle transactions on the web is to wrap each request in a\ntransaction. Set :setting:`ATOMIC_REQUESTS <DATABASE-ATOMIC_REQUESTS>` to\n``True`` in the configuration of each database for which you want to enable\nthis behavior.\n\nIt works like this. Before calling a view function, Django starts a\ntransaction. If the response is produced without problems, Django commits the\ntransaction. If the view produces an exception, Django rolls back the\ntransaction.\n\nYou may perform subtransactions using savepoints in your view code, typically\nwith the :func:`atomic` context manager. However, at the end of the view,\neither all or none of the changes will be committed.\n\n.. warning::\n\n    While the simplicity of this transaction model is appealing, it also makes it\n    inefficient when traffic increases. Opening a transaction for every view has\n    some overhead. The impact on performance depends on the query patterns of your\n    application and on how well your database handles locking.\n\n.. admonition:: Per-request transactions and streaming responses\n\n    When a view returns a :class:`~django.http.StreamingHttpResponse`, reading\n    the contents of the response will often execute code to generate the\n    content. Since the view has already returned, such code runs outside of\n    the transaction.\n\n    Generally speaking, it isn't advisable to write to the database while\n    generating a streaming response, since there's no sensible way to handle\n    errors after starting to send the response.\n\nIn practice, this feature wraps every view function in the :func:`atomic`\ndecorator described below.\n\nNote that only the execution of your view is enclosed in the transactions.\nMiddleware runs outside of the transaction, and so does the rendering of\ntemplate responses.\n\nWhen :setting:`ATOMIC_REQUESTS <DATABASE-ATOMIC_REQUESTS>` is enabled, it's\nstill possible to prevent views from running in a transaction.\n\n.. function:: non_atomic_requests(using=None)\n\n    This decorator will negate the effect of :setting:`ATOMIC_REQUESTS\n    <DATABASE-ATOMIC_REQUESTS>` for a given view::\n\n        from django.db import transaction\n\n        @transaction.non_atomic_requests\n        def my_view(request):\n            do_stuff()\n\n        @transaction.non_atomic_requests(using='other')\n        def my_other_view(request):\n            do_stuff_on_the_other_database()\n\n    It only works if it's applied to the view itself.\n\nControlling transactions explicitly\n-----------------------------------\n\nDjango provides a single API to control database transactions.\n\n.. function:: atomic(using=None, savepoint=True)\n\n    Atomicity is the defining property of database transactions. ``atomic``\n    allows us to create a block of code within which the atomicity on the\n    database is guaranteed. If the block of code is successfully completed, the\n    changes are committed to the database. If there is an exception, the\n    changes are rolled back.\n\n    ``atomic`` blocks can be nested. In this case, when an inner block\n    completes successfully, its effects can still be rolled back if an\n    exception is raised in the outer block at a later point.\n\n    ``atomic`` is usable both as a :py:term:`decorator`::\n\n        from django.db import transaction\n\n        @transaction.atomic\n        def viewfunc(request):\n            # This code executes inside a transaction.\n            do_stuff()\n\n    and as a :py:term:`context manager`::\n\n        from django.db import transaction\n\n        def viewfunc(request):\n            # This code executes in autocommit mode (Django's default).\n            do_stuff()\n\n            with transaction.atomic():\n                # This code executes inside a transaction.\n                do_more_stuff()\n\n    Wrapping ``atomic`` in a try/except block allows for natural handling of\n    integrity errors::\n\n        from django.db import IntegrityError, transaction\n\n        @transaction.atomic\n        def viewfunc(request):\n            create_parent()\n\n            try:\n                with transaction.atomic():\n                    generate_relationships()\n            except IntegrityError:\n                handle_exception()\n\n            add_children()\n\n    In this example, even if ``generate_relationships()`` causes a database\n    error by breaking an integrity constraint, you can execute queries in\n    ``add_children()``, and the changes from ``create_parent()`` are still\n    there and bound to the same transaction. Note that any operations attempted\n    in ``generate_relationships()`` will already have been rolled back safely\n    when ``handle_exception()`` is called, so the exception handler can also\n    operate on the database if necessary.\n\n    .. admonition:: Avoid catching exceptions inside ``atomic``!\n\n        When exiting an ``atomic`` block, Django looks at whether it's exited\n        normally or with an exception to determine whether to commit or roll\n        back. If you catch and handle exceptions inside an ``atomic`` block,\n        you may hide from Django the fact that a problem has happened. This\n        can result in unexpected behavior.\n\n        This is mostly a concern for :exc:`~django.db.DatabaseError` and its\n        subclasses such as :exc:`~django.db.IntegrityError`. After such an\n        error, the transaction is broken and Django will perform a rollback at\n        the end of the ``atomic`` block. If you attempt to run database\n        queries before the rollback happens, Django will raise a\n        :class:`~django.db.transaction.TransactionManagementError`. You may\n        also encounter this behavior when an ORM-related signal handler raises\n        an exception.\n\n        The correct way to catch database errors is around an ``atomic`` block\n        as shown above. If necessary, add an extra ``atomic`` block for this\n        purpose. This pattern has another advantage: it delimits explicitly\n        which operations will be rolled back if an exception occurs.\n\n        If you catch exceptions raised by raw SQL queries, Django's behavior\n        is unspecified and database-dependent.\n\n    .. admonition:: You may need to manually revert model state when rolling back a transaction.\n\n        The values of a model's fields won't be reverted when a transaction\n        rollback happens. This could lead to an inconsistent model state unless\n        you manually restore the original field values.\n\n        For example, given ``MyModel`` with an ``active`` field, this snippet\n        ensures that the ``if obj.active`` check at the end uses the correct\n        value if updating ``active`` to ``True`` fails in the transaction::\n\n            from django.db import DatabaseError, transaction\n\n            obj = MyModel(active=False)\n            obj.active = True\n            try:\n                with transaction.atomic():\n                    obj.save()\n            except DatabaseError:\n                obj.active = False\n\n            if obj.active:\n                ...\n\n    In order to guarantee atomicity, ``atomic`` disables some APIs. Attempting\n    to commit, roll back, or change the autocommit state of the database\n    connection within an ``atomic`` block will raise an exception.\n\n    ``atomic`` takes a ``using`` argument which should be the name of a\n    database. If this argument isn't provided, Django uses the ``\"default\"``\n    database.\n\n    Under the hood, Django's transaction management code:\n\n    - opens a transaction when entering the outermost ``atomic`` block;\n    - creates a savepoint when entering an inner ``atomic`` block;\n    - releases or rolls back to the savepoint when exiting an inner block;\n    - commits or rolls back the transaction when exiting the outermost block.\n\n    You can disable the creation of savepoints for inner blocks by setting the\n    ``savepoint`` argument to ``False``. If an exception occurs, Django will\n    perform the rollback when exiting the first parent block with a savepoint\n    if there is one, and the outermost block otherwise. Atomicity is still\n    guaranteed by the outer transaction. This option should only be used if\n    the overhead of savepoints is noticeable. It has the drawback of breaking\n    the error handling described above.\n\n    You may use ``atomic`` when autocommit is turned off. It will only use\n    savepoints, even for the outermost block.\n\n.. admonition:: Performance considerations\n\n    Open transactions have a performance cost for your database server. To\n    minimize this overhead, keep your transactions as short as possible. This\n    is especially important if you're using :func:`atomic` in long-running\n    processes, outside of Django's request / response cycle.\n\nAutocommit\n==========\n\n.. _autocommit-details:\n\nWhy Django uses autocommit\n--------------------------\n\nIn the SQL standards, each SQL query starts a transaction, unless one is\nalready active. Such transactions must then be explicitly committed or rolled\nback.\n\nThis isn't always convenient for application developers. To alleviate this\nproblem, most databases provide an autocommit mode. When autocommit is turned\non and no transaction is active, each SQL query gets wrapped in its own\ntransaction. In other words, not only does each such query start a\ntransaction, but the transaction also gets automatically committed or rolled\nback, depending on whether the query succeeded.\n\n:pep:`249`, the Python Database API Specification v2.0, requires autocommit to\nbe initially turned off. Django overrides this default and turns autocommit\non.\n\nTo avoid this, you can :ref:`deactivate the transaction management\n<deactivate-transaction-management>`, but it isn't recommended.\n\n.. _deactivate-transaction-management:\n\nDeactivating transaction management\n-----------------------------------\n\nYou can totally disable Django's transaction management for a given database\nby setting :setting:`AUTOCOMMIT <DATABASE-AUTOCOMMIT>` to ``False`` in its\nconfiguration. If you do this, Django won't enable autocommit, and won't\nperform any commits. You'll get the regular behavior of the underlying\ndatabase library.\n\nThis requires you to commit explicitly every transaction, even those started\nby Django or by third-party libraries. Thus, this is best used in situations\nwhere you want to run your own transaction-controlling middleware or do\nsomething really strange.\n\nPerforming actions after commit\n===============================\n\nSometimes you need to perform an action related to the current database\ntransaction, but only if the transaction successfully commits. Examples might\ninclude a `Celery`_ task, an email notification, or a cache invalidation.\n\n.. _Celery: http://www.celeryproject.org/\n\nDjango provides the :func:`on_commit` function to register callback functions\nthat should be executed after a transaction is successfully committed:\n\n.. function:: on_commit(func, using=None)\n\nPass any function (that takes no arguments) to :func:`on_commit`::\n\n    from django.db import transaction\n\n    def do_something():\n        pass  # send a mail, invalidate a cache, fire off a Celery task, etc.\n\n    transaction.on_commit(do_something)\n\nYou can also wrap your function in a lambda::\n\n    transaction.on_commit(lambda: some_celery_task.delay('arg1'))\n\nThe function you pass in will be called immediately after a hypothetical\ndatabase write made where ``on_commit()`` is called would be successfully\ncommitted.\n\nIf you call ``on_commit()`` while there isn't an active transaction, the\ncallback will be executed immediately.\n\nIf that hypothetical database write is instead rolled back (typically when an\nunhandled exception is raised in an :func:`atomic` block), your function will\nbe discarded and never called.\n\nSavepoints\n----------\n\nSavepoints (i.e. nested :func:`atomic` blocks) are handled correctly. That is,\nan :func:`on_commit` callable registered after a savepoint (in a nested\n:func:`atomic` block) will be called after the outer transaction is committed,\nbut not if a rollback to that savepoint or any previous savepoint occurred\nduring the transaction::\n\n    with transaction.atomic():  # Outer atomic, start a new transaction\n        transaction.on_commit(foo)\n\n        with transaction.atomic():  # Inner atomic block, create a savepoint\n            transaction.on_commit(bar)\n\n    # foo() and then bar() will be called when leaving the outermost block\n\nOn the other hand, when a savepoint is rolled back (due to an exception being\nraised), the inner callable will not be called::\n\n    with transaction.atomic():  # Outer atomic, start a new transaction\n        transaction.on_commit(foo)\n\n        try:\n            with transaction.atomic():  # Inner atomic block, create a savepoint\n                transaction.on_commit(bar)\n                raise SomeError()  # Raising an exception - abort the savepoint\n        except SomeError:\n            pass\n\n    # foo() will be called, but not bar()\n\nOrder of execution\n------------------\n\nOn-commit functions for a given transaction are executed in the order they were\nregistered.\n\nException handling\n------------------\n\nIf one on-commit function within a given transaction raises an uncaught\nexception, no later registered functions in that same transaction will run.\nThis is the same behavior as if you'd executed the functions sequentially\nyourself without :func:`on_commit`.\n\nTiming of execution\n-------------------\n\nYour callbacks are executed *after* a successful commit, so a failure in a\ncallback will not cause the transaction to roll back. They are executed\nconditionally upon the success of the transaction, but they are not *part* of\nthe transaction. For the intended use cases (mail notifications, Celery tasks,\netc.), this should be fine. If it's not (if your follow-up action is so\ncritical that its failure should mean the failure of the transaction itself),\nthen you don't want to use the :func:`on_commit` hook. Instead, you may want\n`two-phase commit`_ such as the :ref:`psycopg Two-Phase Commit protocol support\n<psycopg2:tpc>` and the :pep:`optional Two-Phase Commit Extensions in the\nPython DB-API specification <249#optional-two-phase-commit-extensions>`.\n\nCallbacks are not run until autocommit is restored on the connection following\nthe commit (because otherwise any queries done in a callback would open an\nimplicit transaction, preventing the connection from going back into autocommit\nmode).\n\nWhen in autocommit mode and outside of an :func:`atomic` block, the function\nwill run immediately, not on commit.\n\nOn-commit functions only work with :ref:`autocommit mode <managing-autocommit>`\nand the :func:`atomic` (or :setting:`ATOMIC_REQUESTS\n<DATABASE-ATOMIC_REQUESTS>`) transaction API. Calling :func:`on_commit` when\nautocommit is disabled and you are not within an atomic block will result in an\nerror.\n\n.. _two-phase commit: https://en.wikipedia.org/wiki/Two-phase_commit_protocol\n\nUse in tests\n------------\n\nDjango's :class:`~django.test.TestCase` class wraps each test in a transaction\nand rolls back that transaction after each test, in order to provide test\nisolation. This means that no transaction is ever actually committed, thus your\n:func:`on_commit` callbacks will never be run. If you need to test the results\nof an :func:`on_commit` callback, use a\n:class:`~django.test.TransactionTestCase` instead.\n\nWhy no rollback hook?\n---------------------\n\nA rollback hook is harder to implement robustly than a commit hook, since a\nvariety of things can cause an implicit rollback.\n\nFor instance, if your database connection is dropped because your process was\nkilled without a chance to shut down gracefully, your rollback hook will never\nrun.\n\nBut there is a solution: instead of doing something during the atomic block\n(transaction) and then undoing it if the transaction fails, use\n:func:`on_commit` to delay doing it in the first place until after the\ntransaction succeeds. It's a lot easier to undo something you never did in the\nfirst place!\n\nLow-level APIs\n==============\n\n.. warning::\n\n    Always prefer :func:`atomic` if possible at all. It accounts for the\n    idiosyncrasies of each database and prevents invalid operations.\n\n    The low level APIs are only useful if you're implementing your own\n    transaction management.\n\n.. _managing-autocommit:\n\nAutocommit\n----------\n\nDjango provides an API in the :mod:`django.db.transaction` module to manage the\nautocommit state of each database connection.\n\n.. function:: get_autocommit(using=None)\n\n.. function:: set_autocommit(autocommit, using=None)\n\nThese functions take a ``using`` argument which should be the name of a\ndatabase. If it isn't provided, Django uses the ``\"default\"`` database.\n\nAutocommit is initially turned on. If you turn it off, it's your\nresponsibility to restore it.\n\nOnce you turn autocommit off, you get the default behavior of your database\nadapter, and Django won't help you. Although that behavior is specified in\n:pep:`249`, implementations of adapters aren't always consistent with one\nanother. Review the documentation of the adapter you're using carefully.\n\nYou must ensure that no transaction is active, usually by issuing a\n:func:`commit` or a :func:`rollback`, before turning autocommit back on.\n\nDjango will refuse to turn autocommit off when an :func:`atomic` block is\nactive, because that would break atomicity.\n\nTransactions\n------------\n\nA transaction is an atomic set of database queries. Even if your program\ncrashes, the database guarantees that either all the changes will be applied,\nor none of them.\n\nDjango doesn't provide an API to start a transaction. The expected way to\nstart a transaction is to disable autocommit with :func:`set_autocommit`.\n\nOnce you're in a transaction, you can choose either to apply the changes\nyou've performed until this point with :func:`commit`, or to cancel them with\n:func:`rollback`. These functions are defined in :mod:`django.db.transaction`.\n\n.. function:: commit(using=None)\n\n.. function:: rollback(using=None)\n\nThese functions take a ``using`` argument which should be the name of a\ndatabase. If it isn't provided, Django uses the ``\"default\"`` database.\n\nDjango will refuse to commit or to rollback when an :func:`atomic` block is\nactive, because that would break atomicity.\n\n.. _topics-db-transactions-savepoints:\n\nSavepoints\n----------\n\nA savepoint is a marker within a transaction that enables you to roll back\npart of a transaction, rather than the full transaction. Savepoints are\navailable with the SQLite, PostgreSQL, Oracle, and MySQL (when using the InnoDB\nstorage engine) backends. Other backends provide the savepoint functions, but\nthey're empty operations -- they don't actually do anything.\n\nSavepoints aren't especially useful if you are using autocommit, the default\nbehavior of Django. However, once you open a transaction with :func:`atomic`,\nyou build up a series of database operations awaiting a commit or rollback. If\nyou issue a rollback, the entire transaction is rolled back. Savepoints\nprovide the ability to perform a fine-grained rollback, rather than the full\nrollback that would be performed by ``transaction.rollback()``.\n\nWhen the :func:`atomic` decorator is nested, it creates a savepoint to allow\npartial commit or rollback. You're strongly encouraged to use :func:`atomic`\nrather than the functions described below, but they're still part of the\npublic API, and there's no plan to deprecate them.\n\nEach of these functions takes a ``using`` argument which should be the name of\na database for which the behavior applies.  If no ``using`` argument is\nprovided then the ``\"default\"`` database is used.\n\nSavepoints are controlled by three functions in :mod:`django.db.transaction`:\n\n.. function:: savepoint(using=None)\n\n    Creates a new savepoint. This marks a point in the transaction that is\n    known to be in a \"good\" state. Returns the savepoint ID (``sid``).\n\n.. function:: savepoint_commit(sid, using=None)\n\n    Releases savepoint ``sid``. The changes performed since the savepoint was\n    created become part of the transaction.\n\n.. function:: savepoint_rollback(sid, using=None)\n\n    Rolls back the transaction to savepoint ``sid``.\n\nThese functions do nothing if savepoints aren't supported or if the database\nis in autocommit mode.\n\nIn addition, there's a utility function:\n\n.. function:: clean_savepoints(using=None)\n\n    Resets the counter used to generate unique savepoint IDs.\n\nThe following example demonstrates the use of savepoints::\n\n    from django.db import transaction\n\n    # open a transaction\n    @transaction.atomic\n    def viewfunc(request):\n\n        a.save()\n        # transaction now contains a.save()\n\n        sid = transaction.savepoint()\n\n        b.save()\n        # transaction now contains a.save() and b.save()\n\n        if want_to_keep_b:\n            transaction.savepoint_commit(sid)\n            # open transaction still contains a.save() and b.save()\n        else:\n            transaction.savepoint_rollback(sid)\n            # open transaction now contains only a.save()\n\nSavepoints may be used to recover from a database error by performing a partial\nrollback. If you're doing this inside an :func:`atomic` block, the entire block\nwill still be rolled back, because it doesn't know you've handled the situation\nat a lower level! To prevent this, you can control the rollback behavior with\nthe following functions.\n\n.. function:: get_rollback(using=None)\n\n.. function:: set_rollback(rollback, using=None)\n\nSetting the rollback flag to ``True`` forces a rollback when exiting the\ninnermost atomic block. This may be useful to trigger a rollback without\nraising an exception.\n\nSetting it to ``False`` prevents such a rollback. Before doing that, make sure\nyou've rolled back the transaction to a known-good savepoint within the current\natomic block! Otherwise you're breaking atomicity and data corruption may\noccur.\n\nDatabase-specific notes\n=======================\n\n.. _savepoints-in-sqlite:\n\nSavepoints in SQLite\n--------------------\n\nWhile SQLite supports savepoints, a flaw in the design of the :mod:`sqlite3`\nmodule makes them hardly usable.\n\nWhen autocommit is enabled, savepoints don't make sense. When it's disabled,\n:mod:`sqlite3` commits implicitly before savepoint statements. (In fact, it\ncommits before any statement other than ``SELECT``, ``INSERT``, ``UPDATE``,\n``DELETE`` and ``REPLACE``.) This bug has two consequences:\n\n- The low level APIs for savepoints are only usable inside a transaction ie.\n  inside an :func:`atomic` block.\n- It's impossible to use :func:`atomic` when autocommit is turned off.\n\nTransactions in MySQL\n---------------------\n\nIf you're using MySQL, your tables may or may not support transactions; it\ndepends on your MySQL version and the table types you're using. (By\n\"table types,\" we mean something like \"InnoDB\" or \"MyISAM\".) MySQL transaction\npeculiarities are outside the scope of this article, but the MySQL site has\n`information on MySQL transactions`_.\n\nIf your MySQL setup does *not* support transactions, then Django will always\nfunction in autocommit mode: statements will be executed and committed as soon\nas they're called. If your MySQL setup *does* support transactions, Django\nwill handle transactions as explained in this document.\n\n.. _information on MySQL transactions: https://dev.mysql.com/doc/refman/en/sql-syntax-transactions.html\n\nHandling exceptions within PostgreSQL transactions\n--------------------------------------------------\n\n.. note::\n\n    This section is relevant only if you're implementing your own transaction\n    management. This problem cannot occur in Django's default mode and\n    :func:`atomic` handles it automatically.\n\nInside a transaction, when a call to a PostgreSQL cursor raises an exception\n(typically ``IntegrityError``), all subsequent SQL in the same transaction\nwill fail with the error \"current transaction is aborted, queries ignored\nuntil end of transaction block\". While the basic use of ``save()`` is unlikely\nto raise an exception in PostgreSQL, there are more advanced usage patterns\nwhich might, such as saving objects with unique fields, saving using the\nforce_insert/force_update flag, or invoking custom SQL.\n\nThere are several ways to recover from this sort of error.\n\nTransaction rollback\n~~~~~~~~~~~~~~~~~~~~\n\nThe first option is to roll back the entire transaction. For example::\n\n    a.save() # Succeeds, but may be undone by transaction rollback\n    try:\n        b.save() # Could throw exception\n    except IntegrityError:\n        transaction.rollback()\n    c.save() # Succeeds, but a.save() may have been undone\n\nCalling ``transaction.rollback()`` rolls back the entire transaction. Any\nuncommitted database operations will be lost. In this example, the changes\nmade by ``a.save()`` would be lost, even though that operation raised no error\nitself.\n\nSavepoint rollback\n~~~~~~~~~~~~~~~~~~\n\nYou can use :ref:`savepoints <topics-db-transactions-savepoints>` to control\nthe extent of a rollback. Before performing a database operation that could\nfail, you can set or update the savepoint; that way, if the operation fails,\nyou can roll back the single offending operation, rather than the entire\ntransaction. For example::\n\n    a.save() # Succeeds, and never undone by savepoint rollback\n    sid = transaction.savepoint()\n    try:\n        b.save() # Could throw exception\n        transaction.savepoint_commit(sid)\n    except IntegrityError:\n        transaction.savepoint_rollback(sid)\n    c.save() # Succeeds, and a.save() is never undone\n\nIn this example, ``a.save()`` will not be undone in the case where\n``b.save()`` raises an exception.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":295,"nodeType":"TextFile","repoName":null,"name":"README.rst","path":"","text":"======\nDjango\n======\n\nDjango is a high-level Python Web framework that encourages rapid development\nand clean, pragmatic design. Thanks for checking it out.\n\nAll documentation is in the \"``docs``\" directory and online at\nhttps://docs.djangoproject.com/en/stable/. If you're just getting started,\nhere's how we recommend you read the docs:\n\n* First, read ``docs/intro/install.txt`` for instructions on installing Django.\n\n* Next, work through the tutorials in order (``docs/intro/tutorial01.txt``,\n  ``docs/intro/tutorial02.txt``, etc.).\n\n* If you want to set up an actual deployment server, read\n  ``docs/howto/deployment/index.txt`` for instructions.\n\n* You'll probably want to read through the topical guides (in ``docs/topics``)\n  next; from there you can jump to the HOWTOs (in ``docs/howto``) for specific\n  problems, and check out the reference (``docs/ref``) for gory details.\n\n* See ``docs/README`` for instructions on building an HTML version of the docs.\n\nDocs are updated rigorously. If you find any problems in the docs, or think\nthey should be clarified in any way, please take 30 seconds to fill out a\nticket here: https://code.djangoproject.com/newticket\n\nTo get more help:\n\n* Join the ``#django`` channel on irc.freenode.net. Lots of helpful people hang\n  out there. See https://freenode.net/kb/answer/chat if you're new to IRC.\n\n* Join the django-users mailing list, or read the archives, at\n  https://groups.google.com/group/django-users.\n\nTo contribute to Django:\n\n* Check out https://docs.djangoproject.com/en/dev/internals/contributing/ for\n  information about getting involved.\n\nTo run Django's test suite:\n\n* Follow the instructions in the \"Unit tests\" section of\n  ``docs/internals/contributing/writing-code/unit-tests.txt``, published online at\n  https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/unit-tests/#running-the-unit-tests\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":296,"nodeType":"Package","repoName":null,"name":"docs/topics/testing","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":297,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/topics/testing","text":"=================\nTesting in Django\n=================\n\nAutomated testing is an extremely useful bug-killing tool for the modern\nWeb developer. You can use a collection of tests -- a **test suite** -- to\nsolve, or avoid, a number of problems:\n\n* When you're writing new code, you can use tests to validate your code\n  works as expected.\n\n* When you're refactoring or modifying old code, you can use tests to\n  ensure your changes haven't affected your application's behavior\n  unexpectedly.\n\nTesting a Web application is a complex task, because a Web application is made\nof several layers of logic -- from HTTP-level request handling, to form\nvalidation and processing, to template rendering. With Django's test-execution\nframework and assorted utilities, you can simulate requests, insert test data,\ninspect your application's output and generally verify your code is doing what\nit should be doing.\n\nThe preferred way to write tests in Django is using the :mod:`unittest` module\nbuilt-in to the Python standard library. This is covered in detail in the\n:doc:`overview` document.\n\nYou can also use any *other* Python test framework; Django provides an API and\ntools for that kind of integration. They are described in the\n:ref:`other-testing-frameworks` section of :doc:`advanced`.\n\n.. toctree::\n   :maxdepth: 1\n\n   overview\n   tools\n   advanced\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":298,"nodeType":"TextFile","repoName":null,"name":"multi-db.txt","path":"docs/topics/db","text":"==================\nMultiple databases\n==================\n\nThis topic guide describes Django's support for interacting with\nmultiple databases. Most of the rest of Django's documentation assumes\nyou are interacting with a single database. If you want to interact\nwith multiple databases, you'll need to take some additional steps.\n\n.. seealso::\n\n    See :ref:`testing-multi-db` for information about testing with multiple\n    databases.\n\nDefining your databases\n=======================\n\nThe first step to using more than one database with Django is to tell\nDjango about the database servers you'll be using. This is done using\nthe :setting:`DATABASES` setting. This setting maps database aliases,\nwhich are a way to refer to a specific database throughout Django, to\na dictionary of settings for that specific connection. The settings in\nthe inner dictionaries are described fully in the :setting:`DATABASES`\ndocumentation.\n\nDatabases can have any alias you choose. However, the alias\n``default`` has special significance. Django uses the database with\nthe alias of ``default`` when no other database has been selected.\n\nThe following is an example ``settings.py`` snippet defining two\ndatabases -- a default PostgreSQL database and a MySQL database called\n``users``::\n\n    DATABASES = {\n        'default': {\n            'NAME': 'app_data',\n            'ENGINE': 'django.db.backends.postgresql',\n            'USER': 'postgres_user',\n            'PASSWORD': 's3krit'\n        },\n        'users': {\n            'NAME': 'user_data',\n            'ENGINE': 'django.db.backends.mysql',\n            'USER': 'mysql_user',\n            'PASSWORD': 'priv4te'\n        }\n    }\n\nIf the concept of a ``default`` database doesn't make sense in the context\nof your project, you need to be careful to always specify the database\nthat you want to use. Django requires that a ``default`` database entry\nbe defined, but the parameters dictionary can be left blank if it will not be\nused. To do this, you must set up :setting:`DATABASE_ROUTERS` for all of your\napps' models, including those in any contrib and third-party apps you're using,\nso that no queries are routed to the default database. The following is an\nexample ``settings.py`` snippet defining two non-default databases, with the\n``default`` entry intentionally left empty::\n\n    DATABASES = {\n        'default': {},\n        'users': {\n            'NAME': 'user_data',\n            'ENGINE': 'django.db.backends.mysql',\n            'USER': 'mysql_user',\n            'PASSWORD': 'superS3cret'\n        },\n        'customers': {\n            'NAME': 'customer_data',\n            'ENGINE': 'django.db.backends.mysql',\n            'USER': 'mysql_cust',\n            'PASSWORD': 'veryPriv@ate'\n        }\n    }\n\nIf you attempt to access a database that you haven't defined in your\n:setting:`DATABASES` setting, Django will raise a\n``django.db.utils.ConnectionDoesNotExist`` exception.\n\nSynchronizing your databases\n============================\n\nThe :djadmin:`migrate` management command operates on one database at a\ntime. By default, it operates on the ``default`` database, but by\nproviding the :option:`--database <migrate --database>` option, you can tell it\nto synchronize a different database. So, to synchronize all models onto\nall databases in the first example above, you would need to call::\n\n    $ ./manage.py migrate\n    $ ./manage.py migrate --database=users\n\nIf you don't want every application to be synchronized onto a\nparticular database, you can define a :ref:`database\nrouter<topics-db-multi-db-routing>` that implements a policy\nconstraining the availability of particular models.\n\nIf, as in the second example above, you've left the ``default`` database empty,\nyou must provide a database name each time you run :djadmin:`migrate`. Omitting\nthe database name would raise an error. For the second example::\n\n    $ ./manage.py migrate --database=users\n    $ ./manage.py migrate --database=customers\n\nUsing other management commands\n-------------------------------\n\nMost other ``django-admin`` commands that interact with the database operate in\nthe same way as :djadmin:`migrate` -- they only ever operate on one database at\na time, using ``--database`` to control the database used.\n\nAn exception to this rule is the :djadmin:`makemigrations` command. It\nvalidates the migration history in the databases to catch problems with the\nexisting migration files (which could be caused by editing them) before\ncreating new migrations. By default, it checks only the ``default`` database,\nbut it consults the :meth:`allow_migrate` method of :ref:`routers\n<topics-db-multi-db-routing>` if any are installed.\n\n.. _topics-db-multi-db-routing:\n\nAutomatic database routing\n==========================\n\nThe easiest way to use multiple databases is to set up a database\nrouting scheme. The default routing scheme ensures that objects remain\n'sticky' to their original database (i.e., an object retrieved from\nthe ``foo`` database will be saved on the same database). The default\nrouting scheme ensures that if a database isn't specified, all queries\nfall back to the ``default`` database.\n\nYou don't have to do anything to activate the default routing scheme\n-- it is provided 'out of the box' on every Django project. However,\nif you want to implement more interesting database allocation\nbehaviors, you can define and install your own database routers.\n\nDatabase routers\n----------------\n\nA database Router is a class that provides up to four methods:\n\n.. method:: db_for_read(model, **hints)\n\n    Suggest the database that should be used for read operations for\n    objects of type ``model``.\n\n    If a database operation is able to provide any additional\n    information that might assist in selecting a database, it will be\n    provided in the ``hints`` dictionary. Details on valid hints are\n    provided :ref:`below <topics-db-multi-db-hints>`.\n\n    Returns ``None`` if there is no suggestion.\n\n.. method:: db_for_write(model, **hints)\n\n    Suggest the database that should be used for writes of objects of\n    type Model.\n\n    If a database operation is able to provide any additional\n    information that might assist in selecting a database, it will be\n    provided in the ``hints`` dictionary. Details on valid hints are\n    provided :ref:`below <topics-db-multi-db-hints>`.\n\n    Returns ``None`` if there is no suggestion.\n\n.. method:: allow_relation(obj1, obj2, **hints)\n\n    Return ``True`` if a relation between ``obj1`` and ``obj2`` should be\n    allowed, ``False`` if the relation should be prevented, or ``None`` if\n    the router has no opinion. This is purely a validation operation,\n    used by foreign key and many to many operations to determine if a\n    relation should be allowed between two objects.\n\n    If no router has an opinion (i.e. all routers return ``None``), only\n    relations within the same database are allowed.\n\n.. method:: allow_migrate(db, app_label, model_name=None, **hints)\n\n    Determine if the migration operation is allowed to run on the database with\n    alias ``db``. Return ``True`` if the operation should run, ``False`` if it\n    shouldn't run, or ``None`` if the router has no opinion.\n\n    The ``app_label`` positional argument is the label of the application\n    being migrated.\n\n    ``model_name`` is set by most migration operations to the value of\n    ``model._meta.model_name`` (the lowercased version of the model\n    ``__name__``) of the model being migrated. Its value is ``None`` for the\n    :class:`~django.db.migrations.operations.RunPython` and\n    :class:`~django.db.migrations.operations.RunSQL` operations unless they\n    provide it using hints.\n\n    ``hints`` are used by certain operations to communicate additional\n    information to the router.\n\n    When ``model_name`` is set, ``hints`` normally contains the model class\n    under the key ``'model'``. Note that it may be a :ref:`historical model\n    <historical-models>`, and thus not have any custom attributes, methods, or\n    managers. You should only rely on ``_meta``.\n\n    This method can also be used to determine the availability of a model on a\n    given database.\n\n    :djadmin:`makemigrations` always creates migrations for model changes, but\n    if ``allow_migrate()`` returns ``False``, any migration operations for the\n    ``model_name`` will be silently skipped when running :djadmin:`migrate` on\n    the ``db``. Changing the behavior of ``allow_migrate()`` for models that\n    already have migrations may result in broken foreign keys, extra tables,\n    or missing tables. When :djadmin:`makemigrations` verifies the migration\n    history, it skips databases where no app is allowed to migrate.\n\nA router doesn't have to provide *all* these methods -- it may omit one\nor more of them. If one of the methods is omitted, Django will skip\nthat router when performing the relevant check.\n\n.. _topics-db-multi-db-hints:\n\nHints\n~~~~~\n\nThe hints received by the database router can be used to decide which\ndatabase should receive a given request.\n\nAt present, the only hint that will be provided is ``instance``, an\nobject instance that is related to the read or write operation that is\nunderway. This might be the instance that is being saved, or it might\nbe an instance that is being added in a many-to-many relation. In some\ncases, no instance hint will be provided at all. The router checks for\nthe existence of an instance hint, and determine if that hint should be\nused to alter routing behavior.\n\nUsing routers\n-------------\n\nDatabase routers are installed using the :setting:`DATABASE_ROUTERS`\nsetting. This setting defines a list of class names, each specifying a\nrouter that should be used by the master router\n(``django.db.router``).\n\nThe master router is used by Django's database operations to allocate\ndatabase usage. Whenever a query needs to know which database to use,\nit calls the master router, providing a model and a hint (if\navailable). Django then tries each router in turn until a database\nsuggestion can be found. If no suggestion can be found, it tries the\ncurrent ``_state.db`` of the hint instance. If a hint instance wasn't\nprovided, or the instance doesn't currently have database state, the\nmaster router will allocate the ``default`` database.\n\nAn example\n----------\n\n.. admonition:: Example purposes only!\n\n    This example is intended as a demonstration of how the router\n    infrastructure can be used to alter database usage. It\n    intentionally ignores some complex issues in order to\n    demonstrate how routers are used.\n\n    This example won't work if any of the models in ``myapp`` contain\n    relationships to models outside of the ``other`` database.\n    :ref:`Cross-database relationships <no_cross_database_relations>`\n    introduce referential integrity problems that Django can't\n    currently handle.\n\n    The primary/replica (referred to as master/slave by some databases)\n    configuration described is also flawed -- it\n    doesn't provide any solution for handling replication lag (i.e.,\n    query inconsistencies introduced because of the time taken for a\n    write to propagate to the replicas). It also doesn't consider the\n    interaction of transactions with the database utilization strategy.\n\nSo - what does this mean in practice? Let's consider another sample\nconfiguration. This one will have several databases: one for the\n``auth`` application, and all other apps using a primary/replica setup\nwith two read replicas. Here are the settings specifying these\ndatabases::\n\n    DATABASES = {\n        'default': {},\n        'auth_db': {\n            'NAME': 'auth_db',\n            'ENGINE': 'django.db.backends.mysql',\n            'USER': 'mysql_user',\n            'PASSWORD': 'swordfish',\n        },\n        'primary': {\n            'NAME': 'primary',\n            'ENGINE': 'django.db.backends.mysql',\n            'USER': 'mysql_user',\n            'PASSWORD': 'spam',\n        },\n        'replica1': {\n            'NAME': 'replica1',\n            'ENGINE': 'django.db.backends.mysql',\n            'USER': 'mysql_user',\n            'PASSWORD': 'eggs',\n        },\n        'replica2': {\n            'NAME': 'replica2',\n            'ENGINE': 'django.db.backends.mysql',\n            'USER': 'mysql_user',\n            'PASSWORD': 'bacon',\n        },\n    }\n\nNow we'll need to handle routing. First we want a router that knows to\nsend queries for the ``auth`` and ``contenttypes`` apps to ``auth_db``\n(``auth`` models are linked to ``ContentType``, so they must be stored in the\nsame database)::\n\n    class AuthRouter:\n        \"\"\"\n        A router to control all database operations on models in the\n        auth and contenttypes applications.\n        \"\"\"\n        route_app_labels = {'auth', 'contenttypes'}\n\n        def db_for_read(self, model, **hints):\n            \"\"\"\n            Attempts to read auth and contenttypes models go to auth_db.\n            \"\"\"\n            if model._meta.app_label in self.route_app_labels:\n                return 'auth_db'\n            return None\n\n        def db_for_write(self, model, **hints):\n            \"\"\"\n            Attempts to write auth and contenttypes models go to auth_db.\n            \"\"\"\n            if model._meta.app_label in self.route_app_labels:\n                return 'auth_db'\n            return None\n\n        def allow_relation(self, obj1, obj2, **hints):\n            \"\"\"\n            Allow relations if a model in the auth or contenttypes apps is\n            involved.\n            \"\"\"\n            if (\n                obj1._meta.app_label in self.route_app_labels or\n                obj2._meta.app_label in self.route_app_labels\n            ):\n               return True\n            return None\n\n        def allow_migrate(self, db, app_label, model_name=None, **hints):\n            \"\"\"\n            Make sure the auth and contenttypes apps only appear in the\n            'auth_db' database.\n            \"\"\"\n            if app_label in self.route_app_labels:\n                return db == 'auth_db'\n            return None\n\nAnd we also want a router that sends all other apps to the\nprimary/replica configuration, and randomly chooses a replica to read\nfrom::\n\n    import random\n\n    class PrimaryReplicaRouter:\n        def db_for_read(self, model, **hints):\n            \"\"\"\n            Reads go to a randomly-chosen replica.\n            \"\"\"\n            return random.choice(['replica1', 'replica2'])\n\n        def db_for_write(self, model, **hints):\n            \"\"\"\n            Writes always go to primary.\n            \"\"\"\n            return 'primary'\n\n        def allow_relation(self, obj1, obj2, **hints):\n            \"\"\"\n            Relations between objects are allowed if both objects are\n            in the primary/replica pool.\n            \"\"\"\n            db_list = ('primary', 'replica1', 'replica2')\n            if obj1._state.db in db_list and obj2._state.db in db_list:\n                return True\n            return None\n\n        def allow_migrate(self, db, app_label, model_name=None, **hints):\n            \"\"\"\n            All non-auth models end up in this pool.\n            \"\"\"\n            return True\n\nFinally, in the settings file, we add the following (substituting\n``path.to.`` with the actual Python path to the module(s) where the\nrouters are defined)::\n\n    DATABASE_ROUTERS = ['path.to.AuthRouter', 'path.to.PrimaryReplicaRouter']\n\nThe order in which routers are processed is significant. Routers will\nbe queried in the order they are listed in the\n:setting:`DATABASE_ROUTERS` setting. In this example, the\n``AuthRouter`` is processed before the ``PrimaryReplicaRouter``, and as a\nresult, decisions concerning the models in ``auth`` are processed\nbefore any other decision is made. If the :setting:`DATABASE_ROUTERS`\nsetting listed the two routers in the other order,\n``PrimaryReplicaRouter.allow_migrate()`` would be processed first. The\ncatch-all nature of the PrimaryReplicaRouter implementation would mean\nthat all models would be available on all databases.\n\nWith this setup installed, lets run some Django code::\n\n    >>> # This retrieval will be performed on the 'auth_db' database\n    >>> fred = User.objects.get(username='fred')\n    >>> fred.first_name = 'Frederick'\n\n    >>> # This save will also be directed to 'auth_db'\n    >>> fred.save()\n\n    >>> # These retrieval will be randomly allocated to a replica database\n    >>> dna = Person.objects.get(name='Douglas Adams')\n\n    >>> # A new object has no database allocation when created\n    >>> mh = Book(title='Mostly Harmless')\n\n    >>> # This assignment will consult the router, and set mh onto\n    >>> # the same database as the author object\n    >>> mh.author = dna\n\n    >>> # This save will force the 'mh' instance onto the primary database...\n    >>> mh.save()\n\n    >>> # ... but if we re-retrieve the object, it will come back on a replica\n    >>> mh = Book.objects.get(title='Mostly Harmless')\n\nThis example defined a router to handle interaction with models from the\n``auth`` app, and other routers to handle interaction with all other apps. If\nyou left your ``default`` database empty and don't want to define a catch-all\ndatabase router to handle all apps not otherwise specified, your routers must\nhandle the names of all apps in :setting:`INSTALLED_APPS` before you migrate.\nSee :ref:`contrib_app_multiple_databases` for information about contrib apps\nthat must be together in one database.\n\nManually selecting a database\n=============================\n\nDjango also provides an API that allows you to maintain complete control\nover database usage in your code. A manually specified database allocation\nwill take priority over a database allocated by a router.\n\nManually selecting a database for a ``QuerySet``\n------------------------------------------------\n\nYou can select the database for a ``QuerySet`` at any point in the\n``QuerySet`` \"chain.\" Call ``using()`` on the ``QuerySet`` to get another\n``QuerySet`` that uses the specified database.\n\n``using()`` takes a single argument: the alias of the database on\nwhich you want to run the query. For example::\n\n    >>> # This will run on the 'default' database.\n    >>> Author.objects.all()\n\n    >>> # So will this.\n    >>> Author.objects.using('default').all()\n\n    >>> # This will run on the 'other' database.\n    >>> Author.objects.using('other').all()\n\nSelecting a database for ``save()``\n-----------------------------------\n\nUse the ``using`` keyword to ``Model.save()`` to specify to which\ndatabase the data should be saved.\n\nFor example, to save an object to the ``legacy_users`` database, you'd\nuse this::\n\n    >>> my_object.save(using='legacy_users')\n\nIf you don't specify ``using``, the ``save()`` method will save into\nthe default database allocated by the routers.\n\nMoving an object from one database to another\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf you've saved an instance to one database, it might be tempting to\nuse ``save(using=...)`` as a way to migrate the instance to a new\ndatabase. However, if you don't take appropriate steps, this could\nhave some unexpected consequences.\n\nConsider the following example::\n\n    >>> p = Person(name='Fred')\n    >>> p.save(using='first')  # (statement 1)\n    >>> p.save(using='second') # (statement 2)\n\nIn statement 1, a new ``Person`` object is saved to the ``first``\ndatabase. At this time, ``p`` doesn't have a primary key, so Django\nissues an SQL ``INSERT`` statement. This creates a primary key, and\nDjango assigns that primary key to ``p``.\n\nWhen the save occurs in statement 2, ``p`` already has a primary key\nvalue, and Django will attempt to use that primary key on the new\ndatabase. If the primary key value isn't in use in the ``second``\ndatabase, then you won't have any problems -- the object will be\ncopied to the new database.\n\nHowever, if the primary key of ``p`` is already in use on the\n``second`` database, the existing object in the ``second`` database\nwill be overridden when ``p`` is saved.\n\nYou can avoid this in two ways. First, you can clear the primary key\nof the instance. If an object has no primary key, Django will treat it\nas a new object, avoiding any loss of data on the ``second``\ndatabase::\n\n    >>> p = Person(name='Fred')\n    >>> p.save(using='first')\n    >>> p.pk = None # Clear the primary key.\n    >>> p.save(using='second') # Write a completely new object.\n\nThe second option is to use the ``force_insert`` option to ``save()``\nto ensure that Django does an SQL ``INSERT``::\n\n    >>> p = Person(name='Fred')\n    >>> p.save(using='first')\n    >>> p.save(using='second', force_insert=True)\n\nThis will ensure that the person named ``Fred`` will have the same\nprimary key on both databases. If that primary key is already in use\nwhen you try to save onto the ``second`` database, an error will be\nraised.\n\nSelecting a database to delete from\n-----------------------------------\n\nBy default, a call to delete an existing object will be executed on\nthe same database that was used to retrieve the object in the first\nplace::\n\n    >>> u = User.objects.using('legacy_users').get(username='fred')\n    >>> u.delete() # will delete from the `legacy_users` database\n\nTo specify the database from which a model will be deleted, pass a\n``using`` keyword argument to the ``Model.delete()`` method. This\nargument works just like the ``using`` keyword argument to ``save()``.\n\nFor example, if you're migrating a user from the ``legacy_users``\ndatabase to the ``new_users`` database, you might use these commands::\n\n    >>> user_obj.save(using='new_users')\n    >>> user_obj.delete(using='legacy_users')\n\nUsing managers with multiple databases\n--------------------------------------\n\nUse the ``db_manager()`` method on managers to give managers access to\na non-default database.\n\nFor example, say you have a custom manager method that touches the\ndatabase -- ``User.objects.create_user()``. Because ``create_user()``\nis a manager method, not a ``QuerySet`` method, you can't do\n``User.objects.using('new_users').create_user()``. (The\n``create_user()`` method is only available on ``User.objects``, the\nmanager, not on ``QuerySet`` objects derived from the manager.) The\nsolution is to use ``db_manager()``, like this::\n\n    User.objects.db_manager('new_users').create_user(...)\n\n``db_manager()`` returns a copy of the manager bound to the database you specify.\n\nUsing ``get_queryset()`` with multiple databases\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf you're overriding ``get_queryset()`` on your manager, be sure to\neither call the method on the parent (using ``super()``) or do the\nappropriate handling of the ``_db`` attribute on the manager (a string\ncontaining the name of the database to use).\n\nFor example, if you want to return a custom ``QuerySet`` class from\nthe ``get_queryset`` method, you could do this::\n\n    class MyManager(models.Manager):\n        def get_queryset(self):\n            qs = CustomQuerySet(self.model)\n            if self._db is not None:\n                qs = qs.using(self._db)\n            return qs\n\nExposing multiple databases in Django's admin interface\n=======================================================\n\nDjango's admin doesn't have any explicit support for multiple\ndatabases. If you want to provide an admin interface for a model on a\ndatabase other than that specified by your router chain, you'll\nneed to write custom :class:`~django.contrib.admin.ModelAdmin` classes\nthat will direct the admin to use a specific database for content.\n\n``ModelAdmin`` objects have five methods that require customization for\nmultiple-database support::\n\n    class MultiDBModelAdmin(admin.ModelAdmin):\n        # A handy constant for the name of the alternate database.\n        using = 'other'\n\n        def save_model(self, request, obj, form, change):\n            # Tell Django to save objects to the 'other' database.\n            obj.save(using=self.using)\n\n        def delete_model(self, request, obj):\n            # Tell Django to delete objects from the 'other' database\n            obj.delete(using=self.using)\n\n        def get_queryset(self, request):\n            # Tell Django to look for objects on the 'other' database.\n            return super().get_queryset(request).using(self.using)\n\n        def formfield_for_foreignkey(self, db_field, request, **kwargs):\n            # Tell Django to populate ForeignKey widgets using a query\n            # on the 'other' database.\n            return super().formfield_for_foreignkey(db_field, request, using=self.using, **kwargs)\n\n        def formfield_for_manytomany(self, db_field, request, **kwargs):\n            # Tell Django to populate ManyToMany widgets using a query\n            # on the 'other' database.\n            return super().formfield_for_manytomany(db_field, request, using=self.using, **kwargs)\n\nThe implementation provided here implements a multi-database strategy\nwhere all objects of a given type are stored on a specific database\n(e.g., all ``User`` objects are in the ``other`` database). If your\nusage of multiple databases is more complex, your ``ModelAdmin`` will\nneed to reflect that strategy.\n\n:class:`~django.contrib.admin.InlineModelAdmin` objects can be handled in a\nsimilar fashion. They require three customized methods::\n\n    class MultiDBTabularInline(admin.TabularInline):\n        using = 'other'\n\n        def get_queryset(self, request):\n            # Tell Django to look for inline objects on the 'other' database.\n            return super().get_queryset(request).using(self.using)\n\n        def formfield_for_foreignkey(self, db_field, request, **kwargs):\n            # Tell Django to populate ForeignKey widgets using a query\n            # on the 'other' database.\n            return super().formfield_for_foreignkey(db_field, request, using=self.using, **kwargs)\n\n        def formfield_for_manytomany(self, db_field, request, **kwargs):\n            # Tell Django to populate ManyToMany widgets using a query\n            # on the 'other' database.\n            return super().formfield_for_manytomany(db_field, request, using=self.using, **kwargs)\n\nOnce you've written your model admin definitions, they can be\nregistered with any ``Admin`` instance::\n\n    from django.contrib import admin\n\n    # Specialize the multi-db admin objects for use with specific models.\n    class BookInline(MultiDBTabularInline):\n        model = Book\n\n    class PublisherAdmin(MultiDBModelAdmin):\n        inlines = [BookInline]\n\n    admin.site.register(Author, MultiDBModelAdmin)\n    admin.site.register(Publisher, PublisherAdmin)\n\n    othersite = admin.AdminSite('othersite')\n    othersite.register(Publisher, MultiDBModelAdmin)\n\nThis example sets up two admin sites. On the first site, the\n``Author`` and ``Publisher`` objects are exposed; ``Publisher``\nobjects have a tabular inline showing books published by that\npublisher. The second site exposes just publishers, without the\ninlines.\n\nUsing raw cursors with multiple databases\n=========================================\n\nIf you are using more than one database you can use\n``django.db.connections`` to obtain the connection (and cursor) for a\nspecific database. ``django.db.connections`` is a dictionary-like\nobject that allows you to retrieve a specific connection using its\nalias::\n\n    from django.db import connections\n    with connections['my_db_alias'].cursor() as cursor:\n        ...\n\nLimitations of multiple databases\n=================================\n\n.. _no_cross_database_relations:\n\nCross-database relations\n------------------------\n\nDjango doesn't currently provide any support for foreign key or\nmany-to-many relationships spanning multiple databases. If you\nhave used a router to partition models to different databases,\nany foreign key and many-to-many relationships defined by those\nmodels must be internal to a single database.\n\nThis is because of referential integrity. In order to maintain a\nrelationship between two objects, Django needs to know that the\nprimary key of the related object is valid. If the primary key is\nstored on a separate database, it's not possible to easily evaluate\nthe validity of a primary key.\n\nIf you're using Postgres, Oracle, or MySQL with InnoDB, this is\nenforced at the database integrity level -- database level key\nconstraints prevent the creation of relations that can't be validated.\n\nHowever, if you're using SQLite or MySQL with MyISAM tables, there is\nno enforced referential integrity; as a result, you may be able to\n'fake' cross database foreign keys. However, this configuration is not\nofficially supported by Django.\n\n.. _contrib_app_multiple_databases:\n\nBehavior of contrib apps\n------------------------\n\nSeveral contrib apps include models, and some apps depend on others. Since\ncross-database relationships are impossible, this creates some restrictions on\nhow you can split these models across databases:\n\n- each one of ``contenttypes.ContentType``, ``sessions.Session`` and\n  ``sites.Site`` can be stored in any database, given a suitable router.\n- ``auth`` models — ``User``, ``Group`` and ``Permission`` — are linked\n  together and linked to ``ContentType``, so they must be stored in the same\n  database as ``ContentType``.\n- ``admin`` depends on ``auth``, so its models must be in the same database\n  as ``auth``.\n- ``flatpages`` and ``redirects`` depend on ``sites``, so their models must be\n  in the same database as ``sites``.\n\nIn addition, some objects are automatically created just after\n:djadmin:`migrate` creates a table to hold them in a database:\n\n- a default ``Site``,\n- a ``ContentType`` for each model (including those not stored in that\n  database),\n- the ``Permission``\\s for each model (including those not stored in that\n  database).\n\nFor common setups with multiple databases, it isn't useful to have these\nobjects in more than one database. Common setups include primary/replica and\nconnecting to external databases. Therefore, it's recommended to write a\n:ref:`database router<topics-db-multi-db-routing>` that allows synchronizing\nthese three models to only one database. Use the same approach for contrib\nand third-party apps that don't need their tables in multiple databases.\n\n.. warning::\n\n    If you're synchronizing content types to more than one database, be aware\n    that their primary keys may not match across databases. This may result in\n    data corruption or data loss.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":299,"nodeType":"TextFile","repoName":null,"name":"middleware.txt","path":"docs/topics/http","text":"==========\nMiddleware\n==========\n\nMiddleware is a framework of hooks into Django's request/response processing.\nIt's a light, low-level \"plugin\" system for globally altering Django's input\nor output.\n\nEach middleware component is responsible for doing some specific function. For\nexample, Django includes a middleware component,\n:class:`~django.contrib.auth.middleware.AuthenticationMiddleware`, that\nassociates users with requests using sessions.\n\nThis document explains how middleware works, how you activate middleware, and\nhow to write your own middleware. Django ships with some built-in middleware\nyou can use right out of the box. They're documented in the :doc:`built-in\nmiddleware reference </ref/middleware>`.\n\nWriting your own middleware\n===========================\n\nA middleware factory is a callable that takes a ``get_response`` callable and\nreturns a middleware. A middleware is a callable that takes a request and\nreturns a response, just like a view.\n\nA middleware can be written as a function that looks like this::\n\n    def simple_middleware(get_response):\n        # One-time configuration and initialization.\n\n        def middleware(request):\n            # Code to be executed for each request before\n            # the view (and later middleware) are called.\n\n            response = get_response(request)\n\n            # Code to be executed for each request/response after\n            # the view is called.\n\n            return response\n\n        return middleware\n\nOr it can be written as a class whose instances are callable, like this::\n\n    class SimpleMiddleware:\n        def __init__(self, get_response):\n            self.get_response = get_response\n            # One-time configuration and initialization.\n\n        def __call__(self, request):\n            # Code to be executed for each request before\n            # the view (and later middleware) are called.\n\n            response = self.get_response(request)\n\n            # Code to be executed for each request/response after\n            # the view is called.\n\n            return response\n\nThe ``get_response`` callable provided by Django might be the actual view (if\nthis is the last listed middleware) or it might be the next middleware in the\nchain. The current middleware doesn't need to know or care what exactly it is,\njust that it represents whatever comes next.\n\nThe above is a slight simplification -- the ``get_response`` callable for the\nlast middleware in the chain won't be the actual view but rather a wrapper\nmethod from the handler which takes care of applying :ref:`view middleware\n<view-middleware>`, calling the view with appropriate URL arguments, and\napplying :ref:`template-response <template-response-middleware>` and\n:ref:`exception <exception-middleware>` middleware.\n\nMiddleware can either support only synchronous Python (the default), only\nasynchronous Python, or both. See :ref:`async-middleware` for details of how to\nadvertise what you support, and know what kind of request you are getting.\n\nMiddleware can live anywhere on your Python path.\n\n``__init__(get_response)``\n--------------------------\n\nMiddleware factories must accept a ``get_response`` argument. You can also\ninitialize some global state for the middleware. Keep in mind a couple of\ncaveats:\n\n* Django initializes your middleware with only the ``get_response`` argument,\n  so you can't define ``__init__()`` as requiring any other arguments.\n\n* Unlike the ``__call__()`` method which is called once per request,\n  ``__init__()`` is called only *once*, when the Web server starts.\n\nMarking middleware as unused\n----------------------------\n\nIt's sometimes useful to determine at startup time whether a piece of\nmiddleware should be used. In these cases, your middleware's ``__init__()``\nmethod may raise :exc:`~django.core.exceptions.MiddlewareNotUsed`. Django will\nthen remove that middleware from the middleware process and log a debug message\nto the :ref:`django-request-logger` logger when :setting:`DEBUG` is ``True``.\n\nActivating middleware\n=====================\n\nTo activate a middleware component, add it to the :setting:`MIDDLEWARE` list in\nyour Django settings.\n\nIn :setting:`MIDDLEWARE`, each middleware component is represented by a string:\nthe full Python path to the middleware factory's class or function name. For\nexample, here's the default value created by :djadmin:`django-admin\nstartproject <startproject>`::\n\n    MIDDLEWARE = [\n        'django.middleware.security.SecurityMiddleware',\n        'django.contrib.sessions.middleware.SessionMiddleware',\n        'django.middleware.common.CommonMiddleware',\n        'django.middleware.csrf.CsrfViewMiddleware',\n        'django.contrib.auth.middleware.AuthenticationMiddleware',\n        'django.contrib.messages.middleware.MessageMiddleware',\n        'django.middleware.clickjacking.XFrameOptionsMiddleware',\n    ]\n\nA Django installation doesn't require any middleware — :setting:`MIDDLEWARE`\ncan be empty, if you'd like — but it's strongly suggested that you at least use\n:class:`~django.middleware.common.CommonMiddleware`.\n\nThe order in :setting:`MIDDLEWARE` matters because a middleware can depend on\nother middleware. For instance,\n:class:`~django.contrib.auth.middleware.AuthenticationMiddleware` stores the\nauthenticated user in the session; therefore, it must run after\n:class:`~django.contrib.sessions.middleware.SessionMiddleware`. See\n:ref:`middleware-ordering` for some common hints about ordering of Django\nmiddleware classes.\n\nMiddleware order and layering\n=============================\n\nDuring the request phase, before calling the view, Django applies middleware in\nthe order it's defined in :setting:`MIDDLEWARE`, top-down.\n\nYou can think of it like an onion: each middleware class is a \"layer\" that\nwraps the view, which is in the core of the onion. If the request passes\nthrough all the layers of the onion (each one calls ``get_response`` to pass\nthe request in to the next layer), all the way to the view at the core, the\nresponse will then pass through every layer (in reverse order) on the way back\nout.\n\nIf one of the layers decides to short-circuit and return a response without\never calling its ``get_response``, none of the layers of the onion inside that\nlayer (including the view) will see the request or the response. The response\nwill only return through the same layers that the request passed in through.\n\nOther middleware hooks\n======================\n\nBesides the basic request/response middleware pattern described earlier, you\ncan add three other special methods to class-based middleware:\n\n.. _view-middleware:\n\n``process_view()``\n------------------\n\n.. method:: process_view(request, view_func, view_args, view_kwargs)\n\n``request`` is an :class:`~django.http.HttpRequest` object. ``view_func`` is\nthe Python function that Django is about to use. (It's the actual function\nobject, not the name of the function as a string.) ``view_args`` is a list of\npositional arguments that will be passed to the view, and ``view_kwargs`` is a\ndictionary of keyword arguments that will be passed to the view. Neither\n``view_args`` nor ``view_kwargs`` include the first view argument\n(``request``).\n\n``process_view()`` is called just before Django calls the view.\n\nIt should return either ``None`` or an :class:`~django.http.HttpResponse`\nobject. If it returns ``None``, Django will continue processing this request,\nexecuting any other ``process_view()`` middleware and, then, the appropriate\nview. If it returns an :class:`~django.http.HttpResponse` object, Django won't\nbother calling the appropriate view; it'll apply response middleware to that\n:class:`~django.http.HttpResponse` and return the result.\n\n.. note::\n\n    Accessing :attr:`request.POST <django.http.HttpRequest.POST>` inside\n    middleware before the view runs or in ``process_view()`` will prevent any\n    view running after the middleware from being able to :ref:`modify the\n    upload handlers for the request <modifying_upload_handlers_on_the_fly>`,\n    and should normally be avoided.\n\n    The :class:`~django.middleware.csrf.CsrfViewMiddleware` class can be\n    considered an exception, as it provides the\n    :func:`~django.views.decorators.csrf.csrf_exempt` and\n    :func:`~django.views.decorators.csrf.csrf_protect` decorators which allow\n    views to explicitly control at what point the CSRF validation should occur.\n\n.. _exception-middleware:\n\n``process_exception()``\n-----------------------\n\n.. method:: process_exception(request, exception)\n\n``request`` is an :class:`~django.http.HttpRequest` object. ``exception`` is an\n``Exception`` object raised by the view function.\n\nDjango calls ``process_exception()`` when a view raises an exception.\n``process_exception()`` should return either ``None`` or an\n:class:`~django.http.HttpResponse` object. If it returns an\n:class:`~django.http.HttpResponse` object, the template response and response\nmiddleware will be applied and the resulting response returned to the\nbrowser. Otherwise, :ref:`default exception handling <error-views>` kicks in.\n\nAgain, middleware are run in reverse order during the response phase, which\nincludes ``process_exception``. If an exception middleware returns a response,\nthe ``process_exception`` methods of the middleware classes above that\nmiddleware won't be called at all.\n\n.. _template-response-middleware:\n\n``process_template_response()``\n-------------------------------\n\n.. method:: process_template_response(request, response)\n\n``request`` is an :class:`~django.http.HttpRequest` object. ``response`` is\nthe :class:`~django.template.response.TemplateResponse` object (or equivalent)\nreturned by a Django view or by a middleware.\n\n``process_template_response()`` is called just after the view has finished\nexecuting, if the response instance has a ``render()`` method, indicating that\nit is a :class:`~django.template.response.TemplateResponse` or equivalent.\n\nIt must return a response object that implements a ``render`` method. It could\nalter the given ``response`` by changing ``response.template_name`` and\n``response.context_data``, or it could create and return a brand-new\n:class:`~django.template.response.TemplateResponse` or equivalent.\n\nYou don't need to explicitly render responses -- responses will be\nautomatically rendered once all template response middleware has been\ncalled.\n\nMiddleware are run in reverse order during the response phase, which\nincludes ``process_template_response()``.\n\nDealing with streaming responses\n================================\n\nUnlike :class:`~django.http.HttpResponse`,\n:class:`~django.http.StreamingHttpResponse` does not have a ``content``\nattribute. As a result, middleware can no longer assume that all responses\nwill have a ``content`` attribute. If they need access to the content, they\nmust test for streaming responses and adjust their behavior accordingly::\n\n    if response.streaming:\n        response.streaming_content = wrap_streaming_content(response.streaming_content)\n    else:\n        response.content = alter_content(response.content)\n\n.. note::\n\n    ``streaming_content`` should be assumed to be too large to hold in memory.\n    Response middleware may wrap it in a new generator, but must not consume\n    it. Wrapping is typically implemented as follows::\n\n        def wrap_streaming_content(content):\n            for chunk in content:\n                yield alter_content(chunk)\n\nException handling\n==================\n\nDjango automatically converts exceptions raised by the view or by middleware\ninto an appropriate HTTP response with an error status code. :ref:`Certain\nexceptions <error-views>` are converted to 4xx status codes, while an unknown\nexception is converted to a 500 status code.\n\nThis conversion takes place before and after each middleware (you can think of\nit as the thin film in between each layer of the onion), so that every\nmiddleware can always rely on getting some kind of HTTP response back from\ncalling its ``get_response`` callable. Middleware don't need to worry about\nwrapping their call to ``get_response`` in a ``try/except`` and handling an\nexception that might have been raised by a later middleware or the view. Even\nif the very next middleware in the chain raises an\n:class:`~django.http.Http404` exception, for example, your middleware won't see\nthat exception; instead it will get an :class:`~django.http.HttpResponse`\nobject with a :attr:`~django.http.HttpResponse.status_code` of 404.\n\n.. _async-middleware:\n\nAsynchronous support\n====================\n\n.. versionadded:: 3.1\n\nMiddleware can support any combination of synchronous and asynchronous\nrequests. Django will adapt requests to fit the middleware's requirements if it\ncannot support both, but at a performance penalty.\n\nBy default, Django assumes that your middleware is capable of handling only\nsynchronous requests. To change these assumptions, set the following attributes\non your middleware factory function or class:\n\n* ``sync_capable`` is a boolean indicating if the middleware can handle\n  synchronous requests. Defaults to ``True``.\n\n* ``async_capable`` is a boolean indicating if the middleware can handle\n  asynchronous requests. Defaults to ``False``.\n\nIf your middleware has both ``sync_capable = True`` and\n``async_capable = True``, then Django will pass it the request without\nconverting it. In this case, you can work out if your middleware will receive\nasync requests by checking if the ``get_response`` object you are passed is a\ncoroutine function, using :py:func:`asyncio.iscoroutinefunction`.\n\nThe ``django.utils.decorators`` module contains\n:func:`~django.utils.decorators.sync_only_middleware`,\n:func:`~django.utils.decorators.async_only_middleware`, and\n:func:`~django.utils.decorators.sync_and_async_middleware` decorators that\nallow you to apply these flags to middleware factory functions.\n\nThe returned callable must match the sync or async nature of the\n``get_response`` method. If you have an asynchronous ``get_response``, you must\nreturn a coroutine function (``async def``).\n\n``process_view``, ``process_template_response`` and ``process_exception``\nmethods, if they are provided, should also be adapted to match the sync/async\nmode. However, Django will individually adapt them as required if you do not,\nat an additional performance penalty.\n\nHere's an example of how to create a middleware function that supports both::\n\n    import asyncio\n    from django.utils.decorators import sync_and_async_middleware\n\n    @sync_and_async_middleware\n    def simple_middleware(get_response):\n        # One-time configuration and initialization goes here.\n        if asyncio.iscoroutinefunction(get_response):\n            async def middleware(request):\n                # Do something here!\n                response = await get_response(request)\n                return response\n\n        else:\n            def middleware(request):\n                # Do something here!\n                response = get_response(request)\n                return response\n\n        return middleware\n\n.. note::\n\n    If you declare a hybrid middleware that supports both synchronous and\n    asynchronous calls, the kind of call you get may not match the underlying\n    view. Django will optimize the middleware call stack to have as few\n    sync/async transitions as possible.\n\n    Thus, even if you are wrapping an async view, you may be called in sync\n    mode if there is other, synchronous middleware between you and the view.\n\n.. _upgrading-middleware:\n\nUpgrading pre-Django 1.10-style middleware\n==========================================\n\n.. class:: django.utils.deprecation.MiddlewareMixin\n    :module:\n\nDjango provides ``django.utils.deprecation.MiddlewareMixin`` to ease creating\nmiddleware classes that are compatible with both :setting:`MIDDLEWARE` and the\nold ``MIDDLEWARE_CLASSES``, and support synchronous and asynchronous requests.\nAll middleware classes included with Django are compatible with both settings.\n\nThe mixin provides an ``__init__()`` method that requires a ``get_response``\nargument and stores it in ``self.get_response``.\n\nThe ``__call__()`` method:\n\n#. Calls ``self.process_request(request)`` (if defined).\n#. Calls ``self.get_response(request)`` to get the response from later\n   middleware and the view.\n#. Calls ``self.process_response(request, response)`` (if defined).\n#. Returns the response.\n\nIf used with ``MIDDLEWARE_CLASSES``, the ``__call__()`` method will\nnever be used; Django calls ``process_request()`` and ``process_response()``\ndirectly.\n\nIn most cases, inheriting from this mixin will be sufficient to make an\nold-style middleware compatible with the new system with sufficient\nbackwards-compatibility. The new short-circuiting semantics will be harmless or\neven beneficial to the existing middleware. In a few cases, a middleware class\nmay need some changes to adjust to the new semantics.\n\nThese are the behavioral differences between using :setting:`MIDDLEWARE` and\n``MIDDLEWARE_CLASSES``:\n\n#. Under ``MIDDLEWARE_CLASSES``, every middleware will always have its\n   ``process_response`` method called, even if an earlier middleware\n   short-circuited by returning a response from its ``process_request``\n   method. Under :setting:`MIDDLEWARE`, middleware behaves more like an onion:\n   the layers that a response goes through on the way out are the same layers\n   that saw the request on the way in. If a middleware short-circuits, only\n   that middleware and the ones before it in :setting:`MIDDLEWARE` will see the\n   response.\n\n#. Under ``MIDDLEWARE_CLASSES``, ``process_exception`` is applied to\n   exceptions raised from a middleware ``process_request`` method. Under\n   :setting:`MIDDLEWARE`, ``process_exception`` applies only to exceptions\n   raised from the view (or from the ``render`` method of a\n   :class:`~django.template.response.TemplateResponse`). Exceptions raised from\n   a middleware are converted to the appropriate HTTP response and then passed\n   to the next middleware.\n\n#. Under ``MIDDLEWARE_CLASSES``, if a ``process_response`` method raises\n   an exception, the ``process_response`` methods of all earlier middleware are\n   skipped and a ``500 Internal Server Error`` HTTP response is always\n   returned (even if the exception raised was e.g. an\n   :class:`~django.http.Http404`). Under :setting:`MIDDLEWARE`, an exception\n   raised from a middleware will immediately be converted to the appropriate\n   HTTP response, and then the next middleware in line will see that\n   response. Middleware are never skipped due to a middleware raising an\n   exception.\n\n.. versionchanged:: 3.1\n\n    Support for asynchronous requests was added to the ``MiddlewareMixin``.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":300,"nodeType":"TextFile","repoName":null,"name":"search.txt","path":"docs/topics/db","text":"======\nSearch\n======\n\nA common task for web applications is to search some data in the database with\nuser input. In a simple case, this could be filtering a list of objects by a\ncategory. A more complex use case might require searching with weighting,\ncategorization, highlighting, multiple languages, and so on. This document\nexplains some of the possible use cases and the tools you can use.\n\nWe'll refer to the same models used in :doc:`/topics/db/queries`.\n\nUse Cases\n=========\n\nStandard textual queries\n------------------------\n\nText-based fields have a selection of matching operations. For example, you may\nwish to allow lookup up an author like so::\n\n    >>> Author.objects.filter(name__contains='Terry')\n    [<Author: Terry Gilliam>, <Author: Terry Jones>]\n\nThis is a very fragile solution as it requires the user to know an exact\nsubstring of the author's name. A better approach could be a case-insensitive\nmatch (:lookup:`icontains`), but this is only marginally better.\n\nA database's more advanced comparison functions\n-----------------------------------------------\n\nIf you're using PostgreSQL, Django provides :doc:`a selection of database\nspecific tools </ref/contrib/postgres/search>` to allow you to leverage more\ncomplex querying options. Other databases have different selections of tools,\npossibly via plugins or user-defined functions. Django doesn't include any\nsupport for them at this time. We'll use some examples from PostgreSQL to\ndemonstrate the kind of functionality databases may have.\n\n.. admonition:: Searching in other databases\n\n    All of the searching tools provided by :mod:`django.contrib.postgres` are\n    constructed entirely on public APIs such as :doc:`custom lookups\n    </ref/models/lookups>` and :doc:`database functions\n    </ref/models/database-functions>`. Depending on your database, you should\n    be able to construct queries to allow similar APIs. If there are specific\n    things which cannot be achieved this way, please open a ticket.\n\nIn the above example, we determined that a case insensitive lookup would be\nmore useful. When dealing with non-English names, a further improvement is to\nuse :lookup:`unaccented comparison <unaccent>`::\n\n    >>> Author.objects.filter(name__unaccent__icontains='Helen')\n    [<Author: Helen Mirren>, <Author: Helena Bonham Carter>, <Author: Hélène Joy>]\n\nThis shows another issue, where we are matching against a different spelling of\nthe name. In this case we have an asymmetry though - a search for ``Helen``\nwill pick up ``Helena`` or ``Hélène``, but not the reverse. Another option\nwould be to use a :lookup:`trigram_similar` comparison, which compares\nsequences of letters.\n\nFor example::\n\n    >>> Author.objects.filter(name__unaccent__lower__trigram_similar='Hélène')\n    [<Author: Helen Mirren>, <Author: Hélène Joy>]\n\nNow we have a different problem - the longer name of \"Helena Bonham Carter\"\ndoesn't show up as it is much longer. Trigram searches consider all\ncombinations of three letters, and compares how many appear in both search and\nsource strings. For the longer name, there are more combinations which appear\nin the source string so it is no longer considered a close match.\n\nThe correct choice of comparison functions here depends on your particular data\nset, for example the language(s) used and the type of text being searched. All\nof the examples we've seen are on short strings where the user is likely to\nenter something close (by varying definitions) to the source data.\n\nDocument-based search\n---------------------\n\nStandard database operations stop being a useful approach when you start\nconsidering large blocks of text. Whereas the examples above can be thought of\nas operations on a string of characters, full text search looks at the actual\nwords. Depending on the system used, it's likely to use some of the following\nideas:\n\n- Ignoring \"stop words\" such as \"a\", \"the\", \"and\".\n- Stemming words, so that \"pony\" and \"ponies\" are considered similar.\n- Weighting words based on different criteria such as how frequently they\n  appear in the text, or the importance of the fields, such as the title or\n  keywords, that they appear in.\n\nThere are many alternatives for using searching software, some of the most\nprominent are Elastic_ and Solr_. These are full document-based search\nsolutions. To use them with data from Django models, you'll need a layer which\ntranslates your data into a textual document, including back-references to the\ndatabase ids. When a search using the engine returns a certain document, you\ncan then look it up in the database. There are a variety of third-party\nlibraries which are designed to help with this process.\n\n.. _Elastic: https://www.elastic.co/\n.. _Solr: https://lucene.apache.org/solr/\n\nPostgreSQL support\n~~~~~~~~~~~~~~~~~~\n\nPostgreSQL has its own full text search implementation built-in. While not as\npowerful as some other search engines, it has the advantage of being inside\nyour database and so can easily be combined with other relational queries such\nas categorization.\n\nThe :mod:`django.contrib.postgres` module provides some helpers to make these\nqueries. For example, a query might select all the blog entries which mention\n\"cheese\"::\n\n    >>> Entry.objects.filter(body_text__search='cheese')\n    [<Entry: Cheese on Toast recipes>, <Entry: Pizza recipes>]\n\nYou can also filter on a combination of fields and on related models::\n\n    >>> Entry.objects.annotate(\n    ...     search=SearchVector('blog__tagline', 'body_text'),\n    ... ).filter(search='cheese')\n    [\n        <Entry: Cheese on Toast recipes>,\n        <Entry: Pizza Recipes>,\n        <Entry: Dairy farming in Argentina>,\n    ]\n\nSee the ``contrib.postgres`` :doc:`/ref/contrib/postgres/search` document for\ncomplete details.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":301,"nodeType":"Package","repoName":null,"name":"docs/topics/forms","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":302,"nodeType":"TextFile","repoName":null,"name":"media.txt","path":"docs/topics/forms","text":"=================================\nForm Assets (the ``Media`` class)\n=================================\n\nRendering an attractive and easy-to-use Web form requires more than just\nHTML - it also requires CSS stylesheets, and if you want to use fancy\n\"Web2.0\" widgets, you may also need to include some JavaScript on each\npage. The exact combination of CSS and JavaScript that is required for\nany given page will depend upon the widgets that are in use on that page.\n\nThis is where asset definitions come in. Django allows you to\nassociate different files -- like stylesheets and scripts -- with the\nforms and widgets that require those assets. For example, if you want\nto use a calendar to render DateFields, you can define a custom\nCalendar widget. This widget can then be associated with the CSS and\nJavaScript that is required to render the calendar. When the Calendar\nwidget is used on a form, Django is able to identify the CSS and\nJavaScript files that are required, and provide the list of file names\nin a form suitable for inclusion on your Web page.\n\n.. admonition:: Assets and Django Admin\n\n    The Django Admin application defines a number of customized\n    widgets for calendars, filtered selections, and so on. These\n    widgets define asset requirements, and the Django Admin uses the\n    custom widgets in place of the Django defaults. The Admin\n    templates will only include those files that are required to\n    render the widgets on any given page.\n\n    If you like the widgets that the Django Admin application uses,\n    feel free to use them in your own application! They're all stored\n    in ``django.contrib.admin.widgets``.\n\n.. admonition:: Which JavaScript toolkit?\n\n    Many JavaScript toolkits exist, and many of them include widgets (such\n    as calendar widgets) that can be used to enhance your application.\n    Django has deliberately avoided blessing any one JavaScript toolkit.\n    Each toolkit has its own relative strengths and weaknesses - use\n    whichever toolkit suits your requirements. Django is able to integrate\n    with any JavaScript toolkit.\n\n.. _assets-as-a-static-definition:\n\nAssets as a static definition\n=============================\n\nThe easiest way to define assets is as a static definition. Using this\nmethod, the declaration is an inner ``Media`` class. The properties of the\ninner class define the requirements.\n\nHere's an example::\n\n    from django import forms\n\n    class CalendarWidget(forms.TextInput):\n        class Media:\n            css = {\n                'all': ('pretty.css',)\n            }\n            js = ('animations.js', 'actions.js')\n\nThis code defines a ``CalendarWidget``, which will be based on ``TextInput``.\nEvery time the CalendarWidget is used on a form, that form will be directed\nto include the CSS file ``pretty.css``, and the JavaScript files\n``animations.js`` and ``actions.js``.\n\nThis static definition is converted at runtime into a widget property\nnamed ``media``. The list of assets for a ``CalendarWidget`` instance\ncan be retrieved through this property::\n\n    >>> w = CalendarWidget()\n    >>> print(w.media)\n    <link href=\"http://static.example.com/pretty.css\" type=\"text/css\" media=\"all\" rel=\"stylesheet\">\n    <script src=\"http://static.example.com/animations.js\"></script>\n    <script src=\"http://static.example.com/actions.js\"></script>\n\nHere's a list of all possible ``Media`` options. There are no required options.\n\n``css``\n-------\n\nA dictionary describing the CSS files required for various forms of output\nmedia.\n\nThe values in the dictionary should be a tuple/list of file names. See\n:ref:`the section on paths <form-asset-paths>` for details of how to\nspecify paths to these files.\n\nThe keys in the dictionary are the output media types. These are the same\ntypes accepted by CSS files in media declarations: 'all', 'aural', 'braille',\n'embossed', 'handheld', 'print', 'projection', 'screen', 'tty' and 'tv'. If\nyou need to have different stylesheets for different media types, provide\na list of CSS files for each output medium. The following example would\nprovide two CSS options -- one for the screen, and one for print::\n\n    class Media:\n        css = {\n            'screen': ('pretty.css',),\n            'print': ('newspaper.css',)\n        }\n\nIf a group of CSS files are appropriate for multiple output media types,\nthe dictionary key can be a comma separated list of output media types.\nIn the following example, TV's and projectors will have the same media\nrequirements::\n\n    class Media:\n        css = {\n            'screen': ('pretty.css',),\n            'tv,projector': ('lo_res.css',),\n            'print': ('newspaper.css',)\n        }\n\nIf this last CSS definition were to be rendered, it would become the following HTML::\n\n    <link href=\"http://static.example.com/pretty.css\" type=\"text/css\" media=\"screen\" rel=\"stylesheet\">\n    <link href=\"http://static.example.com/lo_res.css\" type=\"text/css\" media=\"tv,projector\" rel=\"stylesheet\">\n    <link href=\"http://static.example.com/newspaper.css\" type=\"text/css\" media=\"print\" rel=\"stylesheet\">\n\n``js``\n------\n\nA tuple describing the required JavaScript files. See :ref:`the\nsection on paths <form-asset-paths>` for details of how to specify\npaths to these files.\n\n``extend``\n----------\n\nA boolean defining inheritance behavior for ``Media`` declarations.\n\nBy default, any object using a static ``Media`` definition will\ninherit all the assets associated with the parent widget. This occurs\nregardless of how the parent defines its own requirements. For\nexample, if we were to extend our basic Calendar widget from the\nexample above::\n\n    >>> class FancyCalendarWidget(CalendarWidget):\n    ...     class Media:\n    ...         css = {\n    ...             'all': ('fancy.css',)\n    ...         }\n    ...         js = ('whizbang.js',)\n\n    >>> w = FancyCalendarWidget()\n    >>> print(w.media)\n    <link href=\"http://static.example.com/pretty.css\" type=\"text/css\" media=\"all\" rel=\"stylesheet\">\n    <link href=\"http://static.example.com/fancy.css\" type=\"text/css\" media=\"all\" rel=\"stylesheet\">\n    <script src=\"http://static.example.com/animations.js\"></script>\n    <script src=\"http://static.example.com/actions.js\"></script>\n    <script src=\"http://static.example.com/whizbang.js\"></script>\n\nThe FancyCalendar widget inherits all the assets from its parent\nwidget. If you don't want ``Media`` to be inherited in this way, add\nan ``extend=False`` declaration to the ``Media`` declaration::\n\n    >>> class FancyCalendarWidget(CalendarWidget):\n    ...     class Media:\n    ...         extend = False\n    ...         css = {\n    ...             'all': ('fancy.css',)\n    ...         }\n    ...         js = ('whizbang.js',)\n\n    >>> w = FancyCalendarWidget()\n    >>> print(w.media)\n    <link href=\"http://static.example.com/fancy.css\" type=\"text/css\" media=\"all\" rel=\"stylesheet\">\n    <script src=\"http://static.example.com/whizbang.js\"></script>\n\nIf you require even more control over inheritance, define your assets using a\n:ref:`dynamic property <dynamic-property>`. Dynamic properties give you\ncomplete control over which files are inherited, and which are not.\n\n.. _dynamic-property:\n\n``Media`` as a dynamic property\n===============================\n\nIf you need to perform some more sophisticated manipulation of asset\nrequirements, you can define the ``media`` property directly. This is\ndone by defining a widget property that returns an instance of\n``forms.Media``.  The constructor for ``forms.Media`` accepts ``css``\nand ``js`` keyword arguments in the same format as that used in a\nstatic media definition.\n\nFor example, the static definition for our Calendar Widget could also\nbe defined in a dynamic fashion::\n\n    class CalendarWidget(forms.TextInput):\n        @property\n        def media(self):\n            return forms.Media(css={'all': ('pretty.css',)},\n                               js=('animations.js', 'actions.js'))\n\nSee the section on `Media objects`_ for more details on how to construct\nreturn values for dynamic ``media`` properties.\n\n.. _form-asset-paths:\n\nPaths in asset definitions\n==========================\n\nPaths used to specify assets can be either relative or absolute. If a\npath starts with ``/``, ``http://`` or ``https://``, it will be\ninterpreted as an absolute path, and left as-is. All other paths will\nbe prepended with the value of the appropriate prefix. If the\n:mod:`django.contrib.staticfiles` app is installed, it will be used to serve\nassets.\n\nWhether or not you use :mod:`django.contrib.staticfiles`,  the\n:setting:`STATIC_URL` and :setting:`STATIC_ROOT` settings are required to\nrender a complete web page.\n\nTo find the appropriate prefix to use, Django will check if the\n:setting:`STATIC_URL` setting is not ``None`` and automatically fall back\nto using :setting:`MEDIA_URL`. For example, if the :setting:`MEDIA_URL` for\nyour site was ``'http://uploads.example.com/'`` and :setting:`STATIC_URL`\nwas ``None``::\n\n    >>> from django import forms\n    >>> class CalendarWidget(forms.TextInput):\n    ...     class Media:\n    ...         css = {\n    ...             'all': ('/css/pretty.css',),\n    ...         }\n    ...         js = ('animations.js', 'http://othersite.com/actions.js')\n\n    >>> w = CalendarWidget()\n    >>> print(w.media)\n    <link href=\"/css/pretty.css\" type=\"text/css\" media=\"all\" rel=\"stylesheet\">\n    <script src=\"http://uploads.example.com/animations.js\"></script>\n    <script src=\"http://othersite.com/actions.js\"></script>\n\nBut if :setting:`STATIC_URL` is ``'http://static.example.com/'``::\n\n    >>> w = CalendarWidget()\n    >>> print(w.media)\n    <link href=\"/css/pretty.css\" type=\"text/css\" media=\"all\" rel=\"stylesheet\">\n    <script src=\"http://static.example.com/animations.js\"></script>\n    <script src=\"http://othersite.com/actions.js\"></script>\n\nOr if :mod:`~django.contrib.staticfiles` is configured using the\n:class:`~django.contrib.staticfiles.storage.ManifestStaticFilesStorage`::\n\n    >>> w = CalendarWidget()\n    >>> print(w.media)\n    <link href=\"/css/pretty.css\" type=\"text/css\" media=\"all\" rel=\"stylesheet\">\n    <script src=\"https://static.example.com/animations.27e20196a850.js\"></script>\n    <script src=\"http://othersite.com/actions.js\"></script>\n\n``Media`` objects\n=================\n\nWhen you interrogate the ``media`` attribute of a widget or form, the\nvalue that is returned is a ``forms.Media`` object. As we have already\nseen, the string representation of a ``Media`` object is the HTML\nrequired to include the relevant files in the ``<head>`` block of your\nHTML page.\n\nHowever, ``Media`` objects have some other interesting properties.\n\nSubsets of assets\n-----------------\n\nIf you only want files of a particular type, you can use the subscript\noperator to filter out a medium of interest. For example::\n\n    >>> w = CalendarWidget()\n    >>> print(w.media)\n    <link href=\"http://static.example.com/pretty.css\" type=\"text/css\" media=\"all\" rel=\"stylesheet\">\n    <script src=\"http://static.example.com/animations.js\"></script>\n    <script src=\"http://static.example.com/actions.js\"></script>\n\n    >>> print(w.media['css'])\n    <link href=\"http://static.example.com/pretty.css\" type=\"text/css\" media=\"all\" rel=\"stylesheet\">\n\nWhen you use the subscript operator, the value that is returned is a\nnew ``Media`` object -- but one that only contains the media of interest.\n\nCombining ``Media`` objects\n---------------------------\n\n``Media`` objects can also be added together. When two ``Media`` objects are\nadded, the resulting ``Media`` object contains the union of the assets\nspecified by both::\n\n    >>> from django import forms\n    >>> class CalendarWidget(forms.TextInput):\n    ...     class Media:\n    ...         css = {\n    ...             'all': ('pretty.css',)\n    ...         }\n    ...         js = ('animations.js', 'actions.js')\n\n    >>> class OtherWidget(forms.TextInput):\n    ...     class Media:\n    ...         js = ('whizbang.js',)\n\n    >>> w1 = CalendarWidget()\n    >>> w2 = OtherWidget()\n    >>> print(w1.media + w2.media)\n    <link href=\"http://static.example.com/pretty.css\" type=\"text/css\" media=\"all\" rel=\"stylesheet\">\n    <script src=\"http://static.example.com/animations.js\"></script>\n    <script src=\"http://static.example.com/actions.js\"></script>\n    <script src=\"http://static.example.com/whizbang.js\"></script>\n\n.. _form-media-asset-order:\n\nOrder of assets\n---------------\n\nThe order in which assets are inserted into the DOM is often important. For\nexample, you may have a script that depends on jQuery. Therefore, combining\n``Media`` objects attempts to preserve the relative order in which assets are\ndefined in each ``Media`` class.\n\nFor example::\n\n    >>> from django import forms\n    >>> class CalendarWidget(forms.TextInput):\n    ...     class Media:\n    ...         js = ('jQuery.js', 'calendar.js', 'noConflict.js')\n    >>> class TimeWidget(forms.TextInput):\n    ...     class Media:\n    ...         js = ('jQuery.js', 'time.js', 'noConflict.js')\n    >>> w1 = CalendarWidget()\n    >>> w2 = TimeWidget()\n    >>> print(w1.media + w2.media)\n    <script src=\"http://static.example.com/jQuery.js\"></script>\n    <script src=\"http://static.example.com/calendar.js\"></script>\n    <script src=\"http://static.example.com/time.js\"></script>\n    <script src=\"http://static.example.com/noConflict.js\"></script>\n\nCombining ``Media`` objects with assets in a conflicting order results in a\n``MediaOrderConflictWarning``.\n\n``Media`` on Forms\n==================\n\nWidgets aren't the only objects that can have ``media`` definitions --\nforms can also define ``media``. The rules for ``media`` definitions\non forms are the same as the rules for widgets: declarations can be\nstatic or dynamic; path and inheritance rules for those declarations\nare exactly the same.\n\nRegardless of whether you define a ``media`` declaration, *all* Form\nobjects have a ``media`` property. The default value for this property\nis the result of adding the ``media`` definitions for all widgets that\nare part of the form::\n\n    >>> from django import forms\n    >>> class ContactForm(forms.Form):\n    ...     date = DateField(widget=CalendarWidget)\n    ...     name = CharField(max_length=40, widget=OtherWidget)\n\n    >>> f = ContactForm()\n    >>> f.media\n    <link href=\"http://static.example.com/pretty.css\" type=\"text/css\" media=\"all\" rel=\"stylesheet\">\n    <script src=\"http://static.example.com/animations.js\"></script>\n    <script src=\"http://static.example.com/actions.js\"></script>\n    <script src=\"http://static.example.com/whizbang.js\"></script>\n\nIf you want to associate additional assets with a form -- for example,\nCSS for form layout -- add a ``Media`` declaration to the form::\n\n    >>> class ContactForm(forms.Form):\n    ...     date = DateField(widget=CalendarWidget)\n    ...     name = CharField(max_length=40, widget=OtherWidget)\n    ...\n    ...     class Media:\n    ...         css = {\n    ...             'all': ('layout.css',)\n    ...         }\n\n    >>> f = ContactForm()\n    >>> f.media\n    <link href=\"http://static.example.com/pretty.css\" type=\"text/css\" media=\"all\" rel=\"stylesheet\">\n    <link href=\"http://static.example.com/layout.css\" type=\"text/css\" media=\"all\" rel=\"stylesheet\">\n    <script src=\"http://static.example.com/animations.js\"></script>\n    <script src=\"http://static.example.com/actions.js\"></script>\n    <script src=\"http://static.example.com/whizbang.js\"></script>\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":303,"nodeType":"Package","repoName":null,"name":"docs/topics/testing/_images","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":304,"nodeType":"TextFile","repoName":null,"name":"django_unittest_classes_hierarchy.graffle","path":"docs/topics/testing/_images","text":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"https://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>ActiveLayerIndex</key>\n\t<integer>0</integer>\n\t<key>ApplicationVersion</key>\n\t<array>\n\t\t<string>com.omnigroup.OmniGrafflePro</string>\n\t\t<string>139.15.0.171074</string>\n\t</array>\n\t<key>AutoAdjust</key>\n\t<true/>\n\t<key>BackgroundGraphic</key>\n\t<dict>\n\t\t<key>Bounds</key>\n\t\t<string>{{0, 0}, {559, 783}}</string>\n\t\t<key>Class</key>\n\t\t<string>SolidGraphic</string>\n\t\t<key>ID</key>\n\t\t<integer>2</integer>\n\t\t<key>Style</key>\n\t\t<dict>\n\t\t\t<key>shadow</key>\n\t\t\t<dict>\n\t\t\t\t<key>Draws</key>\n\t\t\t\t<string>NO</string>\n\t\t\t</dict>\n\t\t\t<key>stroke</key>\n\t\t\t<dict>\n\t\t\t\t<key>Draws</key>\n\t\t\t\t<string>NO</string>\n\t\t\t</dict>\n\t\t</dict>\n\t</dict>\n\t<key>BaseZoom</key>\n\t<integer>0</integer>\n\t<key>CanvasOrigin</key>\n\t<string>{0, 0}</string>\n\t<key>ColumnAlign</key>\n\t<integer>1</integer>\n\t<key>ColumnSpacing</key>\n\t<real>36</real>\n\t<key>CreationDate</key>\n\t<string>2012-12-16 18:52:14 +0000</string>\n\t<key>Creator</key>\n\t<string>Aymeric Augustin</string>\n\t<key>DisplayScale</key>\n\t<string>1.000 cm = 1.000 cm</string>\n\t<key>GraphDocumentVersion</key>\n\t<integer>8</integer>\n\t<key>GraphicsList</key>\n\t<array>\n\t\t<dict>\n\t\t\t<key>Class</key>\n\t\t\t<string>LineGraphic</string>\n\t\t\t<key>Head</key>\n\t\t\t<dict>\n\t\t\t\t<key>ID</key>\n\t\t\t\t<integer>8</integer>\n\t\t\t</dict>\n\t\t\t<key>ID</key>\n\t\t\t<integer>29</integer>\n\t\t\t<key>OrthogonalBarAutomatic</key>\n\t\t\t<true/>\n\t\t\t<key>OrthogonalBarPoint</key>\n\t\t\t<string>{0, 0}</string>\n\t\t\t<key>OrthogonalBarPosition</key>\n\t\t\t<real>-1</real>\n\t\t\t<key>Points</key>\n\t\t\t<array>\n\t\t\t\t<string>{369, 459}</string>\n\t\t\t\t<string>{216, 400.5}</string>\n\t\t\t</array>\n\t\t\t<key>Style</key>\n\t\t\t<dict>\n\t\t\t\t<key>stroke</key>\n\t\t\t\t<dict>\n\t\t\t\t\t<key>HeadArrow</key>\n\t\t\t\t\t<string>UMLInheritance</string>\n\t\t\t\t\t<key>HeadScale</key>\n\t\t\t\t\t<real>0.79999995231628418</real>\n\t\t\t\t\t<key>Legacy</key>\n\t\t\t\t\t<true/>\n\t\t\t\t\t<key>LineType</key>\n\t\t\t\t\t<integer>2</integer>\n\t\t\t\t\t<key>TailArrow</key>\n\t\t\t\t\t<string>0</string>\n\t\t\t\t</dict>\n\t\t\t</dict>\n\t\t\t<key>Tail</key>\n\t\t\t<dict>\n\t\t\t\t<key>ID</key>\n\t\t\t\t<integer>6</integer>\n\t\t\t\t<key>Info</key>\n\t\t\t\t<integer>2</integer>\n\t\t\t</dict>\n\t\t</dict>\n\t\t<dict>\n\t\t\t<key>Class</key>\n\t\t\t<string>LineGraphic</string>\n\t\t\t<key>Head</key>\n\t\t\t<dict>\n\t\t\t\t<key>ID</key>\n\t\t\t\t<integer>10</integer>\n\t\t\t</dict>\n\t\t\t<key>ID</key>\n\t\t\t<integer>26</integer>\n\t\t\t<key>OrthogonalBarAutomatic</key>\n\t\t\t<true/>\n\t\t\t<key>OrthogonalBarPoint</key>\n\t\t\t<string>{0, 0}</string>\n\t\t\t<key>OrthogonalBarPosition</key>\n\t\t\t<real>-1</real>\n\t\t\t<key>Points</key>\n\t\t\t<array>\n\t\t\t\t<string>{135, 315}</string>\n\t\t\t\t<string>{135, 261}</string>\n\t\t\t</array>\n\t\t\t<key>Style</key>\n\t\t\t<dict>\n\t\t\t\t<key>stroke</key>\n\t\t\t\t<dict>\n\t\t\t\t\t<key>HeadArrow</key>\n\t\t\t\t\t<string>UMLInheritance</string>\n\t\t\t\t\t<key>HeadScale</key>\n\t\t\t\t\t<real>0.79999995231628418</real>\n\t\t\t\t\t<key>Legacy</key>\n\t\t\t\t\t<true/>\n\t\t\t\t\t<key>LineType</key>\n\t\t\t\t\t<integer>2</integer>\n\t\t\t\t\t<key>TailArrow</key>\n\t\t\t\t\t<string>0</string>\n\t\t\t\t</dict>\n\t\t\t</dict>\n\t\t\t<key>Tail</key>\n\t\t\t<dict>\n\t\t\t\t<key>ID</key>\n\t\t\t\t<integer>9</integer>\n\t\t\t</dict>\n\t\t</dict>\n\t\t<dict>\n\t\t\t<key>Class</key>\n\t\t\t<string>LineGraphic</string>\n\t\t\t<key>Head</key>\n\t\t\t<dict>\n\t\t\t\t<key>ID</key>\n\t\t\t\t<integer>9</integer>\n\t\t\t</dict>\n\t\t\t<key>ID</key>\n\t\t\t<integer>25</integer>\n\t\t\t<key>OrthogonalBarAutomatic</key>\n\t\t\t<true/>\n\t\t\t<key>OrthogonalBarPoint</key>\n\t\t\t<string>{0, 0}</string>\n\t\t\t<key>OrthogonalBarPosition</key>\n\t\t\t<real>-1</real>\n\t\t\t<key>Points</key>\n\t\t\t<array>\n\t\t\t\t<string>{135, 387}</string>\n\t\t\t\t<string>{135, 342}</string>\n\t\t\t</array>\n\t\t\t<key>Style</key>\n\t\t\t<dict>\n\t\t\t\t<key>stroke</key>\n\t\t\t\t<dict>\n\t\t\t\t\t<key>HeadArrow</key>\n\t\t\t\t\t<string>UMLInheritance</string>\n\t\t\t\t\t<key>HeadScale</key>\n\t\t\t\t\t<real>0.79999995231628418</real>\n\t\t\t\t\t<key>Legacy</key>\n\t\t\t\t\t<true/>\n\t\t\t\t\t<key>LineType</key>\n\t\t\t\t\t<integer>2</integer>\n\t\t\t\t\t<key>TailArrow</key>\n\t\t\t\t\t<string>0</string>\n\t\t\t\t</dict>\n\t\t\t</dict>\n\t\t\t<key>Tail</key>\n\t\t\t<dict>\n\t\t\t\t<key>ID</key>\n\t\t\t\t<integer>8</integer>\n\t\t\t</dict>\n\t\t</dict>\n\t\t<dict>\n\t\t\t<key>Class</key>\n\t\t\t<string>LineGraphic</string>\n\t\t\t<key>Head</key>\n\t\t\t<dict>\n\t\t\t\t<key>ID</key>\n\t\t\t\t<integer>8</integer>\n\t\t\t</dict>\n\t\t\t<key>ID</key>\n\t\t\t<integer>23</integer>\n\t\t\t<key>OrthogonalBarAutomatic</key>\n\t\t\t<true/>\n\t\t\t<key>OrthogonalBarPoint</key>\n\t\t\t<string>{0, 0}</string>\n\t\t\t<key>OrthogonalBarPosition</key>\n\t\t\t<real>-1</real>\n\t\t\t<key>Points</key>\n\t\t\t<array>\n\t\t\t\t<string>{135, 459}</string>\n\t\t\t\t<string>{135, 414}</string>\n\t\t\t</array>\n\t\t\t<key>Style</key>\n\t\t\t<dict>\n\t\t\t\t<key>stroke</key>\n\t\t\t\t<dict>\n\t\t\t\t\t<key>HeadArrow</key>\n\t\t\t\t\t<string>UMLInheritance</string>\n\t\t\t\t\t<key>HeadScale</key>\n\t\t\t\t\t<real>0.79999995231628418</real>\n\t\t\t\t\t<key>Legacy</key>\n\t\t\t\t\t<true/>\n\t\t\t\t\t<key>LineType</key>\n\t\t\t\t\t<integer>2</integer>\n\t\t\t\t\t<key>TailArrow</key>\n\t\t\t\t\t<string>0</string>\n\t\t\t\t</dict>\n\t\t\t</dict>\n\t\t\t<key>Tail</key>\n\t\t\t<dict>\n\t\t\t\t<key>ID</key>\n\t\t\t\t<integer>7</integer>\n\t\t\t</dict>\n\t\t</dict>\n\t\t<dict>\n\t\t\t<key>Bounds</key>\n\t\t\t<string>{{54, 234}, {162, 27}}</string>\n\t\t\t<key>Class</key>\n\t\t\t<string>ShapedGraphic</string>\n\t\t\t<key>ID</key>\n\t\t\t<integer>10</integer>\n\t\t\t<key>Magnets</key>\n\t\t\t<array>\n\t\t\t\t<string>{0, 1}</string>\n\t\t\t\t<string>{0, -1}</string>\n\t\t\t\t<string>{1, 0}</string>\n\t\t\t\t<string>{-1, 0}</string>\n\t\t\t</array>\n\t\t\t<key>Shape</key>\n\t\t\t<string>Rectangle</string>\n\t\t\t<key>Style</key>\n\t\t\t<dict>\n\t\t\t\t<key>fill</key>\n\t\t\t\t<dict>\n\t\t\t\t\t<key>FillType</key>\n\t\t\t\t\t<integer>2</integer>\n\t\t\t\t\t<key>GradientAngle</key>\n\t\t\t\t\t<real>90</real>\n\t\t\t\t\t<key>GradientColor</key>\n\t\t\t\t\t<dict>\n\t\t\t\t\t\t<key>w</key>\n\t\t\t\t\t\t<string>0.666667</string>\n\t\t\t\t\t</dict>\n\t\t\t\t</dict>\n\t\t\t\t<key>stroke</key>\n\t\t\t\t<dict>\n\t\t\t\t\t<key>CornerRadius</key>\n\t\t\t\t\t<real>5</real>\n\t\t\t\t</dict>\n\t\t\t</dict>\n\t\t\t<key>Text</key>\n\t\t\t<dict>\n\t\t\t\t<key>Text</key>\n\t\t\t\t<string>{\\rtf1\\ansi\\ansicpg1252\\cocoartf1187\\cocoasubrtf390\n\\cocoascreenfonts1{\\fonttbl\\f0\\fmodern\\fcharset0 Courier;}\n{\\colortbl;\\red255\\green255\\blue255;}\n\\pard\\tx560\\tx1120\\tx1680\\tx2240\\tx2800\\tx3360\\tx3920\\tx4480\\tx5040\\tx5600\\tx6160\\tx6720\\pardirnatural\\qc\n\n\\f0\\fs24 \\cf0 TestCase}</string>\n\t\t\t</dict>\n\t\t</dict>\n\t\t<dict>\n\t\t\t<key>Bounds</key>\n\t\t\t<string>{{54, 315}, {162, 27}}</string>\n\t\t\t<key>Class</key>\n\t\t\t<string>ShapedGraphic</string>\n\t\t\t<key>ID</key>\n\t\t\t<integer>9</integer>\n\t\t\t<key>Magnets</key>\n\t\t\t<array>\n\t\t\t\t<string>{0, 1}</string>\n\t\t\t\t<string>{0, -1}</string>\n\t\t\t\t<string>{1, 0}</string>\n\t\t\t\t<string>{-1, 0}</string>\n\t\t\t</array>\n\t\t\t<key>Shape</key>\n\t\t\t<string>Rectangle</string>\n\t\t\t<key>Style</key>\n\t\t\t<dict>\n\t\t\t\t<key>fill</key>\n\t\t\t\t<dict>\n\t\t\t\t\t<key>FillType</key>\n\t\t\t\t\t<integer>2</integer>\n\t\t\t\t\t<key>GradientAngle</key>\n\t\t\t\t\t<real>90</real>\n\t\t\t\t\t<key>GradientColor</key>\n\t\t\t\t\t<dict>\n\t\t\t\t\t\t<key>w</key>\n\t\t\t\t\t\t<string>0.666667</string>\n\t\t\t\t\t</dict>\n\t\t\t\t</dict>\n\t\t\t\t<key>stroke</key>\n\t\t\t\t<dict>\n\t\t\t\t\t<key>CornerRadius</key>\n\t\t\t\t\t<real>5</real>\n\t\t\t\t</dict>\n\t\t\t</dict>\n\t\t\t<key>Text</key>\n\t\t\t<dict>\n\t\t\t\t<key>Text</key>\n\t\t\t\t<string>{\\rtf1\\ansi\\ansicpg1252\\cocoartf1187\\cocoasubrtf390\n\\cocoascreenfonts1{\\fonttbl\\f0\\fmodern\\fcharset0 Courier;}\n{\\colortbl;\\red255\\green255\\blue255;}\n\\pard\\tx560\\tx1120\\tx1680\\tx2240\\tx2800\\tx3360\\tx3920\\tx4480\\tx5040\\tx5600\\tx6160\\tx6720\\pardirnatural\\qc\n\n\\f0\\fs24 \\cf0 SimpleTestCase}</string>\n\t\t\t</dict>\n\t\t</dict>\n\t\t<dict>\n\t\t\t<key>Bounds</key>\n\t\t\t<string>{{54, 387}, {162, 27}}</string>\n\t\t\t<key>Class</key>\n\t\t\t<string>ShapedGraphic</string>\n\t\t\t<key>ID</key>\n\t\t\t<integer>8</integer>\n\t\t\t<key>Magnets</key>\n\t\t\t<array>\n\t\t\t\t<string>{0, 1}</string>\n\t\t\t\t<string>{0, -1}</string>\n\t\t\t\t<string>{1, 0}</string>\n\t\t\t\t<string>{-1, 0}</string>\n\t\t\t</array>\n\t\t\t<key>Shape</key>\n\t\t\t<string>Rectangle</string>\n\t\t\t<key>Style</key>\n\t\t\t<dict>\n\t\t\t\t<key>fill</key>\n\t\t\t\t<dict>\n\t\t\t\t\t<key>FillType</key>\n\t\t\t\t\t<integer>2</integer>\n\t\t\t\t\t<key>GradientAngle</key>\n\t\t\t\t\t<real>90</real>\n\t\t\t\t\t<key>GradientColor</key>\n\t\t\t\t\t<dict>\n\t\t\t\t\t\t<key>w</key>\n\t\t\t\t\t\t<string>0.666667</string>\n\t\t\t\t\t</dict>\n\t\t\t\t</dict>\n\t\t\t\t<key>stroke</key>\n\t\t\t\t<dict>\n\t\t\t\t\t<key>CornerRadius</key>\n\t\t\t\t\t<real>5</real>\n\t\t\t\t</dict>\n\t\t\t</dict>\n\t\t\t<key>Text</key>\n\t\t\t<dict>\n\t\t\t\t<key>Text</key>\n\t\t\t\t<string>{\\rtf1\\ansi\\ansicpg1252\\cocoartf1187\\cocoasubrtf390\n\\cocoascreenfonts1{\\fonttbl\\f0\\fmodern\\fcharset0 Courier;}\n{\\colortbl;\\red255\\green255\\blue255;}\n\\pard\\tx560\\tx1120\\tx1680\\tx2240\\tx2800\\tx3360\\tx3920\\tx4480\\tx5040\\tx5600\\tx6160\\tx6720\\pardirnatural\\qc\n\n\\f0\\fs24 \\cf0 TransactionTestCase}</string>\n\t\t\t</dict>\n\t\t</dict>\n\t\t<dict>\n\t\t\t<key>Bounds</key>\n\t\t\t<string>{{54, 459}, {162, 27}}</string>\n\t\t\t<key>Class</key>\n\t\t\t<string>ShapedGraphic</string>\n\t\t\t<key>ID</key>\n\t\t\t<integer>7</integer>\n\t\t\t<key>Magnets</key>\n\t\t\t<array>\n\t\t\t\t<string>{0, 1}</string>\n\t\t\t\t<string>{0, -1}</string>\n\t\t\t\t<string>{1, 0}</string>\n\t\t\t\t<string>{-1, 0}</string>\n\t\t\t</array>\n\t\t\t<key>Shape</key>\n\t\t\t<string>Rectangle</string>\n\t\t\t<key>Style</key>\n\t\t\t<dict>\n\t\t\t\t<key>fill</key>\n\t\t\t\t<dict>\n\t\t\t\t\t<key>FillType</key>\n\t\t\t\t\t<integer>2</integer>\n\t\t\t\t\t<key>GradientAngle</key>\n\t\t\t\t\t<real>90</real>\n\t\t\t\t\t<key>GradientColor</key>\n\t\t\t\t\t<dict>\n\t\t\t\t\t\t<key>w</key>\n\t\t\t\t\t\t<string>0.666667</string>\n\t\t\t\t\t</dict>\n\t\t\t\t</dict>\n\t\t\t\t<key>stroke</key>\n\t\t\t\t<dict>\n\t\t\t\t\t<key>CornerRadius</key>\n\t\t\t\t\t<real>5</real>\n\t\t\t\t</dict>\n\t\t\t</dict>\n\t\t\t<key>Text</key>\n\t\t\t<dict>\n\t\t\t\t<key>Text</key>\n\t\t\t\t<string>{\\rtf1\\ansi\\ansicpg1252\\cocoartf1187\\cocoasubrtf390\n\\cocoascreenfonts1{\\fonttbl\\f0\\fmodern\\fcharset0 Courier;}\n{\\colortbl;\\red255\\green255\\blue255;}\n\\pard\\tx560\\tx1120\\tx1680\\tx2240\\tx2800\\tx3360\\tx3920\\tx4480\\tx5040\\tx5600\\tx6160\\tx6720\\pardirnatural\\qc\n\n\\f0\\fs24 \\cf0 TestCase}</string>\n\t\t\t</dict>\n\t\t</dict>\n\t\t<dict>\n\t\t\t<key>Bounds</key>\n\t\t\t<string>{{288, 459}, {162, 27}}</string>\n\t\t\t<key>Class</key>\n\t\t\t<string>ShapedGraphic</string>\n\t\t\t<key>ID</key>\n\t\t\t<integer>6</integer>\n\t\t\t<key>Magnets</key>\n\t\t\t<array>\n\t\t\t\t<string>{0, 1}</string>\n\t\t\t\t<string>{0, -1}</string>\n\t\t\t\t<string>{1, 0}</string>\n\t\t\t\t<string>{-1, 0}</string>\n\t\t\t</array>\n\t\t\t<key>Shape</key>\n\t\t\t<string>Rectangle</string>\n\t\t\t<key>Style</key>\n\t\t\t<dict>\n\t\t\t\t<key>fill</key>\n\t\t\t\t<dict>\n\t\t\t\t\t<key>FillType</key>\n\t\t\t\t\t<integer>2</integer>\n\t\t\t\t\t<key>GradientAngle</key>\n\t\t\t\t\t<real>90</real>\n\t\t\t\t\t<key>GradientColor</key>\n\t\t\t\t\t<dict>\n\t\t\t\t\t\t<key>w</key>\n\t\t\t\t\t\t<string>0.666667</string>\n\t\t\t\t\t</dict>\n\t\t\t\t</dict>\n\t\t\t\t<key>stroke</key>\n\t\t\t\t<dict>\n\t\t\t\t\t<key>CornerRadius</key>\n\t\t\t\t\t<real>5</real>\n\t\t\t\t</dict>\n\t\t\t</dict>\n\t\t\t<key>Text</key>\n\t\t\t<dict>\n\t\t\t\t<key>Text</key>\n\t\t\t\t<string>{\\rtf1\\ansi\\ansicpg1252\\cocoartf1187\\cocoasubrtf390\n\\cocoascreenfonts1{\\fonttbl\\f0\\fmodern\\fcharset0 Courier;}\n{\\colortbl;\\red255\\green255\\blue255;}\n\\pard\\tx560\\tx1120\\tx1680\\tx2240\\tx2800\\tx3360\\tx3920\\tx4480\\tx5040\\tx5600\\tx6160\\tx6720\\pardirnatural\\qc\n\n\\f0\\fs24 \\cf0 LiveServerTestCase}</string>\n\t\t\t</dict>\n\t\t</dict>\n\t\t<dict>\n\t\t\t<key>Bounds</key>\n\t\t\t<string>{{18, 297}, {468, 207}}</string>\n\t\t\t<key>Class</key>\n\t\t\t<string>ShapedGraphic</string>\n\t\t\t<key>ID</key>\n\t\t\t<integer>13</integer>\n\t\t\t<key>Shape</key>\n\t\t\t<string>Rectangle</string>\n\t\t\t<key>Style</key>\n\t\t\t<dict/>\n\t\t\t<key>Text</key>\n\t\t\t<dict>\n\t\t\t\t<key>Align</key>\n\t\t\t\t<integer>2</integer>\n\t\t\t\t<key>Text</key>\n\t\t\t\t<string>{\\rtf1\\ansi\\ansicpg1252\\cocoartf1187\\cocoasubrtf390\n\\cocoascreenfonts1{\\fonttbl\\f0\\fmodern\\fcharset0 Courier;}\n{\\colortbl;\\red255\\green255\\blue255;}\n\\pard\\tx560\\tx1120\\tx1680\\tx2240\\tx2800\\tx3360\\tx3920\\tx4480\\tx5040\\tx5600\\tx6160\\tx6720\\pardirnatural\\qr\n\n\\f0\\fs24 \\cf0 django.test}</string>\n\t\t\t</dict>\n\t\t\t<key>TextPlacement</key>\n\t\t\t<integer>0</integer>\n\t\t</dict>\n\t\t<dict>\n\t\t\t<key>Bounds</key>\n\t\t\t<string>{{18, 216}, {468, 63}}</string>\n\t\t\t<key>Class</key>\n\t\t\t<string>ShapedGraphic</string>\n\t\t\t<key>ID</key>\n\t\t\t<integer>18</integer>\n\t\t\t<key>Shape</key>\n\t\t\t<string>Rectangle</string>\n\t\t\t<key>Style</key>\n\t\t\t<dict/>\n\t\t\t<key>Text</key>\n\t\t\t<dict>\n\t\t\t\t<key>Align</key>\n\t\t\t\t<integer>2</integer>\n\t\t\t\t<key>Text</key>\n\t\t\t\t<string>{\\rtf1\\ansi\\ansicpg1252\\cocoartf1187\\cocoasubrtf390\n\\cocoascreenfonts1{\\fonttbl\\f0\\fmodern\\fcharset0 Courier-Oblique;\\f1\\fmodern\\fcharset0 Courier;}\n{\\colortbl;\\red255\\green255\\blue255;}\n\\pard\\tx560\\tx1120\\tx1680\\tx2240\\tx2800\\tx3360\\tx3920\\tx4480\\tx5040\\tx5600\\tx6160\\tx6720\\pardirnatural\\qr\n\n\\f0\\i\\fs24 \\cf0 standard library\\\n\n\\f1\\i0 \\\n\\\nunittest}</string>\n\t\t\t</dict>\n\t\t\t<key>TextPlacement</key>\n\t\t\t<integer>0</integer>\n\t\t</dict>\n\t</array>\n\t<key>GridInfo</key>\n\t<dict>\n\t\t<key>ShowsGrid</key>\n\t\t<string>YES</string>\n\t\t<key>SnapsToGrid</key>\n\t\t<string>YES</string>\n\t</dict>\n\t<key>GuidesLocked</key>\n\t<string>NO</string>\n\t<key>GuidesVisible</key>\n\t<string>YES</string>\n\t<key>HPages</key>\n\t<integer>1</integer>\n\t<key>ImageCounter</key>\n\t<integer>1</integer>\n\t<key>KeepToScale</key>\n\t<false/>\n\t<key>Layers</key>\n\t<array>\n\t\t<dict>\n\t\t\t<key>Lock</key>\n\t\t\t<string>NO</string>\n\t\t\t<key>Name</key>\n\t\t\t<string>Calque 1</string>\n\t\t\t<key>Print</key>\n\t\t\t<string>YES</string>\n\t\t\t<key>View</key>\n\t\t\t<string>YES</string>\n\t\t</dict>\n\t</array>\n\t<key>LayoutInfo</key>\n\t<dict>\n\t\t<key>Animate</key>\n\t\t<string>NO</string>\n\t\t<key>circoMinDist</key>\n\t\t<real>18</real>\n\t\t<key>circoSeparation</key>\n\t\t<real>0.0</real>\n\t\t<key>layoutEngine</key>\n\t\t<string>dot</string>\n\t\t<key>neatoSeparation</key>\n\t\t<real>0.0</real>\n\t\t<key>twopiSeparation</key>\n\t\t<real>0.0</real>\n\t</dict>\n\t<key>LinksVisible</key>\n\t<string>NO</string>\n\t<key>MagnetsVisible</key>\n\t<string>NO</string>\n\t<key>MasterSheets</key>\n\t<array/>\n\t<key>ModificationDate</key>\n\t<string>2013-07-01 11:48:06 +0000</string>\n\t<key>Modifier</key>\n\t<string>Aymeric Augustin</string>\n\t<key>NotesVisible</key>\n\t<string>NO</string>\n\t<key>Orientation</key>\n\t<integer>2</integer>\n\t<key>OriginVisible</key>\n\t<string>NO</string>\n\t<key>PageBreaks</key>\n\t<string>YES</string>\n\t<key>PrintInfo</key>\n\t<dict>\n\t\t<key>NSBottomMargin</key>\n\t\t<array>\n\t\t\t<string>float</string>\n\t\t\t<string>41</string>\n\t\t</array>\n\t\t<key>NSHorizonalPagination</key>\n\t\t<array>\n\t\t\t<string>coded</string>\n\t\t\t<string>BAtzdHJlYW10eXBlZIHoA4QBQISEhAhOU051bWJlcgCEhAdOU1ZhbHVlAISECE5TT2JqZWN0AIWEASqEhAFxlwCG</string>\n\t\t</array>\n\t\t<key>NSLeftMargin</key>\n\t\t<array>\n\t\t\t<string>float</string>\n\t\t\t<string>18</string>\n\t\t</array>\n\t\t<key>NSPaperSize</key>\n\t\t<array>\n\t\t\t<string>size</string>\n\t\t\t<string>{595, 842}</string>\n\t\t</array>\n\t\t<key>NSPrintReverseOrientation</key>\n\t\t<array>\n\t\t\t<string>int</string>\n\t\t\t<string>0</string>\n\t\t</array>\n\t\t<key>NSRightMargin</key>\n\t\t<array>\n\t\t\t<string>float</string>\n\t\t\t<string>18</string>\n\t\t</array>\n\t\t<key>NSTopMargin</key>\n\t\t<array>\n\t\t\t<string>float</string>\n\t\t\t<string>18</string>\n\t\t</array>\n\t</dict>\n\t<key>PrintOnePage</key>\n\t<false/>\n\t<key>ReadOnly</key>\n\t<string>NO</string>\n\t<key>RowAlign</key>\n\t<integer>1</integer>\n\t<key>RowSpacing</key>\n\t<real>36</real>\n\t<key>SheetTitle</key>\n\t<string>Canevas 1</string>\n\t<key>SmartAlignmentGuidesActive</key>\n\t<string>YES</string>\n\t<key>SmartDistanceGuidesActive</key>\n\t<string>YES</string>\n\t<key>UniqueID</key>\n\t<integer>1</integer>\n\t<key>UseEntirePage</key>\n\t<false/>\n\t<key>VPages</key>\n\t<integer>1</integer>\n\t<key>WindowInfo</key>\n\t<dict>\n\t\t<key>CurrentSheet</key>\n\t\t<integer>0</integer>\n\t\t<key>ExpandedCanvases</key>\n\t\t<array/>\n\t\t<key>Frame</key>\n\t\t<string>{{613, 284}, {694, 774}}</string>\n\t\t<key>ListView</key>\n\t\t<true/>\n\t\t<key>OutlineWidth</key>\n\t\t<integer>142</integer>\n\t\t<key>RightSidebar</key>\n\t\t<false/>\n\t\t<key>ShowRuler</key>\n\t\t<true/>\n\t\t<key>Sidebar</key>\n\t\t<true/>\n\t\t<key>SidebarWidth</key>\n\t\t<integer>120</integer>\n\t\t<key>VisibleRegion</key>\n\t\t<string>{{0, 0}, {545, 620}}</string>\n\t\t<key>Zoom</key>\n\t\t<real>1</real>\n\t\t<key>ZoomValues</key>\n\t\t<array>\n\t\t\t<array>\n\t\t\t\t<string>Canevas 1</string>\n\t\t\t\t<real>1</real>\n\t\t\t\t<real>1</real>\n\t\t\t</array>\n\t\t</array>\n\t</dict>\n</dict>\n</plist>\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":305,"nodeType":"Package","repoName":null,"name":"docs/topics/class-based-views","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":306,"nodeType":"TextFile","repoName":null,"name":"generic-editing.txt","path":"docs/topics/class-based-views","text":"====================================\nForm handling with class-based views\n====================================\n\nForm processing generally has 3 paths:\n\n* Initial GET (blank or prepopulated form)\n* POST with invalid data (typically redisplay form with errors)\n* POST with valid data (process the data and typically redirect)\n\nImplementing this yourself often results in a lot of repeated boilerplate code\n(see :ref:`Using a form in a view<using-a-form-in-a-view>`). To help avoid\nthis, Django provides a collection of generic class-based views for form\nprocessing.\n\nBasic forms\n===========\n\nGiven a contact form:\n\n.. code-block:: python\n    :caption: forms.py\n\n    from django import forms\n\n    class ContactForm(forms.Form):\n        name = forms.CharField()\n        message = forms.CharField(widget=forms.Textarea)\n\n        def send_email(self):\n            # send email using the self.cleaned_data dictionary\n            pass\n\nThe view can be constructed using a ``FormView``:\n\n.. code-block:: python\n    :caption: views.py\n\n    from myapp.forms import ContactForm\n    from django.views.generic.edit import FormView\n\n    class ContactView(FormView):\n        template_name = 'contact.html'\n        form_class = ContactForm\n        success_url = '/thanks/'\n\n        def form_valid(self, form):\n            # This method is called when valid form data has been POSTed.\n            # It should return an HttpResponse.\n            form.send_email()\n            return super().form_valid(form)\n\nNotes:\n\n* FormView inherits\n  :class:`~django.views.generic.base.TemplateResponseMixin` so\n  :attr:`~django.views.generic.base.TemplateResponseMixin.template_name`\n  can be used here.\n* The default implementation for\n  :meth:`~django.views.generic.edit.FormMixin.form_valid` simply\n  redirects to the :attr:`~django.views.generic.edit.FormMixin.success_url`.\n\nModel forms\n===========\n\nGeneric views really shine when working with models.  These generic\nviews will automatically create a :class:`~django.forms.ModelForm`, so long as\nthey can work out which model class to use:\n\n* If the :attr:`~django.views.generic.edit.ModelFormMixin.model` attribute is\n  given, that model class will be used.\n* If :meth:`~django.views.generic.detail.SingleObjectMixin.get_object()`\n  returns an object, the class of that object will be used.\n* If a :attr:`~django.views.generic.detail.SingleObjectMixin.queryset` is\n  given, the model for that queryset will be used.\n\nModel form views provide a\n:meth:`~django.views.generic.edit.ModelFormMixin.form_valid()` implementation\nthat saves the model automatically.  You can override this if you have any\nspecial requirements; see below for examples.\n\nYou don't even need to provide a ``success_url`` for\n:class:`~django.views.generic.edit.CreateView` or\n:class:`~django.views.generic.edit.UpdateView` - they will use\n:meth:`~django.db.models.Model.get_absolute_url()` on the model object if available.\n\nIf you want to use a custom :class:`~django.forms.ModelForm` (for instance to\nadd extra validation), set\n:attr:`~django.views.generic.edit.FormMixin.form_class` on your view.\n\n.. note::\n    When specifying a custom form class, you must still specify the model,\n    even though the :attr:`~django.views.generic.edit.FormMixin.form_class` may\n    be a :class:`~django.forms.ModelForm`.\n\nFirst we need to add :meth:`~django.db.models.Model.get_absolute_url()` to our\n``Author`` class:\n\n.. code-block:: python\n    :caption: models.py\n\n    from django.db import models\n    from django.urls import reverse\n\n    class Author(models.Model):\n        name = models.CharField(max_length=200)\n\n        def get_absolute_url(self):\n            return reverse('author-detail', kwargs={'pk': self.pk})\n\nThen we can use :class:`CreateView` and friends to do the actual\nwork. Notice how we're just configuring the generic class-based views\nhere; we don't have to write any logic ourselves:\n\n.. code-block:: python\n    :caption: views.py\n\n    from django.urls import reverse_lazy\n    from django.views.generic.edit import CreateView, DeleteView, UpdateView\n    from myapp.models import Author\n\n    class AuthorCreate(CreateView):\n        model = Author\n        fields = ['name']\n\n    class AuthorUpdate(UpdateView):\n        model = Author\n        fields = ['name']\n\n    class AuthorDelete(DeleteView):\n        model = Author\n        success_url = reverse_lazy('author-list')\n\n.. note::\n    We have to use :func:`~django.urls.reverse_lazy` instead of\n    ``reverse()``, as the urls are not loaded when the file is imported.\n\nThe ``fields`` attribute works the same way as the ``fields`` attribute on the\ninner ``Meta`` class on :class:`~django.forms.ModelForm`. Unless you define the\nform class in another way, the attribute is required and the view will raise\nan :exc:`~django.core.exceptions.ImproperlyConfigured` exception if it's not.\n\nIf you specify both the :attr:`~django.views.generic.edit.ModelFormMixin.fields`\nand :attr:`~django.views.generic.edit.FormMixin.form_class` attributes, an\n:exc:`~django.core.exceptions.ImproperlyConfigured` exception will be raised.\n\nFinally, we hook these new views into the URLconf:\n\n.. code-block:: python\n    :caption: urls.py\n\n    from django.urls import path\n    from myapp.views import AuthorCreate, AuthorDelete, AuthorUpdate\n\n    urlpatterns = [\n        # ...\n        path('author/add/', AuthorCreate.as_view(), name='author-add'),\n        path('author/<int:pk>/', AuthorUpdate.as_view(), name='author-update'),\n        path('author/<int:pk>/delete/', AuthorDelete.as_view(), name='author-delete'),\n    ]\n\n.. note::\n\n    These views inherit\n    :class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`\n    which uses\n    :attr:`~django.views.generic.detail.SingleObjectTemplateResponseMixin.template_name_suffix`\n    to construct the\n    :attr:`~django.views.generic.base.TemplateResponseMixin.template_name`\n    based on the model.\n\n    In this example:\n\n    * :class:`CreateView` and :class:`UpdateView` use ``myapp/author_form.html``\n    * :class:`DeleteView` uses ``myapp/author_confirm_delete.html``\n\n    If you wish to have separate templates for :class:`CreateView` and\n    :class:`UpdateView`, you can set either\n    :attr:`~django.views.generic.base.TemplateResponseMixin.template_name` or\n    :attr:`~django.views.generic.detail.SingleObjectTemplateResponseMixin.template_name_suffix`\n    on your view class.\n\nModels and ``request.user``\n===========================\n\nTo track the user that created an object using a :class:`CreateView`,\nyou can use a custom :class:`~django.forms.ModelForm` to do this. First, add\nthe foreign key relation to the model:\n\n.. code-block:: python\n    :caption: models.py\n\n    from django.contrib.auth.models import User\n    from django.db import models\n\n    class Author(models.Model):\n        name = models.CharField(max_length=200)\n        created_by = models.ForeignKey(User, on_delete=models.CASCADE)\n\n        # ...\n\nIn the view, ensure that you don't include ``created_by`` in the list of fields\nto edit, and override\n:meth:`~django.views.generic.edit.ModelFormMixin.form_valid()` to add the user:\n\n.. code-block:: python\n    :caption: views.py\n\n    from django.contrib.auth.mixins import LoginRequiredMixin\n    from django.views.generic.edit import CreateView\n    from myapp.models import Author\n\n    class AuthorCreate(LoginRequiredMixin, CreateView):\n        model = Author\n        fields = ['name']\n\n        def form_valid(self, form):\n            form.instance.created_by = self.request.user\n            return super().form_valid(form)\n\n:class:`~django.contrib.auth.mixins.LoginRequiredMixin` prevents users who\naren't logged in from accessing the form. If you omit that, you'll need to\nhandle unauthorized users in :meth:`~.ModelFormMixin.form_valid()`.\n\n.. _content-negotiation-example:\n\nContent negotiation example\n===========================\n\nHere is an example showing how you might go about implementing a form that\nworks with an API-based workflow as well as 'normal' form POSTs::\n\n    from django.http import JsonResponse\n    from django.views.generic.edit import CreateView\n    from myapp.models import Author\n\n    class JsonableResponseMixin:\n        \"\"\"\n        Mixin to add JSON support to a form.\n        Must be used with an object-based FormView (e.g. CreateView)\n        \"\"\"\n        def form_invalid(self, form):\n            response = super().form_invalid(form)\n            if self.request.accepts('text/html'):\n                return response\n            else:\n                return JsonResponse(form.errors, status=400)\n\n        def form_valid(self, form):\n            # We make sure to call the parent's form_valid() method because\n            # it might do some processing (in the case of CreateView, it will\n            # call form.save() for example).\n            response = super().form_valid(form)\n            if self.request.accepts('text/html'):\n                return response\n            else:\n                data = {\n                    'pk': self.object.pk,\n                }\n                return JsonResponse(data)\n\n    class AuthorCreate(JsonableResponseMixin, CreateView):\n        model = Author\n        fields = ['name']\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":307,"nodeType":"TextFile","repoName":null,"name":"many_to_many.txt","path":"docs/topics/db/examples","text":"==========================\nMany-to-many relationships\n==========================\n\n.. highlight:: pycon\n\nTo define a many-to-many relationship, use\n:class:`~django.db.models.ManyToManyField`.\n\nIn this example, an ``Article`` can be published in multiple ``Publication``\nobjects, and a ``Publication`` has multiple ``Article`` objects:\n\n.. code-block:: python\n\n    from django.db import models\n\n    class Publication(models.Model):\n        title = models.CharField(max_length=30)\n\n        class Meta:\n            ordering = ['title']\n\n        def __str__(self):\n            return self.title\n\n    class Article(models.Model):\n        headline = models.CharField(max_length=100)\n        publications = models.ManyToManyField(Publication)\n\n        class Meta:\n            ordering = ['headline']\n\n        def __str__(self):\n            return self.headline\n\nWhat follows are examples of operations that can be performed using the Python\nAPI facilities.\n\nCreate a few ``Publications``::\n\n    >>> p1 = Publication(title='The Python Journal')\n    >>> p1.save()\n    >>> p2 = Publication(title='Science News')\n    >>> p2.save()\n    >>> p3 = Publication(title='Science Weekly')\n    >>> p3.save()\n\nCreate an ``Article``::\n\n    >>> a1 = Article(headline='Django lets you build Web apps easily')\n\nYou can't associate it with a ``Publication`` until it's been saved::\n\n    >>> a1.publications.add(p1)\n    Traceback (most recent call last):\n    ...\n    ValueError: \"<Article: Django lets you build Web apps easily>\" needs to have a value for field \"id\" before this many-to-many relationship can be used.\n\nSave it!\n::\n\n    >>> a1.save()\n\nAssociate the ``Article`` with a ``Publication``::\n\n    >>> a1.publications.add(p1)\n\nCreate another ``Article``, and set it to appear in the ``Publications``::\n\n    >>> a2 = Article(headline='NASA uses Python')\n    >>> a2.save()\n    >>> a2.publications.add(p1, p2)\n    >>> a2.publications.add(p3)\n\nAdding a second time is OK, it will not duplicate the relation::\n\n    >>> a2.publications.add(p3)\n\nAdding an object of the wrong type raises :exc:`TypeError`::\n\n    >>> a2.publications.add(a1)\n    Traceback (most recent call last):\n    ...\n    TypeError: 'Publication' instance expected\n\nCreate and add a ``Publication`` to an ``Article`` in one step using\n:meth:`~django.db.models.fields.related.RelatedManager.create`::\n\n    >>> new_publication = a2.publications.create(title='Highlights for Children')\n\n``Article`` objects have access to their related ``Publication`` objects::\n\n    >>> a1.publications.all()\n    <QuerySet [<Publication: The Python Journal>]>\n    >>> a2.publications.all()\n    <QuerySet [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]>\n\n``Publication`` objects have access to their related ``Article`` objects::\n\n    >>> p2.article_set.all()\n    <QuerySet [<Article: NASA uses Python>]>\n    >>> p1.article_set.all()\n    <QuerySet [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]>\n    >>> Publication.objects.get(id=4).article_set.all()\n    <QuerySet [<Article: NASA uses Python>]>\n\nMany-to-many relationships can be queried using :ref:`lookups across\nrelationships <lookups-that-span-relationships>`::\n\n    >>> Article.objects.filter(publications__id=1)\n    <QuerySet [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]>\n    >>> Article.objects.filter(publications__pk=1)\n    <QuerySet [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]>\n    >>> Article.objects.filter(publications=1)\n    <QuerySet [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]>\n    >>> Article.objects.filter(publications=p1)\n    <QuerySet [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]>\n\n    >>> Article.objects.filter(publications__title__startswith=\"Science\")\n    <QuerySet [<Article: NASA uses Python>, <Article: NASA uses Python>]>\n\n    >>> Article.objects.filter(publications__title__startswith=\"Science\").distinct()\n    <QuerySet [<Article: NASA uses Python>]>\n\nThe :meth:`~django.db.models.query.QuerySet.count` function respects\n:meth:`~django.db.models.query.QuerySet.distinct` as well::\n\n    >>> Article.objects.filter(publications__title__startswith=\"Science\").count()\n    2\n\n    >>> Article.objects.filter(publications__title__startswith=\"Science\").distinct().count()\n    1\n\n    >>> Article.objects.filter(publications__in=[1,2]).distinct()\n    <QuerySet [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]>\n    >>> Article.objects.filter(publications__in=[p1,p2]).distinct()\n    <QuerySet [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]>\n\nReverse m2m queries are supported (i.e., starting at the table that doesn't have\na :class:`~django.db.models.ManyToManyField`)::\n\n    >>> Publication.objects.filter(id=1)\n    <QuerySet [<Publication: The Python Journal>]>\n    >>> Publication.objects.filter(pk=1)\n    <QuerySet [<Publication: The Python Journal>]>\n\n    >>> Publication.objects.filter(article__headline__startswith=\"NASA\")\n    <QuerySet [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]>\n\n    >>> Publication.objects.filter(article__id=1)\n    <QuerySet [<Publication: The Python Journal>]>\n    >>> Publication.objects.filter(article__pk=1)\n    <QuerySet [<Publication: The Python Journal>]>\n    >>> Publication.objects.filter(article=1)\n    <QuerySet [<Publication: The Python Journal>]>\n    >>> Publication.objects.filter(article=a1)\n    <QuerySet [<Publication: The Python Journal>]>\n\n    >>> Publication.objects.filter(article__in=[1,2]).distinct()\n    <QuerySet [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]>\n    >>> Publication.objects.filter(article__in=[a1,a2]).distinct()\n    <QuerySet [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]>\n\nExcluding a related item works as you would expect, too (although the SQL\ninvolved is a little complex)::\n\n    >>> Article.objects.exclude(publications=p2)\n    <QuerySet [<Article: Django lets you build Web apps easily>]>\n\nIf we delete a ``Publication``, its ``Articles`` won't be able to access it::\n\n    >>> p1.delete()\n    >>> Publication.objects.all()\n    <QuerySet [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>]>\n    >>> a1 = Article.objects.get(pk=1)\n    >>> a1.publications.all()\n    <QuerySet []>\n\nIf we delete an ``Article``, its ``Publications`` won't be able to access it::\n\n    >>> a2.delete()\n    >>> Article.objects.all()\n    <QuerySet [<Article: Django lets you build Web apps easily>]>\n    >>> p2.article_set.all()\n    <QuerySet []>\n\nAdding via the 'other' end of an m2m::\n\n    >>> a4 = Article(headline='NASA finds intelligent life on Earth')\n    >>> a4.save()\n    >>> p2.article_set.add(a4)\n    >>> p2.article_set.all()\n    <QuerySet [<Article: NASA finds intelligent life on Earth>]>\n    >>> a4.publications.all()\n    <QuerySet [<Publication: Science News>]>\n\nAdding via the other end using keywords::\n\n    >>> new_article = p2.article_set.create(headline='Oxygen-free diet works wonders')\n    >>> p2.article_set.all()\n    <QuerySet [<Article: NASA finds intelligent life on Earth>, <Article: Oxygen-free diet works wonders>]>\n    >>> a5 = p2.article_set.all()[1]\n    >>> a5.publications.all()\n    <QuerySet [<Publication: Science News>]>\n\nRemoving ``Publication`` from an ``Article``::\n\n    >>> a4.publications.remove(p2)\n    >>> p2.article_set.all()\n    <QuerySet [<Article: Oxygen-free diet works wonders>]>\n    >>> a4.publications.all()\n    <QuerySet []>\n\nAnd from the other end::\n\n    >>> p2.article_set.remove(a5)\n    >>> p2.article_set.all()\n    <QuerySet []>\n    >>> a5.publications.all()\n    <QuerySet []>\n\nRelation sets can be set::\n\n    >>> a4.publications.all()\n    <QuerySet [<Publication: Science News>]>\n    >>> a4.publications.set([p3])\n    >>> a4.publications.all()\n    <QuerySet [<Publication: Science Weekly>]>\n\nRelation sets can be cleared::\n\n    >>> p2.article_set.clear()\n    >>> p2.article_set.all()\n    <QuerySet []>\n\nAnd you can clear from the other end::\n\n    >>> p2.article_set.add(a4, a5)\n    >>> p2.article_set.all()\n    <QuerySet [<Article: NASA finds intelligent life on Earth>, <Article: Oxygen-free diet works wonders>]>\n    >>> a4.publications.all()\n    <QuerySet [<Publication: Science News>, <Publication: Science Weekly>]>\n    >>> a4.publications.clear()\n    >>> a4.publications.all()\n    <QuerySet []>\n    >>> p2.article_set.all()\n    <QuerySet [<Article: Oxygen-free diet works wonders>]>\n\nRecreate the ``Article`` and ``Publication`` we have deleted::\n\n    >>> p1 = Publication(title='The Python Journal')\n    >>> p1.save()\n    >>> a2 = Article(headline='NASA uses Python')\n    >>> a2.save()\n    >>> a2.publications.add(p1, p2, p3)\n\nBulk delete some ``Publications`` - references to deleted publications should\ngo::\n\n    >>> Publication.objects.filter(title__startswith='Science').delete()\n    >>> Publication.objects.all()\n    <QuerySet [<Publication: Highlights for Children>, <Publication: The Python Journal>]>\n    >>> Article.objects.all()\n    <QuerySet [<Article: Django lets you build Web apps easily>, <Article: NASA finds intelligent life on Earth>, <Article: NASA uses Python>, <Article: Oxygen-free diet works wonders>]>\n    >>> a2.publications.all()\n    <QuerySet [<Publication: The Python Journal>]>\n\nBulk delete some articles - references to deleted objects should go::\n\n    >>> q = Article.objects.filter(headline__startswith='Django')\n    >>> print(q)\n    <QuerySet [<Article: Django lets you build Web apps easily>]>\n    >>> q.delete()\n\nAfter the :meth:`~django.db.models.query.QuerySet.delete`, the\n:class:`~django.db.models.query.QuerySet` cache needs to be cleared, and the\nreferenced objects should be gone::\n\n    >>> print(q)\n    <QuerySet []>\n    >>> p1.article_set.all()\n    <QuerySet [<Article: NASA uses Python>]>\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":308,"nodeType":"TextFile","repoName":null,"name":"overview.txt","path":"docs/topics/testing","text":"=========================\nWriting and running tests\n=========================\n\n.. module:: django.test\n   :synopsis: Testing tools for Django applications.\n\n.. seealso::\n\n    The :doc:`testing tutorial </intro/tutorial05>`, the :doc:`testing tools\n    reference </topics/testing/tools>`, and the :doc:`advanced testing topics\n    </topics/testing/advanced>`.\n\nThis document is split into two primary sections. First, we explain how to write\ntests with Django. Then, we explain how to run them.\n\nWriting tests\n=============\n\nDjango's unit tests use a Python standard library module: :mod:`unittest`. This\nmodule defines tests using a class-based approach.\n\nHere is an example which subclasses from :class:`django.test.TestCase`,\nwhich is a subclass of :class:`unittest.TestCase` that runs each test inside a\ntransaction to provide isolation::\n\n    from django.test import TestCase\n    from myapp.models import Animal\n\n    class AnimalTestCase(TestCase):\n        def setUp(self):\n            Animal.objects.create(name=\"lion\", sound=\"roar\")\n            Animal.objects.create(name=\"cat\", sound=\"meow\")\n\n        def test_animals_can_speak(self):\n            \"\"\"Animals that can speak are correctly identified\"\"\"\n            lion = Animal.objects.get(name=\"lion\")\n            cat = Animal.objects.get(name=\"cat\")\n            self.assertEqual(lion.speak(), 'The lion says \"roar\"')\n            self.assertEqual(cat.speak(), 'The cat says \"meow\"')\n\nWhen you :ref:`run your tests <running-tests>`, the default behavior of the\ntest utility is to find all the test cases (that is, subclasses of\n:class:`unittest.TestCase`) in any file whose name begins with ``test``,\nautomatically build a test suite out of those test cases, and run that suite.\n\nFor more details about :mod:`unittest`, see the Python documentation.\n\n.. admonition:: Where should the tests live?\n\n    The default :djadmin:`startapp` template creates a ``tests.py`` file in the\n    new application. This might be fine if you only have a few tests, but as\n    your test suite grows you'll likely want to restructure it into a tests\n    package so you can split your tests into different submodules such as\n    ``test_models.py``, ``test_views.py``, ``test_forms.py``, etc. Feel free to\n    pick whatever organizational scheme you like.\n\n    See also :ref:`testing-reusable-applications`.\n\n.. warning::\n\n    If your tests rely on database access such as creating or querying models,\n    be sure to create your test classes as subclasses of\n    :class:`django.test.TestCase` rather than :class:`unittest.TestCase`.\n\n    Using :class:`unittest.TestCase` avoids the cost of running each test in a\n    transaction and flushing the database, but if your tests interact with\n    the database their behavior will vary based on the order that the test\n    runner executes them. This can lead to unit tests that pass when run in\n    isolation but fail when run in a suite.\n\n.. _running-tests:\n\nRunning tests\n=============\n\nOnce you've written tests, run them using the :djadmin:`test` command of\nyour project's ``manage.py`` utility::\n\n    $ ./manage.py test\n\nTest discovery is based on the unittest module's :py:ref:`built-in test\ndiscovery <unittest-test-discovery>`.  By default, this will discover tests in\nany file named \"test*.py\" under the current working directory.\n\nYou can specify particular tests to run by supplying any number of \"test\nlabels\" to ``./manage.py test``. Each test label can be a full Python dotted\npath to a package, module, ``TestCase`` subclass, or test method. For instance::\n\n    # Run all the tests in the animals.tests module\n    $ ./manage.py test animals.tests\n\n    # Run all the tests found within the 'animals' package\n    $ ./manage.py test animals\n\n    # Run just one test case\n    $ ./manage.py test animals.tests.AnimalTestCase\n\n    # Run just one test method\n    $ ./manage.py test animals.tests.AnimalTestCase.test_animals_can_speak\n\nYou can also provide a path to a directory to discover tests below that\ndirectory::\n\n    $ ./manage.py test animals/\n\nYou can specify a custom filename pattern match using the ``-p`` (or\n``--pattern``) option, if your test files are named differently from the\n``test*.py`` pattern::\n\n    $ ./manage.py test --pattern=\"tests_*.py\"\n\nIf you press ``Ctrl-C`` while the tests are running, the test runner will\nwait for the currently running test to complete and then exit gracefully.\nDuring a graceful exit the test runner will output details of any test\nfailures, report on how many tests were run and how many errors and failures\nwere encountered, and destroy any test databases as usual. Thus pressing\n``Ctrl-C`` can be very useful if you forget to pass the :option:`--failfast\n<test --failfast>` option, notice that some tests are unexpectedly failing and\nwant to get details on the failures without waiting for the full test run to\ncomplete.\n\nIf you do not want to wait for the currently running test to finish, you\ncan press ``Ctrl-C`` a second time and the test run will halt immediately,\nbut not gracefully. No details of the tests run before the interruption will\nbe reported, and any test databases created by the run will not be destroyed.\n\n.. admonition:: Test with warnings enabled\n\n    It's a good idea to run your tests with Python warnings enabled:\n    ``python -Wa manage.py test``. The ``-Wa`` flag tells Python to\n    display deprecation warnings. Django, like many other Python libraries,\n    uses these warnings to flag when features are going away. It also might\n    flag areas in your code that aren't strictly wrong but could benefit\n    from a better implementation.\n\n\n.. _the-test-database:\n\nThe test database\n-----------------\n\nTests that require a database (namely, model tests) will not use your \"real\"\n(production) database. Separate, blank databases are created for the tests.\n\nRegardless of whether the tests pass or fail, the test databases are destroyed\nwhen all the tests have been executed.\n\nYou can prevent the test databases from being destroyed by using the\n:option:`test --keepdb` option. This will preserve the test database between\nruns. If the database does not exist, it will first be created. Any migrations\nwill also be applied in order to keep it up to date.\n\nAs described in the previous section, if a test run is forcefully interrupted,\nthe test database may not be destroyed. On the next run, you'll be asked\nwhether you want to reuse or destroy the database. Use the :option:`test\n--noinput` option to suppress that prompt and automatically destroy the\ndatabase. This can be useful when running tests on a continuous integration\nserver where tests may be interrupted by a timeout, for example.\n\nThe default test database names are created by prepending ``test_`` to the\nvalue of each :setting:`NAME` in :setting:`DATABASES`. When using SQLite, the\ntests will use an in-memory database by default (i.e., the database will be\ncreated in memory, bypassing the filesystem entirely!). The :setting:`TEST\n<DATABASE-TEST>` dictionary in :setting:`DATABASES` offers a number of settings\nto configure your test database. For example, if you want to use a different\ndatabase name, specify :setting:`NAME <TEST_NAME>` in the :setting:`TEST\n<DATABASE-TEST>` dictionary for any given database in :setting:`DATABASES`.\n\nOn PostgreSQL, :setting:`USER` will also need read access to the built-in\n``postgres`` database.\n\nAside from using a separate database, the test runner will otherwise\nuse all of the same database settings you have in your settings file:\n:setting:`ENGINE <DATABASE-ENGINE>`, :setting:`USER`, :setting:`HOST`, etc. The\ntest database is created by the user specified by :setting:`USER`, so you'll\nneed to make sure that the given user account has sufficient privileges to\ncreate a new database on the system.\n\nFor fine-grained control over the character encoding of your test\ndatabase, use the :setting:`CHARSET <TEST_CHARSET>` TEST option. If you're using\nMySQL, you can also use the :setting:`COLLATION <TEST_COLLATION>` option to\ncontrol the particular collation used by the test database. See the\n:doc:`settings documentation </ref/settings>` for details of these\nand other advanced settings.\n\nIf using an SQLite in-memory database with SQLite, `shared cache\n<https://www.sqlite.org/sharedcache.html>`_ is enabled, so you can write tests\nwith ability to share the database between threads.\n\n.. admonition:: Finding data from your production database when running tests?\n\n    If your code attempts to access the database when its modules are compiled,\n    this will occur *before* the test database is set up, with potentially\n    unexpected results. For example, if you have a database query in\n    module-level code and a real database exists, production data could pollute\n    your tests. *It is a bad idea to have such import-time database queries in\n    your code* anyway - rewrite your code so that it doesn't do this.\n\n    This also applies to customized implementations of\n    :meth:`~django.apps.AppConfig.ready()`.\n\n.. seealso::\n\n    The :ref:`advanced multi-db testing topics <topics-testing-advanced-multidb>`.\n\n.. _order-of-tests:\n\nOrder in which tests are executed\n---------------------------------\n\nIn order to guarantee that all ``TestCase`` code starts with a clean database,\nthe Django test runner reorders tests in the following way:\n\n* All :class:`~django.test.TestCase` subclasses are run first.\n\n* Then, all other Django-based tests (test cases based on\n  :class:`~django.test.SimpleTestCase`, including\n  :class:`~django.test.TransactionTestCase`) are run with no particular\n  ordering guaranteed nor enforced among them.\n\n* Then any other :class:`unittest.TestCase` tests (including doctests) that may\n  alter the database without restoring it to its original state are run.\n\n.. note::\n\n    The new ordering of tests may reveal unexpected dependencies on test case\n    ordering. This is the case with doctests that relied on state left in the\n    database by a given :class:`~django.test.TransactionTestCase` test, they\n    must be updated to be able to run independently.\n\nYou may reverse the execution order inside groups using the :option:`test\n--reverse` option. This can help with ensuring your tests are independent from\neach other.\n\n.. _test-case-serialized-rollback:\n\nRollback emulation\n------------------\n\nAny initial data loaded in migrations will only be available in ``TestCase``\ntests and not in ``TransactionTestCase`` tests, and additionally only on\nbackends where transactions are supported (the most important exception being\nMyISAM). This is also true for tests which rely on ``TransactionTestCase``\nsuch as :class:`LiveServerTestCase` and\n:class:`~django.contrib.staticfiles.testing.StaticLiveServerTestCase`.\n\nDjango can reload that data for you on a per-testcase basis by\nsetting the ``serialized_rollback`` option to ``True`` in the body of the\n``TestCase`` or ``TransactionTestCase``, but note that this will slow down\nthat test suite by approximately 3x.\n\nThird-party apps or those developing against MyISAM will need to set this;\nin general, however, you should be developing your own projects against a\ntransactional database and be using ``TestCase`` for most tests, and thus\nnot need this setting.\n\nThe initial serialization is usually very quick, but if you wish to exclude\nsome apps from this process (and speed up test runs slightly), you may add\nthose apps to :setting:`TEST_NON_SERIALIZED_APPS`.\n\nTo prevent serialized data from being loaded twice, setting\n``serialized_rollback=True`` disables the\n:data:`~django.db.models.signals.post_migrate` signal when flushing the test\ndatabase.\n\nOther test conditions\n---------------------\n\nRegardless of the value of the :setting:`DEBUG` setting in your configuration\nfile, all Django tests run with :setting:`DEBUG`\\=False. This is to ensure that\nthe observed output of your code matches what will be seen in a production\nsetting.\n\nCaches are not cleared after each test, and running \"manage.py test fooapp\" can\ninsert data from the tests into the cache of a live system if you run your\ntests in production because, unlike databases, a separate \"test cache\" is not\nused. This behavior :ticket:`may change <11505>` in the future.\n\nUnderstanding the test output\n-----------------------------\n\nWhen you run your tests, you'll see a number of messages as the test runner\nprepares itself. You can control the level of detail of these messages with the\n``verbosity`` option on the command line::\n\n    Creating test database...\n    Creating table myapp_animal\n    Creating table myapp_mineral\n\nThis tells you that the test runner is creating a test database, as described\nin the previous section.\n\nOnce the test database has been created, Django will run your tests.\nIf everything goes well, you'll see something like this::\n\n    ----------------------------------------------------------------------\n    Ran 22 tests in 0.221s\n\n    OK\n\nIf there are test failures, however, you'll see full details about which tests\nfailed::\n\n    ======================================================================\n    FAIL: test_was_published_recently_with_future_poll (polls.tests.PollMethodTests)\n    ----------------------------------------------------------------------\n    Traceback (most recent call last):\n      File \"/dev/mysite/polls/tests.py\", line 16, in test_was_published_recently_with_future_poll\n        self.assertIs(future_poll.was_published_recently(), False)\n    AssertionError: True is not False\n\n    ----------------------------------------------------------------------\n    Ran 1 test in 0.003s\n\n    FAILED (failures=1)\n\nA full explanation of this error output is beyond the scope of this document,\nbut it's pretty intuitive. You can consult the documentation of Python's\n:mod:`unittest` library for details.\n\nNote that the return code for the test-runner script is 1 for any number of\nfailed and erroneous tests. If all the tests pass, the return code is 0. This\nfeature is useful if you're using the test-runner script in a shell script and\nneed to test for success or failure at that level.\n\n.. _speeding-up-tests-auth-hashers:\n\nSpeeding up the tests\n---------------------\n\nRunning tests in parallel\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\nAs long as your tests are properly isolated, you can run them in parallel to\ngain a speed up on multi-core hardware. See :option:`test --parallel`.\n\nPassword hashing\n~~~~~~~~~~~~~~~~\n\nThe default password hasher is rather slow by design. If you're authenticating\nmany users in your tests, you may want to use a custom settings file and set\nthe :setting:`PASSWORD_HASHERS` setting to a faster hashing algorithm::\n\n    PASSWORD_HASHERS = [\n        'django.contrib.auth.hashers.MD5PasswordHasher',\n    ]\n\nDon't forget to also include in :setting:`PASSWORD_HASHERS` any hashing\nalgorithm used in fixtures, if any.\n\nPreserving the test database\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe :option:`test --keepdb` option preserves the test database between test\nruns. It skips the create and destroy actions which can greatly decrease the\ntime to run tests.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":309,"nodeType":"TextFile","repoName":null,"name":"passwords.txt","path":"docs/topics/auth","text":"=============================\nPassword management in Django\n=============================\n\nPassword management is something that should generally not be reinvented\nunnecessarily, and Django endeavors to provide a secure and flexible set of\ntools for managing user passwords. This document describes how Django stores\npasswords, how the storage hashing can be configured, and some utilities to\nwork with hashed passwords.\n\n.. seealso::\n\n    Even though users may use strong passwords, attackers might be able to\n    eavesdrop on their connections. Use :ref:`HTTPS\n    <security-recommendation-ssl>` to avoid sending passwords (or any other\n    sensitive data) over plain HTTP connections because they will be vulnerable\n    to password sniffing.\n\n.. _auth_password_storage:\n\nHow Django stores passwords\n===========================\n\nDjango provides a flexible password storage system and uses PBKDF2 by default.\n\nThe :attr:`~django.contrib.auth.models.User.password` attribute of a\n:class:`~django.contrib.auth.models.User` object is a string in this format::\n\n    <algorithm>$<iterations>$<salt>$<hash>\n\nThose are the components used for storing a User's password, separated by the\ndollar-sign character and consist of: the hashing algorithm, the number of\nalgorithm iterations (work factor), the random salt, and the resulting password\nhash.  The algorithm is one of a number of one-way hashing or password storage\nalgorithms Django can use; see below. Iterations describe the number of times\nthe algorithm is run over the hash. Salt is the random seed used and the hash\nis the result of the one-way function.\n\nBy default, Django uses the PBKDF2_ algorithm with a SHA256 hash, a\npassword stretching mechanism recommended by NIST_. This should be\nsufficient for most users: it's quite secure, requiring massive\namounts of computing time to break.\n\nHowever, depending on your requirements, you may choose a different\nalgorithm, or even use a custom algorithm to match your specific\nsecurity situation. Again, most users shouldn't need to do this -- if\nyou're not sure, you probably don't.  If you do, please read on:\n\nDjango chooses the algorithm to use by consulting the\n:setting:`PASSWORD_HASHERS` setting. This is a list of hashing algorithm\nclasses that this Django installation supports. The first entry in this list\n(that is, ``settings.PASSWORD_HASHERS[0]``) will be used to store passwords,\nand all the other entries are valid hashers that can be used to check existing\npasswords.  This means that if you want to use a different algorithm, you'll\nneed to modify :setting:`PASSWORD_HASHERS` to list your preferred algorithm\nfirst in the list.\n\nThe default for :setting:`PASSWORD_HASHERS` is::\n\n    PASSWORD_HASHERS = [\n        'django.contrib.auth.hashers.PBKDF2PasswordHasher',\n        'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',\n        'django.contrib.auth.hashers.Argon2PasswordHasher',\n        'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',\n    ]\n\nThis means that Django will use PBKDF2_ to store all passwords but will support\nchecking passwords stored with PBKDF2SHA1, argon2_, and bcrypt_.\n\nThe next few sections describe a couple of common ways advanced users may want\nto modify this setting.\n\n.. _argon2_usage:\n\nUsing Argon2 with Django\n------------------------\n\nArgon2_ is the winner of the 2015 `Password Hashing Competition`_, a community\norganized open competition to select a next generation hashing algorithm. It's\ndesigned not to be easier to compute on custom hardware than it is to compute\non an ordinary CPU.\n\nArgon2_ is not the default for Django because it requires a third-party\nlibrary. The Password Hashing Competition panel, however, recommends immediate\nuse of Argon2 rather than the other algorithms supported by Django.\n\nTo use Argon2 as your default storage algorithm, do the following:\n\n#. Install the `argon2-cffi library`_.  This can be done by running\n   ``python -m pip install django[argon2]``, which is equivalent to\n   ``python -m pip install argon2-cffi`` (along with any version requirement\n   from Django's ``setup.cfg``).\n\n#. Modify :setting:`PASSWORD_HASHERS` to list ``Argon2PasswordHasher`` first.\n   That is, in your settings file, you'd put::\n\n        PASSWORD_HASHERS = [\n            'django.contrib.auth.hashers.Argon2PasswordHasher',\n            'django.contrib.auth.hashers.PBKDF2PasswordHasher',\n            'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',\n            'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',\n        ]\n\n   Keep and/or add any entries in this list if you need Django to :ref:`upgrade\n   passwords <password-upgrades>`.\n\n.. _bcrypt_usage:\n\nUsing ``bcrypt`` with Django\n----------------------------\n\nBcrypt_ is a popular password storage algorithm that's specifically designed\nfor long-term password storage. It's not the default used by Django since it\nrequires the use of third-party libraries, but since many people may want to\nuse it Django supports bcrypt with minimal effort.\n\nTo use Bcrypt as your default storage algorithm, do the following:\n\n#. Install the `bcrypt library`_. This can be done by running\n   ``python -m pip install django[bcrypt]``, which is equivalent to\n   ``python -m pip install bcrypt`` (along with any version requirement from\n   Django's ``setup.cfg``).\n\n#. Modify :setting:`PASSWORD_HASHERS` to list ``BCryptSHA256PasswordHasher``\n   first. That is, in your settings file, you'd put::\n\n        PASSWORD_HASHERS = [\n            'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',\n            'django.contrib.auth.hashers.PBKDF2PasswordHasher',\n            'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',\n            'django.contrib.auth.hashers.Argon2PasswordHasher',\n        ]\n\n   Keep and/or add any entries in this list if you need Django to :ref:`upgrade\n   passwords <password-upgrades>`.\n\nThat's it -- now your Django install will use Bcrypt as the default storage\nalgorithm.\n\n.. _increasing-password-algorithm-work-factor:\n\nIncreasing the work factor\n--------------------------\n\nPBKDF2 and bcrypt\n~~~~~~~~~~~~~~~~~\n\nThe PBKDF2 and bcrypt algorithms use a number of iterations or rounds of\nhashing. This deliberately slows down attackers, making attacks against hashed\npasswords harder. However, as computing power increases, the number of\niterations needs to be increased. We've chosen a reasonable default (and will\nincrease it with each release of Django), but you may wish to tune it up or\ndown, depending on your security needs and available processing power. To do so,\nyou'll subclass the appropriate algorithm and override the ``iterations``\nparameters. For example, to increase the number of iterations used by the\ndefault PBKDF2 algorithm:\n\n#. Create a subclass of ``django.contrib.auth.hashers.PBKDF2PasswordHasher``::\n\n        from django.contrib.auth.hashers import PBKDF2PasswordHasher\n\n        class MyPBKDF2PasswordHasher(PBKDF2PasswordHasher):\n            \"\"\"\n            A subclass of PBKDF2PasswordHasher that uses 100 times more iterations.\n            \"\"\"\n            iterations = PBKDF2PasswordHasher.iterations * 100\n\n   Save this somewhere in your project. For example, you might put this in\n   a file like ``myproject/hashers.py``.\n\n#. Add your new hasher as the first entry in :setting:`PASSWORD_HASHERS`::\n\n        PASSWORD_HASHERS = [\n            'myproject.hashers.MyPBKDF2PasswordHasher',\n            'django.contrib.auth.hashers.PBKDF2PasswordHasher',\n            'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',\n            'django.contrib.auth.hashers.Argon2PasswordHasher',\n            'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',\n        ]\n\nThat's it -- now your Django install will use more iterations when it\nstores passwords using PBKDF2.\n\nArgon2\n~~~~~~\n\nArgon2 has three attributes that can be customized:\n\n#. ``time_cost`` controls the number of iterations within the hash.\n#. ``memory_cost`` controls the size of memory that must be used during the\n   computation of the hash.\n#. ``parallelism`` controls how many CPUs the computation of the hash can be\n   parallelized on.\n\nThe default values of these attributes are probably fine for you. If you\ndetermine that the password hash is too fast or too slow, you can tweak it as\nfollows:\n\n#. Choose ``parallelism`` to be the number of threads you can\n   spare computing the hash.\n#. Choose ``memory_cost`` to be the KiB of memory you can spare.\n#. Adjust ``time_cost`` and measure the time hashing a password takes.\n   Pick a ``time_cost`` that takes an acceptable time for you.\n   If ``time_cost`` set to 1 is unacceptably slow, lower ``memory_cost``.\n\n.. admonition:: ``memory_cost`` interpretation\n\n    The argon2 command-line utility and some other libraries interpret the\n    ``memory_cost`` parameter differently from the value that Django uses. The\n    conversion is given by ``memory_cost == 2 ** memory_cost_commandline``.\n\n.. _password-upgrades:\n\nPassword upgrading\n------------------\n\nWhen users log in, if their passwords are stored with anything other than\nthe preferred algorithm, Django will automatically upgrade the algorithm\nto the preferred one. This means that old installs of Django will get\nautomatically more secure as users log in, and it also means that you\ncan switch to new (and better) storage algorithms as they get invented.\n\nHowever, Django can only upgrade passwords that use algorithms mentioned in\n:setting:`PASSWORD_HASHERS`, so as you upgrade to new systems you should make\nsure never to *remove* entries from this list. If you do, users using\nunmentioned algorithms won't be able to upgrade. Hashed passwords will be\nupdated when increasing (or decreasing) the number of PBKDF2 iterations or\nbcrypt rounds.\n\nBe aware that if all the passwords in your database aren't encoded in the\ndefault hasher's algorithm, you may be vulnerable to a user enumeration timing\nattack due to a difference between the duration of a login request for a user\nwith a password encoded in a non-default algorithm and the duration of a login\nrequest for a nonexistent user (which runs the default hasher). You may be able\nto mitigate this by :ref:`upgrading older password hashes\n<wrapping-password-hashers>`.\n\n.. _wrapping-password-hashers:\n\nPassword upgrading without requiring a login\n--------------------------------------------\n\nIf you have an existing database with an older, weak hash such as MD5 or SHA1,\nyou might want to upgrade those hashes yourself instead of waiting for the\nupgrade to happen when a user logs in (which may never happen if a user doesn't\nreturn to your site). In this case, you can use a \"wrapped\" password hasher.\n\nFor this example, we'll migrate a collection of SHA1 hashes to use\nPBKDF2(SHA1(password)) and add the corresponding password hasher for checking\nif a user entered the correct password on login. We assume we're using the\nbuilt-in ``User`` model and that our project has an ``accounts`` app. You can\nmodify the pattern to work with any algorithm or with a custom user model.\n\nFirst, we'll add the custom hasher:\n\n.. code-block:: python\n    :caption: accounts/hashers.py\n\n    from django.contrib.auth.hashers import (\n        PBKDF2PasswordHasher, SHA1PasswordHasher,\n    )\n\n\n    class PBKDF2WrappedSHA1PasswordHasher(PBKDF2PasswordHasher):\n        algorithm = 'pbkdf2_wrapped_sha1'\n\n        def encode_sha1_hash(self, sha1_hash, salt, iterations=None):\n            return super().encode(sha1_hash, salt, iterations)\n\n        def encode(self, password, salt, iterations=None):\n            _, _, sha1_hash = SHA1PasswordHasher().encode(password, salt).split('$', 2)\n            return self.encode_sha1_hash(sha1_hash, salt, iterations)\n\nThe data migration might look something like:\n\n.. code-block:: python\n    :caption: accounts/migrations/0002_migrate_sha1_passwords.py\n\n    from django.db import migrations\n\n    from ..hashers import PBKDF2WrappedSHA1PasswordHasher\n\n\n    def forwards_func(apps, schema_editor):\n        User = apps.get_model('auth', 'User')\n        users = User.objects.filter(password__startswith='sha1$')\n        hasher = PBKDF2WrappedSHA1PasswordHasher()\n        for user in users:\n            algorithm, salt, sha1_hash = user.password.split('$', 2)\n            user.password = hasher.encode_sha1_hash(sha1_hash, salt)\n            user.save(update_fields=['password'])\n\n\n    class Migration(migrations.Migration):\n\n        dependencies = [\n            ('accounts', '0001_initial'),\n            # replace this with the latest migration in contrib.auth\n            ('auth', '####_migration_name'),\n        ]\n\n        operations = [\n            migrations.RunPython(forwards_func),\n        ]\n\nBe aware that this migration will take on the order of several minutes for\nseveral thousand users, depending on the speed of your hardware.\n\nFinally, we'll add a :setting:`PASSWORD_HASHERS` setting:\n\n.. code-block:: python\n    :caption: mysite/settings.py\n\n    PASSWORD_HASHERS = [\n        'django.contrib.auth.hashers.PBKDF2PasswordHasher',\n        'accounts.hashers.PBKDF2WrappedSHA1PasswordHasher',\n    ]\n\nInclude any other hashers that your site uses in this list.\n\n.. _sha1: https://en.wikipedia.org/wiki/SHA1\n.. _pbkdf2: https://en.wikipedia.org/wiki/PBKDF2\n.. _nist: https://dx.doi.org/10.6028/NIST.SP.800-132\n.. _bcrypt: https://en.wikipedia.org/wiki/Bcrypt\n.. _`bcrypt library`: https://pypi.org/project/bcrypt/\n.. _`argon2-cffi library`: https://pypi.org/project/argon2_cffi/\n.. _argon2: https://en.wikipedia.org/wiki/Argon2\n.. _`Password Hashing Competition`: https://password-hashing.net\n\n.. _auth-included-hashers:\n\nIncluded hashers\n----------------\n\nThe full list of hashers included in Django is::\n\n    [\n        'django.contrib.auth.hashers.PBKDF2PasswordHasher',\n        'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',\n        'django.contrib.auth.hashers.Argon2PasswordHasher',\n        'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',\n        'django.contrib.auth.hashers.BCryptPasswordHasher',\n        'django.contrib.auth.hashers.SHA1PasswordHasher',\n        'django.contrib.auth.hashers.MD5PasswordHasher',\n        'django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher',\n        'django.contrib.auth.hashers.UnsaltedMD5PasswordHasher',\n        'django.contrib.auth.hashers.CryptPasswordHasher',\n    ]\n\nThe corresponding algorithm names are:\n\n* ``pbkdf2_sha256``\n* ``pbkdf2_sha1``\n* ``argon2``\n* ``bcrypt_sha256``\n* ``bcrypt``\n* ``sha1``\n* ``md5``\n* ``unsalted_sha1``\n* ``unsalted_md5``\n* ``crypt``\n\n.. _write-your-own-password-hasher:\n\nWriting your own hasher\n-----------------------\n\nIf you write your own password hasher that contains a work factor such as a\nnumber of iterations, you should implement a\n``harden_runtime(self, password, encoded)`` method to bridge the runtime gap\nbetween the work factor supplied in the ``encoded`` password and the default\nwork factor of the hasher. This prevents a user enumeration timing attack due\nto  difference between a login request for a user with a password encoded in an\nolder number of iterations and a nonexistent user (which runs the default\nhasher's default number of iterations).\n\nTaking PBKDF2 as example, if ``encoded`` contains 20,000 iterations and the\nhasher's default ``iterations`` is 30,000, the method should run ``password``\nthrough another 10,000 iterations of PBKDF2.\n\nIf your hasher doesn't have a work factor, implement the method as a no-op\n(``pass``).\n\nManually managing a user's password\n===================================\n\n.. module:: django.contrib.auth.hashers\n\nThe :mod:`django.contrib.auth.hashers` module provides a set of functions\nto create and validate hashed passwords. You can use them independently\nfrom the ``User`` model.\n\n.. function:: check_password(password, encoded)\n\n    If you'd like to manually authenticate a user by comparing a plain-text\n    password to the hashed password in the database, use the convenience\n    function :func:`check_password`. It takes two arguments: the plain-text\n    password to check, and the full value of a user's ``password`` field in the\n    database to check against, and returns ``True`` if they match, ``False``\n    otherwise.\n\n.. function:: make_password(password, salt=None, hasher='default')\n\n    Creates a hashed password in the format used by this application. It takes\n    one mandatory argument: the password in plain-text (string or bytes).\n    Optionally, you can provide a salt and a hashing algorithm to use, if you\n    don't want to use the defaults (first entry of ``PASSWORD_HASHERS``\n    setting). See :ref:`auth-included-hashers` for the algorithm name of each\n    hasher. If the password argument is ``None``, an unusable password is\n    returned (one that will never be accepted by :func:`check_password`).\n\n    .. versionchanged:: 3.1\n\n        The ``password`` parameter must be a string or bytes if not ``None``.\n\n.. function:: is_password_usable(encoded_password)\n\n    Returns ``False`` if the password is a result of\n    :meth:`.User.set_unusable_password`.\n\n.. _password-validation:\n\nPassword validation\n===================\n\n.. module:: django.contrib.auth.password_validation\n\nUsers often choose poor passwords. To help mitigate this problem, Django\noffers pluggable password validation. You can configure multiple password\nvalidators at the same time. A few validators are included in Django, but you\ncan write your own as well.\n\nEach password validator must provide a help text to explain the requirements to\nthe user, validate a given password and return an error message if it does not\nmeet the requirements, and optionally receive passwords that have been set.\nValidators can also have optional settings to fine tune their behavior.\n\nValidation is controlled by the :setting:`AUTH_PASSWORD_VALIDATORS` setting.\nThe default for the setting is an empty list, which means no validators are\napplied. In new projects created with the default :djadmin:`startproject`\ntemplate, a set of validators is enabled by default.\n\nBy default, validators are used in the forms to reset or change passwords and\nin the :djadmin:`createsuperuser` and :djadmin:`changepassword` management\ncommands. Validators aren't applied at the model level, for example in\n``User.objects.create_user()`` and ``create_superuser()``, because we assume\nthat developers, not users, interact with Django at that level and also because\nmodel validation doesn't automatically run as part of creating models.\n\n.. note::\n\n    Password validation can prevent the use of many types of weak passwords.\n    However, the fact that a password passes all the validators doesn't\n    guarantee that it is a strong password. There are many factors that can\n    weaken a password that are not detectable by even the most advanced\n    password validators.\n\nEnabling password validation\n----------------------------\n\nPassword validation is configured in the\n:setting:`AUTH_PASSWORD_VALIDATORS` setting::\n\n    AUTH_PASSWORD_VALIDATORS = [\n        {\n            'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n        },\n        {\n            'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n            'OPTIONS': {\n                'min_length': 9,\n            }\n        },\n        {\n            'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n        },\n        {\n            'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n        },\n    ]\n\nThis example enables all four included validators:\n\n* ``UserAttributeSimilarityValidator``, which checks the similarity between\n  the password and a set of attributes of the user.\n* ``MinimumLengthValidator``, which checks whether the password meets a minimum\n  length. This validator is configured with a custom option: it now requires\n  the minimum length to be nine characters, instead of the default eight.\n* ``CommonPasswordValidator``, which checks whether the password occurs in a\n  list of common passwords. By default, it compares to an included list of\n  20,000 common passwords.\n* ``NumericPasswordValidator``, which checks whether the password isn't\n  entirely numeric.\n\nFor ``UserAttributeSimilarityValidator`` and ``CommonPasswordValidator``,\nwe're using the default settings in this example. ``NumericPasswordValidator``\nhas no settings.\n\nThe help texts and any errors from password validators are always returned in\nthe order they are listed in :setting:`AUTH_PASSWORD_VALIDATORS`.\n\nIncluded validators\n-------------------\n\nDjango includes four validators:\n\n.. class:: MinimumLengthValidator(min_length=8)\n\n    Validates whether the password meets a minimum length.\n    The minimum length can be customized with the ``min_length`` parameter.\n\n.. class:: UserAttributeSimilarityValidator(user_attributes=DEFAULT_USER_ATTRIBUTES, max_similarity=0.7)\n\n    Validates whether the password is sufficiently different from certain\n    attributes of the user.\n\n    The ``user_attributes`` parameter should be an iterable of names of user\n    attributes to compare to. If this argument is not provided, the default\n    is used: ``'username', 'first_name', 'last_name', 'email'``.\n    Attributes that don't exist are ignored.\n\n    The minimum similarity of a rejected password can be set on a scale of 0 to\n    1 with the ``max_similarity`` parameter. A setting of 0 rejects all\n    passwords, whereas a setting of 1 rejects only passwords that are identical\n    to an attribute's value.\n\n.. class:: CommonPasswordValidator(password_list_path=DEFAULT_PASSWORD_LIST_PATH)\n\n    Validates whether the password is not a common password. This converts the\n    password to lowercase (to do a case-insensitive comparison) and checks it\n    against a list of 20,000 common password created by `Royce Williams\n    <https://gist.github.com/roycewilliams/281ce539915a947a23db17137d91aeb7>`_.\n\n    The ``password_list_path`` can be set to the path of a custom file of\n    common passwords. This file should contain one lowercase password per line\n    and may be plain text or gzipped.\n\n.. class:: NumericPasswordValidator()\n\n    Validates whether the password is not entirely numeric.\n\nIntegrating validation\n----------------------\n\nThere are a few functions in ``django.contrib.auth.password_validation`` that\nyou can call from your own forms or other code to integrate password\nvalidation. This can be useful if you use custom forms for password setting,\nor if you have API calls that allow passwords to be set, for example.\n\n.. function:: validate_password(password, user=None, password_validators=None)\n\n    Validates a password. If all validators find the password valid, returns\n    ``None``. If one or more validators reject the password, raises a\n    :exc:`~django.core.exceptions.ValidationError` with all the error messages\n    from the validators.\n\n    The ``user`` object is optional: if it's not provided, some validators may\n    not be able to perform any validation and will accept any password.\n\n.. function:: password_changed(password, user=None, password_validators=None)\n\n    Informs all validators that the password has been changed. This can be used\n    by validators such as one that prevents password reuse. This should be\n    called once the password has been successfully changed.\n\n    For subclasses of :class:`~django.contrib.auth.models.AbstractBaseUser`,\n    the password field will be marked as \"dirty\" when calling\n    :meth:`~django.contrib.auth.models.AbstractBaseUser.set_password` which\n    triggers a call to ``password_changed()`` after the user is saved.\n\n.. function:: password_validators_help_texts(password_validators=None)\n\n    Returns a list of the help texts of all validators. These explain the\n    password requirements to the user.\n\n.. function:: password_validators_help_text_html(password_validators=None)\n\n    Returns an HTML string with all help texts in an ``<ul>``. This is\n    helpful when adding password validation to forms, as you can pass the\n    output directly to the ``help_text`` parameter of a form field.\n\n.. function:: get_password_validators(validator_config)\n\n    Returns a set of validator objects based on the ``validator_config``\n    parameter. By default, all functions use the validators defined in\n    :setting:`AUTH_PASSWORD_VALIDATORS`, but by calling this function with an\n    alternate set of validators and then passing the result into the\n    ``password_validators`` parameter of the other functions, your custom set\n    of validators will be used instead. This is useful when you have a typical\n    set of validators to use for most scenarios, but also have a special\n    situation that requires a custom set. If you always use the same set\n    of validators, there is no need to use this function, as the configuration\n    from :setting:`AUTH_PASSWORD_VALIDATORS` is used by default.\n\n    The structure of ``validator_config`` is identical to the\n    structure of :setting:`AUTH_PASSWORD_VALIDATORS`. The return value of\n    this function can be passed into the ``password_validators`` parameter\n    of the functions listed above.\n\nNote that where the password is passed to one of these functions, this should\nalways be the clear text password - not a hashed password.\n\nWriting your own validator\n--------------------------\n\nIf Django's built-in validators are not sufficient, you can write your own\npassword validators. Validators have a fairly small interface. They must\nimplement two methods:\n\n* ``validate(self, password, user=None)``: validate a password. Return\n  ``None`` if the password is valid, or raise a\n  :exc:`~django.core.exceptions.ValidationError` with an error message if the\n  password is not valid. You must be able to deal with ``user`` being\n  ``None`` - if that means your validator can't run, return ``None`` for no\n  error.\n* ``get_help_text()``: provide a help text to explain the requirements to\n  the user.\n\nAny items in the ``OPTIONS`` in :setting:`AUTH_PASSWORD_VALIDATORS` for your\nvalidator will be passed to the constructor. All constructor arguments should\nhave a default value.\n\nHere's a basic example of a validator, with one optional setting::\n\n    from django.core.exceptions import ValidationError\n    from django.utils.translation import gettext as _\n\n    class MinimumLengthValidator:\n        def __init__(self, min_length=8):\n            self.min_length = min_length\n\n        def validate(self, password, user=None):\n            if len(password) < self.min_length:\n                raise ValidationError(\n                    _(\"This password must contain at least %(min_length)d characters.\"),\n                    code='password_too_short',\n                    params={'min_length': self.min_length},\n                )\n\n        def get_help_text(self):\n            return _(\n                \"Your password must contain at least %(min_length)d characters.\"\n                % {'min_length': self.min_length}\n            )\n\nYou can also implement ``password_changed(password, user=None``), which will\nbe called after a successful password change. That can be used to prevent\npassword reuse, for example. However, if you decide to store a user's previous\npasswords, you should never do so in clear text.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":310,"nodeType":"TextFile","repoName":null,"name":"sessions.txt","path":"docs/topics/http","text":"===================\nHow to use sessions\n===================\n\n.. module:: django.contrib.sessions\n   :synopsis: Provides session management for Django projects.\n\nDjango provides full support for anonymous sessions. The session framework\nlets you store and retrieve arbitrary data on a per-site-visitor basis. It\nstores data on the server side and abstracts the sending and receiving of\ncookies. Cookies contain a session ID -- not the data itself (unless you're\nusing the :ref:`cookie based backend<cookie-session-backend>`).\n\nEnabling sessions\n=================\n\nSessions are implemented via a piece of :doc:`middleware </ref/middleware>`.\n\nTo enable session functionality, do the following:\n\n* Edit the :setting:`MIDDLEWARE` setting and make sure it contains\n  ``'django.contrib.sessions.middleware.SessionMiddleware'``. The default\n  ``settings.py`` created by ``django-admin startproject`` has\n  ``SessionMiddleware`` activated.\n\nIf you don't want to use sessions, you might as well remove the\n``SessionMiddleware`` line from :setting:`MIDDLEWARE` and\n``'django.contrib.sessions'`` from your :setting:`INSTALLED_APPS`.\nIt'll save you a small bit of overhead.\n\n.. _configuring-sessions:\n\nConfiguring the session engine\n==============================\n\nBy default, Django stores sessions in your database (using the model\n``django.contrib.sessions.models.Session``). Though this is convenient, in\nsome setups it's faster to store session data elsewhere, so Django can be\nconfigured to store session data on your filesystem or in your cache.\n\nUsing database-backed sessions\n------------------------------\n\nIf you want to use a database-backed session, you need to add\n``'django.contrib.sessions'`` to your :setting:`INSTALLED_APPS` setting.\n\nOnce you have configured your installation, run ``manage.py migrate``\nto install the single database table that stores session data.\n\n.. _cached-sessions-backend:\n\nUsing cached sessions\n---------------------\n\nFor better performance, you may want to use a cache-based session backend.\n\nTo store session data using Django's cache system, you'll first need to make\nsure you've configured your cache; see the :doc:`cache documentation\n</topics/cache>` for details.\n\n.. warning::\n\n    You should only use cache-based sessions if you're using the Memcached\n    cache backend. The local-memory cache backend doesn't retain data long\n    enough to be a good choice, and it'll be faster to use file or database\n    sessions directly instead of sending everything through the file or\n    database cache backends. Additionally, the local-memory cache backend is\n    NOT multi-process safe, therefore probably not a good choice for production\n    environments.\n\nIf you have multiple caches defined in :setting:`CACHES`, Django will use the\ndefault cache. To use another cache, set :setting:`SESSION_CACHE_ALIAS` to the\nname of that cache.\n\nOnce your cache is configured, you've got two choices for how to store data in\nthe cache:\n\n* Set :setting:`SESSION_ENGINE` to\n  ``\"django.contrib.sessions.backends.cache\"`` for a simple caching session\n  store. Session data will be stored directly in your cache. However, session\n  data may not be persistent: cached data can be evicted if the cache fills\n  up or if the cache server is restarted.\n\n* For persistent, cached data, set :setting:`SESSION_ENGINE` to\n  ``\"django.contrib.sessions.backends.cached_db\"``. This uses a\n  write-through cache -- every write to the cache will also be written to\n  the database. Session reads only use the database if the data is not\n  already in the cache.\n\nBoth session stores are quite fast, but the simple cache is faster because it\ndisregards persistence. In most cases, the ``cached_db`` backend will be fast\nenough, but if you need that last bit of performance, and are willing to let\nsession data be expunged from time to time, the ``cache`` backend is for you.\n\nIf you use the ``cached_db`` session backend, you also need to follow the\nconfiguration instructions for the `using database-backed sessions`_.\n\nUsing file-based sessions\n-------------------------\n\nTo use file-based sessions, set the :setting:`SESSION_ENGINE` setting to\n``\"django.contrib.sessions.backends.file\"``.\n\nYou might also want to set the :setting:`SESSION_FILE_PATH` setting (which\ndefaults to output from ``tempfile.gettempdir()``, most likely ``/tmp``) to\ncontrol where Django stores session files. Be sure to check that your Web\nserver has permissions to read and write to this location.\n\n.. _cookie-session-backend:\n\nUsing cookie-based sessions\n---------------------------\n\nTo use cookies-based sessions, set the :setting:`SESSION_ENGINE` setting to\n``\"django.contrib.sessions.backends.signed_cookies\"``. The session data will be\nstored using Django's tools for :doc:`cryptographic signing </topics/signing>`\nand the :setting:`SECRET_KEY` setting.\n\n.. note::\n\n    It's recommended to leave the :setting:`SESSION_COOKIE_HTTPONLY` setting\n    on ``True`` to prevent access to the stored data from JavaScript.\n\n.. warning::\n\n    **If the SECRET_KEY is not kept secret and you are using the**\n    :class:`~django.contrib.sessions.serializers.PickleSerializer`, **this can\n    lead to arbitrary remote code execution.**\n\n    An attacker in possession of the :setting:`SECRET_KEY` can not only\n    generate falsified session data, which your site will trust, but also\n    remotely execute arbitrary code, as the data is serialized using pickle.\n\n    If you use cookie-based sessions, pay extra care that your secret key is\n    always kept completely secret, for any system which might be remotely\n    accessible.\n\n    **The session data is signed but not encrypted**\n\n    When using the cookies backend the session data can be read by the client.\n\n    A MAC (Message Authentication Code) is used to protect the data against\n    changes by the client, so that the session data will be invalidated when being\n    tampered with. The same invalidation happens if the client storing the\n    cookie (e.g. your user's browser) can't store all of the session cookie and\n    drops data. Even though Django compresses the data, it's still entirely\n    possible to exceed the :rfc:`common limit of 4096 bytes <2965#section-5.3>`\n    per cookie.\n\n    **No freshness guarantee**\n\n    Note also that while the MAC can guarantee the authenticity of the data\n    (that it was generated by your site, and not someone else), and the\n    integrity of the data (that it is all there and correct), it cannot\n    guarantee freshness i.e. that you are being sent back the last thing you\n    sent to the client. This means that for some uses of session data, the\n    cookie backend might open you up to `replay attacks`_. Unlike other session\n    backends which keep a server-side record of each session and invalidate it\n    when a user logs out, cookie-based sessions are not invalidated when a user\n    logs out. Thus if an attacker steals a user's cookie, they can use that\n    cookie to login as that user even if the user logs out. Cookies will only\n    be detected as 'stale' if they are older than your\n    :setting:`SESSION_COOKIE_AGE`.\n\n    **Performance**\n\n    Finally, the size of a cookie can have an impact on the `speed of your site`_.\n\n.. _`replay attacks`: https://en.wikipedia.org/wiki/Replay_attack\n.. _`speed of your site`: https://yuiblog.com/blog/2007/03/01/performance-research-part-3/\n\nUsing sessions in views\n=======================\n\nWhen ``SessionMiddleware`` is activated, each :class:`~django.http.HttpRequest`\nobject -- the first argument to any Django view function -- will have a\n``session`` attribute, which is a dictionary-like object.\n\nYou can read it and write to ``request.session`` at any point in your view.\nYou can edit it multiple times.\n\n.. class:: backends.base.SessionBase\n\n    This is the base class for all session objects. It has the following\n    standard dictionary methods:\n\n    .. method:: __getitem__(key)\n\n      Example: ``fav_color = request.session['fav_color']``\n\n    .. method:: __setitem__(key, value)\n\n      Example: ``request.session['fav_color'] = 'blue'``\n\n    .. method:: __delitem__(key)\n\n      Example: ``del request.session['fav_color']``. This raises ``KeyError``\n      if the given ``key`` isn't already in the session.\n\n    .. method:: __contains__(key)\n\n      Example: ``'fav_color' in request.session``\n\n    .. method:: get(key, default=None)\n\n      Example: ``fav_color = request.session.get('fav_color', 'red')``\n\n    .. method:: pop(key, default=__not_given)\n\n      Example: ``fav_color = request.session.pop('fav_color', 'blue')``\n\n    .. method:: keys()\n\n    .. method:: items()\n\n    .. method:: setdefault()\n\n    .. method:: clear()\n\n    It also has these methods:\n\n    .. method:: flush()\n\n      Deletes the current session data from the session and deletes the session\n      cookie. This is used if you want to ensure that the previous session data\n      can't be accessed again from the user's browser (for example, the\n      :func:`django.contrib.auth.logout()` function calls it).\n\n    .. method:: set_test_cookie()\n\n      Sets a test cookie to determine whether the user's browser supports\n      cookies. Due to the way cookies work, you won't be able to test this\n      until the user's next page request. See `Setting test cookies`_ below for\n      more information.\n\n    .. method:: test_cookie_worked()\n\n      Returns either ``True`` or ``False``, depending on whether the user's\n      browser accepted the test cookie. Due to the way cookies work, you'll\n      have to call ``set_test_cookie()`` on a previous, separate page request.\n      See `Setting test cookies`_ below for more information.\n\n    .. method:: delete_test_cookie()\n\n      Deletes the test cookie. Use this to clean up after yourself.\n\n    .. method:: get_session_cookie_age()\n\n      Returns the age of session cookies, in seconds. Defaults to\n      :setting:`SESSION_COOKIE_AGE`.\n\n    .. method:: set_expiry(value)\n\n      Sets the expiration time for the session. You can pass a number of\n      different values:\n\n      * If ``value`` is an integer, the session will expire after that\n        many seconds of inactivity. For example, calling\n        ``request.session.set_expiry(300)`` would make the session expire\n        in 5 minutes.\n\n      * If ``value`` is a ``datetime`` or ``timedelta`` object, the\n        session will expire at that specific date/time. Note that ``datetime``\n        and ``timedelta`` values are only serializable if you are using the\n        :class:`~django.contrib.sessions.serializers.PickleSerializer`.\n\n      * If ``value`` is ``0``, the user's session cookie will expire\n        when the user's Web browser is closed.\n\n      * If ``value`` is ``None``, the session reverts to using the global\n        session expiry policy.\n\n      Reading a session is not considered activity for expiration\n      purposes. Session expiration is computed from the last time the\n      session was *modified*.\n\n    .. method:: get_expiry_age()\n\n      Returns the number of seconds until this session expires. For sessions\n      with no custom expiration (or those set to expire at browser close), this\n      will equal :setting:`SESSION_COOKIE_AGE`.\n\n      This function accepts two optional keyword arguments:\n\n      - ``modification``: last modification of the session, as a\n        :class:`~datetime.datetime` object. Defaults to the current time.\n      - ``expiry``: expiry information for the session, as a\n        :class:`~datetime.datetime` object, an :class:`int` (in seconds), or\n        ``None``. Defaults to the value stored in the session by\n        :meth:`set_expiry`, if there is one, or ``None``.\n\n    .. method:: get_expiry_date()\n\n      Returns the date this session will expire. For sessions with no custom\n      expiration (or those set to expire at browser close), this will equal the\n      date :setting:`SESSION_COOKIE_AGE` seconds from now.\n\n      This function accepts the same keyword arguments as :meth:`get_expiry_age`.\n\n    .. method:: get_expire_at_browser_close()\n\n      Returns either ``True`` or ``False``, depending on whether the user's\n      session cookie will expire when the user's Web browser is closed.\n\n    .. method:: clear_expired()\n\n      Removes expired sessions from the session store. This class method is\n      called by :djadmin:`clearsessions`.\n\n    .. method:: cycle_key()\n\n      Creates a new session key while retaining the current session data.\n      :func:`django.contrib.auth.login()` calls this method to mitigate against\n      session fixation.\n\n.. _session_serialization:\n\nSession serialization\n---------------------\n\nBy default, Django serializes session data using JSON. You can use the\n:setting:`SESSION_SERIALIZER` setting to customize the session serialization\nformat. Even with the caveats described in :ref:`custom-serializers`, we highly\nrecommend sticking with JSON serialization *especially if you are using the\ncookie backend*.\n\nFor example, here's an attack scenario if you use :mod:`pickle` to serialize\nsession data. If you're using the :ref:`signed cookie session backend\n<cookie-session-backend>` and :setting:`SECRET_KEY` is known by an attacker\n(there isn't an inherent vulnerability in Django that would cause it to leak),\nthe attacker could insert a string into their session which, when unpickled,\nexecutes arbitrary code on the server. The technique for doing so is simple and\neasily available on the internet. Although the cookie session storage signs the\ncookie-stored data to prevent tampering, a :setting:`SECRET_KEY` leak\nimmediately escalates to a remote code execution vulnerability.\n\nBundled serializers\n~~~~~~~~~~~~~~~~~~~\n\n.. class:: serializers.JSONSerializer\n\n    A wrapper around the JSON serializer from :mod:`django.core.signing`. Can\n    only serialize basic data types.\n\n    In addition, as JSON supports only string keys, note that using non-string\n    keys in ``request.session`` won't work as expected::\n\n        >>> # initial assignment\n        >>> request.session[0] = 'bar'\n        >>> # subsequent requests following serialization & deserialization\n        >>> # of session data\n        >>> request.session[0]  # KeyError\n        >>> request.session['0']\n        'bar'\n\n    Similarly, data that can't be encoded in JSON, such as non-UTF8 bytes like\n    ``'\\xd9'`` (which raises :exc:`UnicodeDecodeError`), can't be stored.\n\n    See the :ref:`custom-serializers` section for more details on limitations\n    of JSON serialization.\n\n.. class:: serializers.PickleSerializer\n\n    Supports arbitrary Python objects, but, as described above, can lead to a\n    remote code execution vulnerability if :setting:`SECRET_KEY` becomes known\n    by an attacker.\n\n.. _custom-serializers:\n\nWrite your own serializer\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\nNote that unlike :class:`~django.contrib.sessions.serializers.PickleSerializer`,\nthe :class:`~django.contrib.sessions.serializers.JSONSerializer` cannot handle\narbitrary Python data types. As is often the case, there is a trade-off between\nconvenience and security. If you wish to store more advanced data types\nincluding ``datetime`` and ``Decimal`` in JSON backed sessions, you will need\nto write a custom serializer (or convert such values to a JSON serializable\nobject before storing them in ``request.session``). While serializing these\nvalues is often straightforward\n(:class:`~django.core.serializers.json.DjangoJSONEncoder` may be helpful),\nwriting a decoder that can reliably get back the same thing that you put in is\nmore fragile. For example, you run the risk of returning a ``datetime`` that\nwas actually a string that just happened to be in the same format chosen for\n``datetime``\\s).\n\nYour serializer class must implement two methods,\n``dumps(self, obj)`` and ``loads(self, data)``, to serialize and deserialize\nthe dictionary of session data, respectively.\n\nSession object guidelines\n-------------------------\n\n* Use normal Python strings as dictionary keys on ``request.session``. This\n  is more of a convention than a hard-and-fast rule.\n\n* Session dictionary keys that begin with an underscore are reserved for\n  internal use by Django.\n\n* Don't override ``request.session`` with a new object, and don't access or\n  set its attributes. Use it like a Python dictionary.\n\nExamples\n--------\n\nThis simplistic view sets a ``has_commented`` variable to ``True`` after a user\nposts a comment. It doesn't let a user post a comment more than once::\n\n    def post_comment(request, new_comment):\n        if request.session.get('has_commented', False):\n            return HttpResponse(\"You've already commented.\")\n        c = comments.Comment(comment=new_comment)\n        c.save()\n        request.session['has_commented'] = True\n        return HttpResponse('Thanks for your comment!')\n\nThis simplistic view logs in a \"member\" of the site::\n\n    def login(request):\n        m = Member.objects.get(username=request.POST['username'])\n        if m.password == request.POST['password']:\n            request.session['member_id'] = m.id\n            return HttpResponse(\"You're logged in.\")\n        else:\n            return HttpResponse(\"Your username and password didn't match.\")\n\n...And this one logs a member out, according to ``login()`` above::\n\n    def logout(request):\n        try:\n            del request.session['member_id']\n        except KeyError:\n            pass\n        return HttpResponse(\"You're logged out.\")\n\nThe standard :meth:`django.contrib.auth.logout` function actually does a bit\nmore than this to prevent inadvertent data leakage. It calls the\n:meth:`~backends.base.SessionBase.flush` method of ``request.session``.\nWe are using this example as a demonstration of how to work with session\nobjects, not as a full ``logout()`` implementation.\n\nSetting test cookies\n====================\n\nAs a convenience, Django provides a way to test whether the user's browser\naccepts cookies. Call the :meth:`~backends.base.SessionBase.set_test_cookie`\nmethod of ``request.session`` in a view, and call\n:meth:`~backends.base.SessionBase.test_cookie_worked` in a subsequent view --\nnot in the same view call.\n\nThis awkward split between ``set_test_cookie()`` and ``test_cookie_worked()``\nis necessary due to the way cookies work. When you set a cookie, you can't\nactually tell whether a browser accepted it until the browser's next request.\n\nIt's good practice to use\n:meth:`~backends.base.SessionBase.delete_test_cookie()` to clean up after\nyourself. Do this after you've verified that the test cookie worked.\n\nHere's a typical usage example::\n\n    from django.http import HttpResponse\n    from django.shortcuts import render\n\n    def login(request):\n        if request.method == 'POST':\n            if request.session.test_cookie_worked():\n                request.session.delete_test_cookie()\n                return HttpResponse(\"You're logged in.\")\n            else:\n                return HttpResponse(\"Please enable cookies and try again.\")\n        request.session.set_test_cookie()\n        return render(request, 'foo/login_form.html')\n\nUsing sessions out of views\n===========================\n\n.. note::\n\n    The examples in this section import the ``SessionStore`` object directly\n    from the ``django.contrib.sessions.backends.db`` backend. In your own code,\n    you should consider importing ``SessionStore`` from the session engine\n    designated by :setting:`SESSION_ENGINE`, as below:\n\n      >>> from importlib import import_module\n      >>> from django.conf import settings\n      >>> SessionStore = import_module(settings.SESSION_ENGINE).SessionStore\n\nAn API is available to manipulate session data outside of a view::\n\n    >>> from django.contrib.sessions.backends.db import SessionStore\n    >>> s = SessionStore()\n    >>> # stored as seconds since epoch since datetimes are not serializable in JSON.\n    >>> s['last_login'] = 1376587691\n    >>> s.create()\n    >>> s.session_key\n    '2b1189a188b44ad18c35e113ac6ceead'\n    >>> s = SessionStore(session_key='2b1189a188b44ad18c35e113ac6ceead')\n    >>> s['last_login']\n    1376587691\n\n``SessionStore.create()`` is designed to create a new session (i.e. one not\nloaded from the session store and with ``session_key=None``). ``save()`` is\ndesigned to save an existing session (i.e. one loaded from the session store).\nCalling ``save()`` on a new session may also work but has a small chance of\ngenerating a ``session_key`` that collides with an existing one. ``create()``\ncalls ``save()`` and loops until an unused ``session_key`` is generated.\n\nIf you're using the ``django.contrib.sessions.backends.db`` backend, each\nsession is a normal Django model. The ``Session`` model is defined in\n``django/contrib/sessions/models.py``. Because it's a normal model, you can\naccess sessions using the normal Django database API::\n\n    >>> from django.contrib.sessions.models import Session\n    >>> s = Session.objects.get(pk='2b1189a188b44ad18c35e113ac6ceead')\n    >>> s.expire_date\n    datetime.datetime(2005, 8, 20, 13, 35, 12)\n\nNote that you'll need to call\n:meth:`~base_session.AbstractBaseSession.get_decoded()` to get the session\ndictionary. This is necessary because the dictionary is stored in an encoded\nformat::\n\n    >>> s.session_data\n    'KGRwMQpTJ19hdXRoX3VzZXJfaWQnCnAyCkkxCnMuMTExY2ZjODI2Yj...'\n    >>> s.get_decoded()\n    {'user_id': 42}\n\nWhen sessions are saved\n=======================\n\nBy default, Django only saves to the session database when the session has been\nmodified -- that is if any of its dictionary values have been assigned or\ndeleted::\n\n    # Session is modified.\n    request.session['foo'] = 'bar'\n\n    # Session is modified.\n    del request.session['foo']\n\n    # Session is modified.\n    request.session['foo'] = {}\n\n    # Gotcha: Session is NOT modified, because this alters\n    # request.session['foo'] instead of request.session.\n    request.session['foo']['bar'] = 'baz'\n\nIn the last case of the above example, we can tell the session object\nexplicitly that it has been modified by setting the ``modified`` attribute on\nthe session object::\n\n    request.session.modified = True\n\nTo change this default behavior, set the :setting:`SESSION_SAVE_EVERY_REQUEST`\nsetting to ``True``. When set to ``True``, Django will save the session to the\ndatabase on every single request.\n\nNote that the session cookie is only sent when a session has been created or\nmodified. If :setting:`SESSION_SAVE_EVERY_REQUEST` is ``True``, the session\ncookie will be sent on every request.\n\nSimilarly, the ``expires`` part of a session cookie is updated each time the\nsession cookie is sent.\n\nThe session is not saved if the response's status code is 500.\n\n.. _browser-length-vs-persistent-sessions:\n\nBrowser-length sessions vs. persistent sessions\n===============================================\n\nYou can control whether the session framework uses browser-length sessions vs.\npersistent sessions with the :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE`\nsetting.\n\nBy default, :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE` is set to ``False``,\nwhich means session cookies will be stored in users' browsers for as long as\n:setting:`SESSION_COOKIE_AGE`. Use this if you don't want people to have to\nlog in every time they open a browser.\n\nIf :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE` is set to ``True``, Django will\nuse browser-length cookies -- cookies that expire as soon as the user closes\ntheir browser. Use this if you want people to have to log in every time they\nopen a browser.\n\nThis setting is a global default and can be overwritten at a per-session level\nby explicitly calling the :meth:`~backends.base.SessionBase.set_expiry` method\nof ``request.session`` as described above in `using sessions in views`_.\n\n.. note::\n\n    Some browsers (Chrome, for example) provide settings that allow users to\n    continue browsing sessions after closing and re-opening the browser. In\n    some cases, this can interfere with the\n    :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE` setting and prevent sessions\n    from expiring on browser close. Please be aware of this while testing\n    Django applications which have the\n    :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE` setting enabled.\n\n.. _clearing-the-session-store:\n\nClearing the session store\n==========================\n\nAs users create new sessions on your website, session data can accumulate in\nyour session store. If you're using the database backend, the\n``django_session`` database table will grow. If you're using the file backend,\nyour temporary directory will contain an increasing number of files.\n\nTo understand this problem, consider what happens with the database backend.\nWhen a user logs in, Django adds a row to the ``django_session`` database\ntable. Django updates this row each time the session data changes. If the user\nlogs out manually, Django deletes the row. But if the user does *not* log out,\nthe row never gets deleted. A similar process happens with the file backend.\n\nDjango does *not* provide automatic purging of expired sessions. Therefore,\nit's your job to purge expired sessions on a regular basis. Django provides a\nclean-up management command for this purpose: :djadmin:`clearsessions`. It's\nrecommended to call this command on a regular basis, for example as a daily\ncron job.\n\nNote that the cache backend isn't vulnerable to this problem, because caches\nautomatically delete stale data. Neither is the cookie backend, because the\nsession data is stored by the users' browsers.\n\nSettings\n========\n\nA few :ref:`Django settings <settings-sessions>` give you control over session\nbehavior:\n\n* :setting:`SESSION_CACHE_ALIAS`\n* :setting:`SESSION_COOKIE_AGE`\n* :setting:`SESSION_COOKIE_DOMAIN`\n* :setting:`SESSION_COOKIE_HTTPONLY`\n* :setting:`SESSION_COOKIE_NAME`\n* :setting:`SESSION_COOKIE_PATH`\n* :setting:`SESSION_COOKIE_SAMESITE`\n* :setting:`SESSION_COOKIE_SECURE`\n* :setting:`SESSION_ENGINE`\n* :setting:`SESSION_EXPIRE_AT_BROWSER_CLOSE`\n* :setting:`SESSION_FILE_PATH`\n* :setting:`SESSION_SAVE_EVERY_REQUEST`\n* :setting:`SESSION_SERIALIZER`\n\n.. _topics-session-security:\n\nSession security\n================\n\nSubdomains within a site are able to set cookies on the client for the whole\ndomain. This makes session fixation possible if cookies are permitted from\nsubdomains not controlled by trusted users.\n\nFor example, an attacker could log into ``good.example.com`` and get a valid\nsession for their account. If the attacker has control over ``bad.example.com``,\nthey can use it to send their session key to you since a subdomain is permitted\nto set cookies on ``*.example.com``. When you visit ``good.example.com``,\nyou'll be logged in as the attacker and might inadvertently enter your\nsensitive personal data (e.g. credit card info) into the attacker's account.\n\nAnother possible attack would be if ``good.example.com`` sets its\n:setting:`SESSION_COOKIE_DOMAIN` to ``\"example.com\"`` which would cause\nsession cookies from that site to be sent to ``bad.example.com``.\n\nTechnical details\n=================\n\n* The session dictionary accepts any :mod:`json` serializable value when using\n  :class:`~django.contrib.sessions.serializers.JSONSerializer` or any\n  picklable Python object when using\n  :class:`~django.contrib.sessions.serializers.PickleSerializer`. See the\n  :mod:`pickle` module for more information.\n\n* Session data is stored in a database table named ``django_session`` .\n\n* Django only sends a cookie if it needs to. If you don't set any session\n  data, it won't send a session cookie.\n\nThe ``SessionStore`` object\n---------------------------\n\nWhen working with sessions internally, Django uses a session store object from\nthe corresponding session engine. By convention, the session store object class\nis named ``SessionStore`` and is located in the module designated by\n:setting:`SESSION_ENGINE`.\n\nAll ``SessionStore`` classes available in Django inherit from\n:class:`~backends.base.SessionBase` and implement data manipulation methods,\nnamely:\n\n* ``exists()``\n* ``create()``\n* ``save()``\n* ``delete()``\n* ``load()``\n* :meth:`~backends.base.SessionBase.clear_expired`\n\nIn order to build a custom session engine or to customize an existing one, you\nmay create a new class inheriting from :class:`~backends.base.SessionBase` or\nany other existing ``SessionStore`` class.\n\nYou can extend the session engines, but doing so with database-backed session\nengines generally requires some extra effort (see the next section for\ndetails).\n\n.. _extending-database-backed-session-engines:\n\nExtending database-backed session engines\n=========================================\n\nCreating a custom database-backed session engine built upon those included in\nDjango (namely ``db`` and ``cached_db``) may be done by inheriting\n:class:`~base_session.AbstractBaseSession` and either ``SessionStore`` class.\n\n``AbstractBaseSession`` and ``BaseSessionManager`` are importable from\n``django.contrib.sessions.base_session`` so that they can be imported without\nincluding ``django.contrib.sessions`` in :setting:`INSTALLED_APPS`.\n\n.. class:: base_session.AbstractBaseSession\n\n\n    The abstract base session model.\n\n    .. attribute:: session_key\n\n        Primary key. The field itself may contain up to 40 characters. The\n        current implementation generates a 32-character string (a random\n        sequence of digits and lowercase ASCII letters).\n\n    .. attribute:: session_data\n\n        A string containing an encoded and serialized session dictionary.\n\n    .. attribute:: expire_date\n\n        A datetime designating when the session expires.\n\n        Expired sessions are not available to a user, however, they may still\n        be stored in the database until the :djadmin:`clearsessions` management\n        command is run.\n\n    .. classmethod:: get_session_store_class()\n\n        Returns a session store class to be used with this session model.\n\n    .. method:: get_decoded()\n\n        Returns decoded session data.\n\n        Decoding is performed by the session store class.\n\nYou can also customize the model manager by subclassing\n:class:`~django.contrib.sessions.base_session.BaseSessionManager`:\n\n.. class:: base_session.BaseSessionManager\n\n    .. method:: encode(session_dict)\n\n        Returns the given session dictionary serialized and encoded as a string.\n\n        Encoding is performed by the session store class tied to a model class.\n\n    .. method:: save(session_key, session_dict, expire_date)\n\n        Saves session data for a provided session key, or deletes the session\n        in case the data is empty.\n\nCustomization of ``SessionStore`` classes is achieved by overriding methods\nand properties described below:\n\n.. class:: backends.db.SessionStore\n\n    Implements database-backed session store.\n\n    .. classmethod:: get_model_class()\n\n        Override this method to return a custom session model if you need one.\n\n    .. method:: create_model_instance(data)\n\n        Returns a new instance of the session model object, which represents\n        the current session state.\n\n        Overriding this method provides the ability to modify session model\n        data before it's saved to database.\n\n.. class:: backends.cached_db.SessionStore\n\n    Implements cached database-backed session store.\n\n    .. attribute:: cache_key_prefix\n\n        A prefix added to a session key to build a cache key string.\n\nExample\n-------\n\nThe example below shows a custom database-backed session engine that includes\nan additional database column to store an account ID (thus providing an option\nto query the database for all active sessions for an account)::\n\n    from django.contrib.sessions.backends.db import SessionStore as DBStore\n    from django.contrib.sessions.base_session import AbstractBaseSession\n    from django.db import models\n\n    class CustomSession(AbstractBaseSession):\n        account_id = models.IntegerField(null=True, db_index=True)\n\n        @classmethod\n        def get_session_store_class(cls):\n            return SessionStore\n\n    class SessionStore(DBStore):\n        @classmethod\n        def get_model_class(cls):\n            return CustomSession\n\n        def create_model_instance(self, data):\n            obj = super().create_model_instance(data)\n            try:\n                account_id = int(data.get('_auth_user_id'))\n            except (ValueError, TypeError):\n                account_id = None\n            obj.account_id = account_id\n            return obj\n\nIf you are migrating from the Django's built-in ``cached_db`` session store to\na custom one based on ``cached_db``, you should override the cache key prefix\nin order to prevent a namespace clash::\n\n    class SessionStore(CachedDBStore):\n        cache_key_prefix = 'mysessions.custom_cached_db_backend'\n\n        # ...\n\nSession IDs in URLs\n===================\n\nThe Django sessions framework is entirely, and solely, cookie-based. It does\nnot fall back to putting session IDs in URLs as a last resort, as PHP does.\nThis is an intentional design decision. Not only does that behavior make URLs\nugly, it makes your site vulnerable to session-ID theft via the \"Referer\"\nheader.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":311,"nodeType":"TextFile","repoName":null,"name":"urls.txt","path":"docs/topics/http","text":"==============\nURL dispatcher\n==============\n\nA clean, elegant URL scheme is an important detail in a high-quality Web\napplication. Django lets you design URLs however you want, with no framework\nlimitations.\n\nSee `Cool URIs don't change`_, by World Wide Web creator Tim Berners-Lee, for\nexcellent arguments on why URLs should be clean and usable.\n\n.. _Cool URIs don't change: https://www.w3.org/Provider/Style/URI\n\nOverview\n========\n\nTo design URLs for an app, you create a Python module informally called a\n**URLconf** (URL configuration). This module is pure Python code and is a\nmapping between URL path expressions to Python functions (your views).\n\nThis mapping can be as short or as long as needed. It can reference other\nmappings. And, because it's pure Python code, it can be constructed\ndynamically.\n\nDjango also provides a way to translate URLs according to the active\nlanguage. See the :ref:`internationalization documentation\n<url-internationalization>` for more information.\n\n.. _how-django-processes-a-request:\n\nHow Django processes a request\n==============================\n\nWhen a user requests a page from your Django-powered site, this is the\nalgorithm the system follows to determine which Python code to execute:\n\n#. Django determines the root URLconf module to use. Ordinarily,\n   this is the value of the :setting:`ROOT_URLCONF` setting, but if the incoming\n   ``HttpRequest`` object has a :attr:`~django.http.HttpRequest.urlconf`\n   attribute (set by middleware), its value will be used in place of the\n   :setting:`ROOT_URLCONF` setting.\n\n#. Django loads that Python module and looks for the variable\n   ``urlpatterns``. This should be a :term:`sequence` of\n   :func:`django.urls.path` and/or :func:`django.urls.re_path` instances.\n\n#. Django runs through each URL pattern, in order, and stops at the first\n   one that matches the requested URL, matching against\n   :attr:`~django.http.HttpRequest.path_info`.\n\n#. Once one of the URL patterns matches, Django imports and calls the given\n   view, which is a Python function (or a :doc:`class-based view\n   </topics/class-based-views/index>`). The view gets passed the following\n   arguments:\n\n   * An instance of :class:`~django.http.HttpRequest`.\n   * If the matched URL pattern contained no named groups, then the\n     matches from the regular expression are provided as positional arguments.\n   * The keyword arguments are made up of any named parts matched by the\n     path expression that are provided, overridden by any arguments specified\n     in the optional ``kwargs`` argument to :func:`django.urls.path` or\n     :func:`django.urls.re_path`.\n\n#. If no URL pattern matches, or if an exception is raised during any\n   point in this process, Django invokes an appropriate\n   error-handling view. See `Error handling`_ below.\n\nExample\n=======\n\nHere's a sample URLconf::\n\n    from django.urls import path\n\n    from . import views\n\n    urlpatterns = [\n        path('articles/2003/', views.special_case_2003),\n        path('articles/<int:year>/', views.year_archive),\n        path('articles/<int:year>/<int:month>/', views.month_archive),\n        path('articles/<int:year>/<int:month>/<slug:slug>/', views.article_detail),\n    ]\n\nNotes:\n\n* To capture a value from the URL, use angle brackets.\n\n* Captured values can optionally include a converter type. For example, use\n  ``<int:name>`` to capture an integer parameter. If a converter isn't included,\n  any string, excluding a ``/`` character, is matched.\n\n* There's no need to add a leading slash, because every URL has that. For\n  example, it's ``articles``, not ``/articles``.\n\nExample requests:\n\n* A request to ``/articles/2005/03/`` would match the third entry in the\n  list. Django would call the function\n  ``views.month_archive(request, year=2005, month=3)``.\n\n* ``/articles/2003/`` would match the first pattern in the list, not the\n  second one, because the patterns are tested in order, and the first one\n  is the first test to pass. Feel free to exploit the ordering to insert\n  special cases like this. Here, Django would call the function\n  ``views.special_case_2003(request)``\n\n* ``/articles/2003`` would not match any of these patterns, because each\n  pattern requires that the URL end with a slash.\n\n* ``/articles/2003/03/building-a-django-site/`` would match the final\n  pattern. Django would call the function\n  ``views.article_detail(request, year=2003, month=3, slug=\"building-a-django-site\")``.\n\nPath converters\n===============\n\nThe following path converters are available by default:\n\n* ``str`` - Matches any non-empty string, excluding the path separator, ``'/'``.\n  This is the default if a converter isn't included in the expression.\n\n* ``int`` - Matches zero or any positive integer. Returns an ``int``.\n\n* ``slug`` - Matches any slug string consisting of ASCII letters or numbers,\n  plus the hyphen and underscore characters. For example,\n  ``building-your-1st-django-site``.\n\n* ``uuid`` - Matches a formatted UUID. To prevent multiple URLs from mapping to\n  the same page, dashes must be included and letters must be lowercase. For\n  example, ``075194d3-6885-417e-a8a8-6c931e272f00``. Returns a\n  :class:`~uuid.UUID` instance.\n\n* ``path`` - Matches any non-empty string, including the path separator,\n  ``'/'``. This allows you to match against a complete URL path rather than\n  a segment of a URL path as with ``str``.\n\n.. _registering-custom-path-converters:\n\nRegistering custom path converters\n==================================\n\nFor more complex matching requirements, you can define your own path converters.\n\nA converter is a class that includes the following:\n\n* A ``regex`` class attribute, as a string.\n\n* A ``to_python(self, value)`` method, which handles converting the matched\n  string into the type that should be passed to the view function. It should\n  raise ``ValueError`` if it can't convert the given value. A ``ValueError`` is\n  interpreted as no match and as a consequence a 404 response is sent to the\n  user unless another URL pattern matches.\n\n* A ``to_url(self, value)`` method, which handles converting the Python type\n  into a string to be used in the URL. It should raise ``ValueError`` if it\n  can't convert the given value. A ``ValueError`` is interpreted as no match\n  and as a consequence :func:`~django.urls.reverse` will raise\n  :class:`~django.urls.NoReverseMatch` unless another URL pattern matches.\n\n  .. versionchanged:: 3.1\n\n    Support for raising ``ValueError`` to indicate no match was added.\n\nFor example::\n\n    class FourDigitYearConverter:\n        regex = '[0-9]{4}'\n\n        def to_python(self, value):\n            return int(value)\n\n        def to_url(self, value):\n            return '%04d' % value\n\nRegister custom converter classes in your URLconf using\n:func:`~django.urls.register_converter`::\n\n    from django.urls import path, register_converter\n\n    from . import converters, views\n\n    register_converter(converters.FourDigitYearConverter, 'yyyy')\n\n    urlpatterns = [\n        path('articles/2003/', views.special_case_2003),\n        path('articles/<yyyy:year>/', views.year_archive),\n        ...\n    ]\n\nUsing regular expressions\n=========================\n\nIf the paths and converters syntax isn't sufficient for defining your URL\npatterns, you can also use regular expressions. To do so, use\n:func:`~django.urls.re_path` instead of :func:`~django.urls.path`.\n\nIn Python regular expressions, the syntax for named regular expression groups\nis ``(?P<name>pattern)``, where ``name`` is the name of the group and\n``pattern`` is some pattern to match.\n\nHere's the example URLconf from earlier, rewritten using regular expressions::\n\n    from django.urls import path, re_path\n\n    from . import views\n\n    urlpatterns = [\n        path('articles/2003/', views.special_case_2003),\n        re_path(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),\n        re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive),\n        re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<slug>[\\w-]+)/$', views.article_detail),\n    ]\n\nThis accomplishes roughly the same thing as the previous example, except:\n\n* The exact URLs that will match are slightly more constrained. For example,\n  the year 10000 will no longer match since the year integers are constrained\n  to be exactly four digits long.\n\n* Each captured argument is sent to the view as a string, regardless of what\n  sort of match the regular expression makes.\n\nWhen switching from using :func:`~django.urls.path` to\n:func:`~django.urls.re_path` or vice versa, it's particularly important to be\naware that the type of the view arguments may change, and so you may need to\nadapt your views.\n\nUsing unnamed regular expression groups\n---------------------------------------\n\nAs well as the named group syntax, e.g. ``(?P<year>[0-9]{4})``, you can\nalso use the shorter unnamed group, e.g. ``([0-9]{4})``.\n\nThis usage isn't particularly recommended as it makes it easier to accidentally\nintroduce errors between the intended meaning of a match and the arguments\nof the view.\n\nIn either case, using only one style within a given regex is recommended. When\nboth styles are mixed, any unnamed groups are ignored and only named groups are\npassed to the view function.\n\nNested arguments\n----------------\n\nRegular expressions allow nested arguments, and Django will resolve them and\npass them to the view. When reversing, Django will try to fill in all outer\ncaptured arguments, ignoring any nested captured arguments. Consider the\nfollowing URL patterns which optionally take a page argument::\n\n    from django.urls import re_path\n\n    urlpatterns = [\n        re_path(r'^blog/(page-(\\d+)/)?$', blog_articles),                  # bad\n        re_path(r'^comments/(?:page-(?P<page_number>\\d+)/)?$', comments),  # good\n    ]\n\nBoth patterns use nested arguments and will resolve: for example,\n``blog/page-2/`` will result in a match to ``blog_articles`` with two\npositional arguments: ``page-2/`` and ``2``. The second pattern for\n``comments`` will match ``comments/page-2/`` with keyword argument\n``page_number`` set to 2. The outer argument in this case is a non-capturing\nargument ``(?:...)``.\n\nThe ``blog_articles`` view needs the outermost captured argument to be reversed,\n``page-2/`` or no arguments in this case, while ``comments`` can be reversed\nwith either no arguments or a value for ``page_number``.\n\nNested captured arguments create a strong coupling between the view arguments\nand the URL as illustrated by ``blog_articles``: the view receives part of the\nURL (``page-2/``) instead of only the value the view is interested in. This\ncoupling is even more pronounced when reversing, since to reverse the view we\nneed to pass the piece of URL instead of the page number.\n\nAs a rule of thumb, only capture the values the view needs to work with and\nuse non-capturing arguments when the regular expression needs an argument but\nthe view ignores it.\n\nWhat the URLconf searches against\n=================================\n\nThe URLconf searches against the requested URL, as a normal Python string. This\ndoes not include GET or POST parameters, or the domain name.\n\nFor example, in a request to ``https://www.example.com/myapp/``, the URLconf\nwill look for ``myapp/``.\n\nIn a request to ``https://www.example.com/myapp/?page=3``, the URLconf will look\nfor ``myapp/``.\n\nThe URLconf doesn't look at the request method. In other words, all request\nmethods -- ``POST``, ``GET``, ``HEAD``, etc. -- will be routed to the same\nfunction for the same URL.\n\nSpecifying defaults for view arguments\n======================================\n\nA convenient trick is to specify default parameters for your views' arguments.\nHere's an example URLconf and view::\n\n    # URLconf\n    from django.urls import path\n\n    from . import views\n\n    urlpatterns = [\n        path('blog/', views.page),\n        path('blog/page<int:num>/', views.page),\n    ]\n\n    # View (in blog/views.py)\n    def page(request, num=1):\n        # Output the appropriate page of blog entries, according to num.\n        ...\n\nIn the above example, both URL patterns point to the same view --\n``views.page`` -- but the first pattern doesn't capture anything from the\nURL. If the first pattern matches, the ``page()`` function will use its\ndefault argument for ``num``, ``1``. If the second pattern matches,\n``page()`` will use whatever ``num`` value was captured.\n\nPerformance\n===========\n\nEach regular expression in a ``urlpatterns`` is compiled the first time it's\naccessed. This makes the system blazingly fast.\n\nSyntax of the ``urlpatterns`` variable\n======================================\n\n``urlpatterns`` should be a :term:`sequence` of :func:`~django.urls.path`\nand/or :func:`~django.urls.re_path` instances.\n\nError handling\n==============\n\nWhen Django can't find a match for the requested URL, or when an exception is\nraised, Django invokes an error-handling view.\n\nThe views to use for these cases are specified by four variables. Their\ndefault values should suffice for most projects, but further customization is\npossible by overriding their default values.\n\nSee the documentation on :ref:`customizing error views\n<customizing-error-views>` for the full details.\n\nSuch values can be set in your root URLconf. Setting these variables in any\nother URLconf will have no effect.\n\nValues must be callables, or strings representing the full Python import path\nto the view that should be called to handle the error condition at hand.\n\nThe variables are:\n\n* ``handler400`` -- See :data:`django.conf.urls.handler400`.\n* ``handler403`` -- See :data:`django.conf.urls.handler403`.\n* ``handler404`` -- See :data:`django.conf.urls.handler404`.\n* ``handler500`` -- See :data:`django.conf.urls.handler500`.\n\n.. _including-other-urlconfs:\n\nIncluding other URLconfs\n========================\n\nAt any point, your ``urlpatterns`` can \"include\" other URLconf modules. This\nessentially \"roots\" a set of URLs below other ones.\n\nFor example, here's an excerpt of the URLconf for the `Django website`_\nitself. It includes a number of other URLconfs::\n\n    from django.urls import include, path\n\n    urlpatterns = [\n        # ... snip ...\n        path('community/', include('aggregator.urls')),\n        path('contact/', include('contact.urls')),\n        # ... snip ...\n    ]\n\nWhenever Django encounters :func:`~django.urls.include()`, it chops off\nwhatever part of the URL matched up to that point and sends the remaining\nstring to the included URLconf for further processing.\n\nAnother possibility is to include additional URL patterns by using a list of\n:func:`~django.urls.path` instances. For example, consider this URLconf::\n\n    from django.urls import include, path\n\n    from apps.main import views as main_views\n    from credit import views as credit_views\n\n    extra_patterns = [\n        path('reports/', credit_views.report),\n        path('reports/<int:id>/', credit_views.report),\n        path('charge/', credit_views.charge),\n    ]\n\n    urlpatterns = [\n        path('', main_views.homepage),\n        path('help/', include('apps.help.urls')),\n        path('credit/', include(extra_patterns)),\n    ]\n\nIn this example, the ``/credit/reports/`` URL will be handled by the\n``credit_views.report()`` Django view.\n\nThis can be used to remove redundancy from URLconfs where a single pattern\nprefix is used repeatedly. For example, consider this URLconf::\n\n    from django.urls import path\n    from . import views\n\n    urlpatterns = [\n        path('<page_slug>-<page_id>/history/', views.history),\n        path('<page_slug>-<page_id>/edit/', views.edit),\n        path('<page_slug>-<page_id>/discuss/', views.discuss),\n        path('<page_slug>-<page_id>/permissions/', views.permissions),\n    ]\n\nWe can improve this by stating the common path prefix only once and grouping\nthe suffixes that differ::\n\n    from django.urls import include, path\n    from . import views\n\n    urlpatterns = [\n        path('<page_slug>-<page_id>/', include([\n            path('history/', views.history),\n            path('edit/', views.edit),\n            path('discuss/', views.discuss),\n            path('permissions/', views.permissions),\n        ])),\n    ]\n\n.. _`Django website`: https://www.djangoproject.com/\n\nCaptured parameters\n-------------------\n\nAn included URLconf receives any captured parameters from parent URLconfs, so\nthe following example is valid::\n\n    # In settings/urls/main.py\n    from django.urls import include, path\n\n    urlpatterns = [\n        path('<username>/blog/', include('foo.urls.blog')),\n    ]\n\n    # In foo/urls/blog.py\n    from django.urls import path\n    from . import views\n\n    urlpatterns = [\n        path('', views.blog.index),\n        path('archive/', views.blog.archive),\n    ]\n\nIn the above example, the captured ``\"username\"`` variable is passed to the\nincluded URLconf, as expected.\n\n.. _views-extra-options:\n\nPassing extra options to view functions\n=======================================\n\nURLconfs have a hook that lets you pass extra arguments to your view functions,\nas a Python dictionary.\n\nThe :func:`~django.urls.path` function can take an optional third argument\nwhich should be a dictionary of extra keyword arguments to pass to the view\nfunction.\n\nFor example::\n\n    from django.urls import path\n    from . import views\n\n    urlpatterns = [\n        path('blog/<int:year>/', views.year_archive, {'foo': 'bar'}),\n    ]\n\nIn this example, for a request to ``/blog/2005/``, Django will call\n``views.year_archive(request, year=2005, foo='bar')``.\n\nThis technique is used in the\n:doc:`syndication framework </ref/contrib/syndication>` to pass metadata and\noptions to views.\n\n.. admonition:: Dealing with conflicts\n\n    It's possible to have a URL pattern which captures named keyword arguments,\n    and also passes arguments with the same names in its dictionary of extra\n    arguments. When this happens, the arguments in the dictionary will be used\n    instead of the arguments captured in the URL.\n\nPassing extra options to ``include()``\n--------------------------------------\n\nSimilarly, you can pass extra options to :func:`~django.urls.include` and\neach line in the included URLconf will be passed the extra options.\n\nFor example, these two URLconf sets are functionally identical:\n\nSet one::\n\n    # main.py\n    from django.urls import include, path\n\n    urlpatterns = [\n        path('blog/', include('inner'), {'blog_id': 3}),\n    ]\n\n    # inner.py\n    from django.urls import path\n    from mysite import views\n\n    urlpatterns = [\n        path('archive/', views.archive),\n        path('about/', views.about),\n    ]\n\nSet two::\n\n    # main.py\n    from django.urls import include, path\n    from mysite import views\n\n    urlpatterns = [\n        path('blog/', include('inner')),\n    ]\n\n    # inner.py\n    from django.urls import path\n\n    urlpatterns = [\n        path('archive/', views.archive, {'blog_id': 3}),\n        path('about/', views.about, {'blog_id': 3}),\n    ]\n\nNote that extra options will *always* be passed to *every* line in the included\nURLconf, regardless of whether the line's view actually accepts those options\nas valid. For this reason, this technique is only useful if you're certain that\nevery view in the included URLconf accepts the extra options you're passing.\n\nReverse resolution of URLs\n==========================\n\nA common need when working on a Django project is the possibility to obtain URLs\nin their final forms either for embedding in generated content (views and assets\nURLs, URLs shown to the user, etc.) or for handling of the navigation flow on\nthe server side (redirections, etc.)\n\nIt is strongly desirable to avoid hard-coding these URLs (a laborious,\nnon-scalable and error-prone strategy). Equally dangerous is devising ad-hoc\nmechanisms to generate URLs that are parallel to the design described by the\nURLconf, which can result in the production of URLs that become stale over time.\n\nIn other words, what's needed is a DRY mechanism. Among other advantages it\nwould allow evolution of the URL design without having to go over all the\nproject source code to search and replace outdated URLs.\n\nThe primary piece of information we have available to get a URL is an\nidentification (e.g. the name) of the view in charge of handling it. Other\npieces of information that necessarily must participate in the lookup of the\nright URL are the types (positional, keyword) and values of the view arguments.\n\nDjango provides a solution such that the URL mapper is the only repository of\nthe URL design. You feed it with your URLconf and then it can be used in both\ndirections:\n\n* Starting with a URL requested by the user/browser, it calls the right Django\n  view providing any arguments it might need with their values as extracted from\n  the URL.\n\n* Starting with the identification of the corresponding Django view plus the\n  values of arguments that would be passed to it, obtain the associated URL.\n\nThe first one is the usage we've been discussing in the previous sections. The\nsecond one is what is known as *reverse resolution of URLs*, *reverse URL\nmatching*, *reverse URL lookup*, or simply *URL reversing*.\n\nDjango provides tools for performing URL reversing that match the different\nlayers where URLs are needed:\n\n* In templates: Using the :ttag:`url` template tag.\n\n* In Python code: Using the :func:`~django.urls.reverse` function.\n\n* In higher level code related to handling of URLs of Django model instances:\n  The :meth:`~django.db.models.Model.get_absolute_url` method.\n\nExamples\n--------\n\nConsider again this URLconf entry::\n\n    from django.urls import path\n\n    from . import views\n\n    urlpatterns = [\n        #...\n        path('articles/<int:year>/', views.year_archive, name='news-year-archive'),\n        #...\n    ]\n\nAccording to this design, the URL for the archive corresponding to year *nnnn*\nis ``/articles/<nnnn>/``.\n\nYou can obtain these in template code by using:\n\n.. code-block:: html+django\n\n    <a href=\"{% url 'news-year-archive' 2012 %}\">2012 Archive</a>\n    {# Or with the year in a template context variable: #}\n    <ul>\n    {% for yearvar in year_list %}\n    <li><a href=\"{% url 'news-year-archive' yearvar %}\">{{ yearvar }} Archive</a></li>\n    {% endfor %}\n    </ul>\n\nOr in Python code::\n\n    from django.http import HttpResponseRedirect\n    from django.urls import reverse\n\n    def redirect_to_year(request):\n        # ...\n        year = 2006\n        # ...\n        return HttpResponseRedirect(reverse('news-year-archive', args=(year,)))\n\nIf, for some reason, it was decided that the URLs where content for yearly\narticle archives are published at should be changed then you would only need to\nchange the entry in the URLconf.\n\nIn some scenarios where views are of a generic nature, a many-to-one\nrelationship might exist between URLs and views. For these cases the view name\nisn't a good enough identifier for it when comes the time of reversing\nURLs. Read the next section to know about the solution Django provides for this.\n\n.. _naming-url-patterns:\n\nNaming URL patterns\n===================\n\nIn order to perform URL reversing, you'll need to use **named URL patterns**\nas done in the examples above. The string used for the URL name can contain any\ncharacters you like. You are not restricted to valid Python names.\n\nWhen naming URL patterns, choose names that are unlikely to clash with other\napplications' choice of names. If you call your URL pattern ``comment``\nand another application does the same thing, the URL that\n:func:`~django.urls.reverse()` finds depends on whichever pattern is last in\nyour project's ``urlpatterns`` list.\n\nPutting a prefix on your URL names, perhaps derived from the application\nname (such as ``myapp-comment`` instead of ``comment``), decreases the chance\nof collision.\n\nYou can deliberately choose the *same URL name* as another application if you\nwant to override a view. For example, a common use case is to override the\n:class:`~django.contrib.auth.views.LoginView`. Parts of Django and most\nthird-party apps assume that this view has a URL pattern with the name\n``login``. If you have a custom login view and give its URL the name ``login``,\n:func:`~django.urls.reverse()` will find your custom view as long as it's in\n``urlpatterns`` after ``django.contrib.auth.urls`` is included (if that's\nincluded at all).\n\nYou may also use the same name for multiple URL patterns if they differ in\ntheir arguments. In addition to the URL name, :func:`~django.urls.reverse()`\nmatches the number of arguments and the names of the keyword arguments. Path\nconverters can also raise ``ValueError`` to indicate no match, see\n:ref:`registering-custom-path-converters` for details.\n\n.. _topics-http-defining-url-namespaces:\n\nURL namespaces\n==============\n\nIntroduction\n------------\n\nURL namespaces allow you to uniquely reverse :ref:`named URL patterns\n<naming-url-patterns>` even if different applications use the same URL names.\nIt's a good practice for third-party apps to always use namespaced URLs (as we\ndid in the tutorial). Similarly, it also allows you to reverse URLs if multiple\ninstances of an application are deployed. In other words, since multiple\ninstances of a single application will share named URLs, namespaces provide a\nway to tell these named URLs apart.\n\nDjango applications that make proper use of URL namespacing can be deployed\nmore than once for a particular site. For example :mod:`django.contrib.admin`\nhas an :class:`~django.contrib.admin.AdminSite` class which allows you to\n:ref:`deploy more than one instance of the admin <multiple-admin-sites>`.  In a\nlater example, we'll discuss the idea of deploying the polls application from\nthe tutorial in two different locations so we can serve the same functionality\nto two different audiences (authors and publishers).\n\nA URL namespace comes in two parts, both of which are strings:\n\n.. glossary::\n\n  application namespace\n    This describes the name of the application that is being deployed. Every\n    instance of a single application will have the same application namespace.\n    For example, Django's admin application has the somewhat predictable\n    application namespace of ``'admin'``.\n\n  instance namespace\n    This identifies a specific instance of an application. Instance namespaces\n    should be unique across your entire project. However, an instance namespace\n    can be the same as the application namespace. This is used to specify a\n    default instance of an application. For example, the default Django admin\n    instance has an instance namespace of ``'admin'``.\n\nNamespaced URLs are specified using the ``':'`` operator. For example, the main\nindex page of the admin application is referenced using ``'admin:index'``. This\nindicates a namespace of ``'admin'``, and a named URL of ``'index'``.\n\nNamespaces can also be nested. The named URL ``'sports:polls:index'`` would\nlook for a pattern named ``'index'`` in the namespace ``'polls'`` that is itself\ndefined within the top-level namespace ``'sports'``.\n\n.. _topics-http-reversing-url-namespaces:\n\nReversing namespaced URLs\n-------------------------\n\nWhen given a namespaced URL (e.g. ``'polls:index'``) to resolve, Django splits\nthe fully qualified name into parts and then tries the following lookup:\n\n#. First, Django looks for a matching :term:`application namespace` (in this\n   example, ``'polls'``). This will yield a list of instances of that\n   application.\n\n#. If there is a current application defined, Django finds and returns the URL\n   resolver for that instance. The current application can be specified with\n   the ``current_app`` argument to the :func:`~django.urls.reverse()`\n   function.\n\n   The :ttag:`url` template tag uses the namespace of the currently resolved\n   view as the current application in a\n   :class:`~django.template.RequestContext`. You can override this default by\n   setting the current application on the :attr:`request.current_app\n   <django.http.HttpRequest.current_app>` attribute.\n\n#. If there is no current application, Django looks for a default\n   application instance. The default application instance is the instance\n   that has an :term:`instance namespace` matching the :term:`application\n   namespace` (in this example, an instance of ``polls`` called ``'polls'``).\n\n#. If there is no default application instance, Django will pick the last\n   deployed instance of the application, whatever its instance name may be.\n\n#. If the provided namespace doesn't match an :term:`application namespace` in\n   step 1, Django will attempt a direct lookup of the namespace as an\n   :term:`instance namespace`.\n\nIf there are nested namespaces, these steps are repeated for each part of the\nnamespace until only the view name is unresolved. The view name will then be\nresolved into a URL in the namespace that has been found.\n\nExample\n~~~~~~~\n\nTo show this resolution strategy in action, consider an example of two instances\nof the ``polls`` application from the tutorial: one called ``'author-polls'``\nand one called ``'publisher-polls'``. Assume we have enhanced that application\nso that it takes the instance namespace into consideration when creating and\ndisplaying polls.\n\n.. code-block:: python\n    :caption: urls.py\n\n    from django.urls import include, path\n\n    urlpatterns = [\n        path('author-polls/', include('polls.urls', namespace='author-polls')),\n        path('publisher-polls/', include('polls.urls', namespace='publisher-polls')),\n    ]\n\n.. code-block:: python\n    :caption: polls/urls.py\n\n    from django.urls import path\n\n    from . import views\n\n    app_name = 'polls'\n    urlpatterns = [\n        path('', views.IndexView.as_view(), name='index'),\n        path('<int:pk>/', views.DetailView.as_view(), name='detail'),\n        ...\n    ]\n\nUsing this setup, the following lookups are possible:\n\n* If one of the instances is current - say, if we were rendering the detail page\n  in the instance ``'author-polls'`` - ``'polls:index'`` will resolve to the\n  index page of the ``'author-polls'`` instance; i.e. both of the following will\n  result in ``\"/author-polls/\"``.\n\n  In the method of a class-based view::\n\n    reverse('polls:index', current_app=self.request.resolver_match.namespace)\n\n  and in the template:\n\n  .. code-block:: html+django\n\n    {% url 'polls:index' %}\n\n* If there is no current instance - say, if we were rendering a page\n  somewhere else on the site - ``'polls:index'`` will resolve to the last\n  registered instance of ``polls``. Since there is no default instance\n  (instance namespace of ``'polls'``), the last instance of ``polls`` that is\n  registered will be used. This would be ``'publisher-polls'`` since it's\n  declared last in the ``urlpatterns``.\n\n* ``'author-polls:index'`` will always resolve to the index page of the instance\n  ``'author-polls'`` (and likewise for ``'publisher-polls'``) .\n\nIf there were also a default instance - i.e., an instance named ``'polls'`` -\nthe only change from above would be in the case where there is no current\ninstance (the second item in the list above). In this case ``'polls:index'``\nwould resolve to the index page of the default instance instead of the instance\ndeclared last in ``urlpatterns``.\n\n.. _namespaces-and-include:\n\nURL namespaces and included URLconfs\n------------------------------------\n\nApplication namespaces of included URLconfs can be specified in two ways.\n\nFirstly, you can set an ``app_name`` attribute in the included URLconf module,\nat the same level as the ``urlpatterns`` attribute. You have to pass the actual\nmodule, or a string reference to the module, to :func:`~django.urls.include`,\nnot the list of ``urlpatterns`` itself.\n\n.. code-block:: python\n    :caption: polls/urls.py\n\n    from django.urls import path\n\n    from . import views\n\n    app_name = 'polls'\n    urlpatterns = [\n        path('', views.IndexView.as_view(), name='index'),\n        path('<int:pk>/', views.DetailView.as_view(), name='detail'),\n        ...\n    ]\n\n.. code-block:: python\n    :caption: urls.py\n\n    from django.urls import include, path\n\n    urlpatterns = [\n        path('polls/', include('polls.urls')),\n    ]\n\nThe URLs defined in ``polls.urls`` will have an application namespace ``polls``.\n\nSecondly, you can include an object that contains embedded namespace data. If\nyou ``include()`` a list of :func:`~django.urls.path` or\n:func:`~django.urls.re_path` instances, the URLs contained in that object\nwill be added to the global namespace. However, you can also ``include()`` a\n2-tuple containing::\n\n    (<list of path()/re_path() instances>, <application namespace>)\n\nFor example::\n\n    from django.urls import include, path\n\n    from . import views\n\n    polls_patterns = ([\n        path('', views.IndexView.as_view(), name='index'),\n        path('<int:pk>/', views.DetailView.as_view(), name='detail'),\n    ], 'polls')\n\n    urlpatterns = [\n        path('polls/', include(polls_patterns)),\n    ]\n\nThis will include the nominated URL patterns into the given application\nnamespace.\n\nThe instance namespace can be specified using the ``namespace`` argument to\n:func:`~django.urls.include`. If the instance namespace is not specified,\nit will default to the included URLconf's application namespace. This means\nit will also be the default instance for that namespace.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":312,"nodeType":"TextFile","repoName":null,"name":"formsets.txt","path":"docs/topics/forms","text":"========\nFormsets\n========\n\n.. currentmodule:: django.forms.formsets\n\n.. class:: BaseFormSet\n\nA formset is a layer of abstraction to work with multiple forms on the same\npage. It can be best compared to a data grid. Let's say you have the following\nform::\n\n    >>> from django import forms\n    >>> class ArticleForm(forms.Form):\n    ...     title = forms.CharField()\n    ...     pub_date = forms.DateField()\n\nYou might want to allow the user to create several articles at once. To create\na formset out of an ``ArticleForm`` you would do::\n\n    >>> from django.forms import formset_factory\n    >>> ArticleFormSet = formset_factory(ArticleForm)\n\nYou now have created a formset class named ``ArticleFormSet``.\nInstantiating the formset gives you the ability to iterate over the forms \nin the formset and display them as you would with a regular form::\n\n    >>> formset = ArticleFormSet()\n    >>> for form in formset:\n    ...     print(form.as_table())\n    <tr><th><label for=\"id_form-0-title\">Title:</label></th><td><input type=\"text\" name=\"form-0-title\" id=\"id_form-0-title\"></td></tr>\n    <tr><th><label for=\"id_form-0-pub_date\">Pub date:</label></th><td><input type=\"text\" name=\"form-0-pub_date\" id=\"id_form-0-pub_date\"></td></tr>\n\nAs you can see it only displayed one empty form. The number of empty forms\nthat is displayed is controlled by the ``extra`` parameter. By default,\n:func:`~django.forms.formsets.formset_factory` defines one extra form; the\nfollowing example will create a formset class to display two blank forms::\n\n    >>> ArticleFormSet = formset_factory(ArticleForm, extra=2)\n\nIterating over a formset will render the forms in the order they were\ncreated. You can change this order by providing an alternate implementation for\nthe ``__iter__()`` method.\n\nFormsets can also be indexed into, which returns the corresponding form. If you\noverride ``__iter__``, you will need to also override ``__getitem__`` to have\nmatching behavior.\n\n.. _formsets-initial-data:\n\nUsing initial data with a formset\n=================================\n\nInitial data is what drives the main usability of a formset. As shown above\nyou can define the number of extra forms. What this means is that you are\ntelling the formset how many additional forms to show in addition to the\nnumber of forms it generates from the initial data. Let's take a look at an\nexample::\n\n    >>> import datetime\n    >>> from django.forms import formset_factory\n    >>> from myapp.forms import ArticleForm\n    >>> ArticleFormSet = formset_factory(ArticleForm, extra=2)\n    >>> formset = ArticleFormSet(initial=[\n    ...     {'title': 'Django is now open source',\n    ...      'pub_date': datetime.date.today(),}\n    ... ])\n\n    >>> for form in formset:\n    ...     print(form.as_table())\n    <tr><th><label for=\"id_form-0-title\">Title:</label></th><td><input type=\"text\" name=\"form-0-title\" value=\"Django is now open source\" id=\"id_form-0-title\"></td></tr>\n    <tr><th><label for=\"id_form-0-pub_date\">Pub date:</label></th><td><input type=\"text\" name=\"form-0-pub_date\" value=\"2008-05-12\" id=\"id_form-0-pub_date\"></td></tr>\n    <tr><th><label for=\"id_form-1-title\">Title:</label></th><td><input type=\"text\" name=\"form-1-title\" id=\"id_form-1-title\"></td></tr>\n    <tr><th><label for=\"id_form-1-pub_date\">Pub date:</label></th><td><input type=\"text\" name=\"form-1-pub_date\" id=\"id_form-1-pub_date\"></td></tr>\n    <tr><th><label for=\"id_form-2-title\">Title:</label></th><td><input type=\"text\" name=\"form-2-title\" id=\"id_form-2-title\"></td></tr>\n    <tr><th><label for=\"id_form-2-pub_date\">Pub date:</label></th><td><input type=\"text\" name=\"form-2-pub_date\" id=\"id_form-2-pub_date\"></td></tr>\n\nThere are now a total of three forms showing above. One for the initial data\nthat was passed in and two extra forms. Also note that we are passing in a\nlist of dictionaries as the initial data.\n\nIf you use an ``initial`` for displaying a formset, you should pass the same\n``initial`` when processing that formset's submission so that the formset can\ndetect which forms were changed by the user. For example, you might have\nsomething like: ``ArticleFormSet(request.POST, initial=[...])``.\n\n.. seealso::\n\n    :ref:`Creating formsets from models with model formsets <model-formsets>`.\n\n.. _formsets-max-num:\n\nLimiting the maximum number of forms\n====================================\n\nThe ``max_num`` parameter to :func:`~django.forms.formsets.formset_factory`\ngives you the ability to limit the number of forms the formset will display::\n\n    >>> from django.forms import formset_factory\n    >>> from myapp.forms import ArticleForm\n    >>> ArticleFormSet = formset_factory(ArticleForm, extra=2, max_num=1)\n    >>> formset = ArticleFormSet()\n    >>> for form in formset:\n    ...     print(form.as_table())\n    <tr><th><label for=\"id_form-0-title\">Title:</label></th><td><input type=\"text\" name=\"form-0-title\" id=\"id_form-0-title\"></td></tr>\n    <tr><th><label for=\"id_form-0-pub_date\">Pub date:</label></th><td><input type=\"text\" name=\"form-0-pub_date\" id=\"id_form-0-pub_date\"></td></tr>\n\nIf the value of ``max_num`` is greater than the number of existing items in the\ninitial data, up to ``extra`` additional blank forms will be added to the\nformset, so long as the total number of forms does not exceed ``max_num``. For\nexample, if ``extra=2`` and ``max_num=2`` and the formset is initialized with\none ``initial`` item, a form for the initial item and one blank form will be\ndisplayed.\n\nIf the number of items in the initial data exceeds ``max_num``, all initial\ndata forms will be displayed regardless of the value of ``max_num`` and no\nextra forms will be displayed. For example, if ``extra=3`` and ``max_num=1``\nand the formset is initialized with two initial items, two forms with the\ninitial data will be displayed.\n\nA ``max_num`` value of ``None`` (the default) puts a high limit on the number\nof forms displayed (1000). In practice this is equivalent to no limit.\n\nBy default, ``max_num`` only affects how many forms are displayed and does not\naffect validation.  If ``validate_max=True`` is passed to the\n:func:`~django.forms.formsets.formset_factory`, then ``max_num`` will affect\nvalidation.  See :ref:`validate_max`.\n\nFormset validation\n==================\n\nValidation with a formset is almost identical to a regular ``Form``. There is\nan ``is_valid`` method on the formset to provide a convenient way to validate\nall forms in the formset::\n\n    >>> from django.forms import formset_factory\n    >>> from myapp.forms import ArticleForm\n    >>> ArticleFormSet = formset_factory(ArticleForm)\n    >>> data = {\n    ...     'form-TOTAL_FORMS': '1',\n    ...     'form-INITIAL_FORMS': '0',\n    ...     'form-MAX_NUM_FORMS': '',\n    ... }\n    >>> formset = ArticleFormSet(data)\n    >>> formset.is_valid()\n    True\n\nWe passed in no data to the formset which is resulting in a valid form. The\nformset is smart enough to ignore extra forms that were not changed. If we\nprovide an invalid article::\n\n    >>> data = {\n    ...     'form-TOTAL_FORMS': '2',\n    ...     'form-INITIAL_FORMS': '0',\n    ...     'form-MAX_NUM_FORMS': '',\n    ...     'form-0-title': 'Test',\n    ...     'form-0-pub_date': '1904-06-16',\n    ...     'form-1-title': 'Test',\n    ...     'form-1-pub_date': '', # <-- this date is missing but required\n    ... }\n    >>> formset = ArticleFormSet(data)\n    >>> formset.is_valid()\n    False\n    >>> formset.errors\n    [{}, {'pub_date': ['This field is required.']}]\n\nAs we can see, ``formset.errors`` is a list whose entries correspond to the\nforms in the formset. Validation was performed for each of the two forms, and\nthe expected error message appears for the second item.\n\nJust like when using a normal ``Form``, each field in a formset's forms may\ninclude HTML attributes such as ``maxlength`` for browser validation. However,\nform fields of formsets won't include the ``required`` attribute as that\nvalidation may be incorrect when adding and deleting forms.\n\n.. method:: BaseFormSet.total_error_count()\n\nTo check how many errors there are in the formset, we can use the\n``total_error_count`` method::\n\n    >>> # Using the previous example\n    >>> formset.errors\n    [{}, {'pub_date': ['This field is required.']}]\n    >>> len(formset.errors)\n    2\n    >>> formset.total_error_count()\n    1\n\nWe can also check if form data differs from the initial data (i.e. the form was\nsent without any data)::\n\n    >>> data = {\n    ...     'form-TOTAL_FORMS': '1',\n    ...     'form-INITIAL_FORMS': '0',\n    ...     'form-MAX_NUM_FORMS': '',\n    ...     'form-0-title': '',\n    ...     'form-0-pub_date': '',\n    ... }\n    >>> formset = ArticleFormSet(data)\n    >>> formset.has_changed()\n    False\n\n.. _understanding-the-managementform:\n\nUnderstanding the ``ManagementForm``\n------------------------------------\n\nYou may have noticed the additional data (``form-TOTAL_FORMS``,\n``form-INITIAL_FORMS`` and ``form-MAX_NUM_FORMS``) that was required\nin the formset's data above. This data is required for the\n``ManagementForm``. This form is used by the formset to manage the\ncollection of forms contained in the formset. If you don't provide\nthis management data, an exception will be raised::\n\n    >>> data = {\n    ...     'form-0-title': 'Test',\n    ...     'form-0-pub_date': '',\n    ... }\n    >>> formset = ArticleFormSet(data)\n    >>> formset.is_valid()\n    Traceback (most recent call last):\n    ...\n    django.core.exceptions.ValidationError: ['ManagementForm data is missing or has been tampered with']\n\nIt is used to keep track of how many form instances are being displayed. If\nyou are adding new forms via JavaScript, you should increment the count fields\nin this form as well. On the other hand, if you are using JavaScript to allow\ndeletion of existing objects, then you need to ensure the ones being removed\nare properly marked for deletion by including ``form-#-DELETE`` in the ``POST``\ndata. It is expected that all forms are present in the ``POST`` data regardless.\n\nThe management form is available as an attribute of the formset\nitself. When rendering a formset in a template, you can include all\nthe management data by rendering ``{{ my_formset.management_form }}``\n(substituting the name of your formset as appropriate).\n\n``total_form_count`` and ``initial_form_count``\n-----------------------------------------------\n\n``BaseFormSet`` has a couple of methods that are closely related to the\n``ManagementForm``, ``total_form_count`` and ``initial_form_count``.\n\n``total_form_count`` returns the total number of forms in this formset.\n``initial_form_count`` returns the number of forms in the formset that were\npre-filled, and is also used to determine how many forms are required. You\nwill probably never need to override either of these methods, so please be\nsure you understand what they do before doing so.\n\n.. _empty_form:\n\n``empty_form``\n--------------\n\n``BaseFormSet`` provides an additional attribute ``empty_form`` which returns\na form instance with a prefix of ``__prefix__`` for easier use in dynamic\nforms with JavaScript.\n\nCustom formset validation\n-------------------------\n\nA formset has a ``clean`` method similar to the one on a ``Form`` class. This\nis where you define your own validation that works at the formset level::\n\n    >>> from django.core.exceptions import ValidationError\n    >>> from django.forms import BaseFormSet\n    >>> from django.forms import formset_factory\n    >>> from myapp.forms import ArticleForm\n\n    >>> class BaseArticleFormSet(BaseFormSet):\n    ...     def clean(self):\n    ...         \"\"\"Checks that no two articles have the same title.\"\"\"\n    ...         if any(self.errors):\n    ...             # Don't bother validating the formset unless each form is valid on its own\n    ...             return\n    ...         titles = []\n    ...         for form in self.forms:\n    ...             if self.can_delete and self._should_delete_form(form):\n    ...                 continue\n    ...             title = form.cleaned_data.get('title')\n    ...             if title in titles:\n    ...                 raise ValidationError(\"Articles in a set must have distinct titles.\")\n    ...             titles.append(title)\n\n    >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet)\n    >>> data = {\n    ...     'form-TOTAL_FORMS': '2',\n    ...     'form-INITIAL_FORMS': '0',\n    ...     'form-MAX_NUM_FORMS': '',\n    ...     'form-0-title': 'Test',\n    ...     'form-0-pub_date': '1904-06-16',\n    ...     'form-1-title': 'Test',\n    ...     'form-1-pub_date': '1912-06-23',\n    ... }\n    >>> formset = ArticleFormSet(data)\n    >>> formset.is_valid()\n    False\n    >>> formset.errors\n    [{}, {}]\n    >>> formset.non_form_errors()\n    ['Articles in a set must have distinct titles.']\n\nThe formset ``clean`` method is called after all the ``Form.clean`` methods\nhave been called. The errors will be found using the ``non_form_errors()``\nmethod on the formset.\n\nValidating the number of forms in a formset\n===========================================\n\nDjango provides a couple ways to validate the minimum or maximum number of\nsubmitted forms. Applications which need more customizable validation of the\nnumber of forms should use custom formset validation.\n\n.. _validate_max:\n\n``validate_max``\n----------------\n\nIf ``validate_max=True`` is passed to\n:func:`~django.forms.formsets.formset_factory`, validation will also check\nthat the number of forms in the data set, minus those marked for\ndeletion, is less than or equal to ``max_num``.\n\n    >>> from django.forms import formset_factory\n    >>> from myapp.forms import ArticleForm\n    >>> ArticleFormSet = formset_factory(ArticleForm, max_num=1, validate_max=True)\n    >>> data = {\n    ...     'form-TOTAL_FORMS': '2',\n    ...     'form-INITIAL_FORMS': '0',\n    ...     'form-MIN_NUM_FORMS': '',\n    ...     'form-MAX_NUM_FORMS': '',\n    ...     'form-0-title': 'Test',\n    ...     'form-0-pub_date': '1904-06-16',\n    ...     'form-1-title': 'Test 2',\n    ...     'form-1-pub_date': '1912-06-23',\n    ... }\n    >>> formset = ArticleFormSet(data)\n    >>> formset.is_valid()\n    False\n    >>> formset.errors\n    [{}, {}]\n    >>> formset.non_form_errors()\n    ['Please submit 1 or fewer forms.']\n\n``validate_max=True`` validates against ``max_num`` strictly even if\n``max_num`` was exceeded because the amount of initial data supplied was\nexcessive.\n\n.. note::\n\n    Regardless of ``validate_max``, if the number of forms in a data set\n    exceeds ``max_num`` by more than 1000, then the form will fail to validate\n    as if ``validate_max`` were set, and additionally only the first 1000\n    forms above ``max_num`` will be validated.  The remainder will be\n    truncated entirely.  This is to protect against memory exhaustion attacks\n    using forged POST requests.\n\n``validate_min``\n----------------\n\nIf ``validate_min=True`` is passed to\n:func:`~django.forms.formsets.formset_factory`, validation will also check\nthat the number of forms in the data set, minus those marked for\ndeletion, is greater than or equal to ``min_num``.\n\n    >>> from django.forms import formset_factory\n    >>> from myapp.forms import ArticleForm\n    >>> ArticleFormSet = formset_factory(ArticleForm, min_num=3, validate_min=True)\n    >>> data = {\n    ...     'form-TOTAL_FORMS': '2',\n    ...     'form-INITIAL_FORMS': '0',\n    ...     'form-MIN_NUM_FORMS': '',\n    ...     'form-MAX_NUM_FORMS': '',\n    ...     'form-0-title': 'Test',\n    ...     'form-0-pub_date': '1904-06-16',\n    ...     'form-1-title': 'Test 2',\n    ...     'form-1-pub_date': '1912-06-23',\n    ... }\n    >>> formset = ArticleFormSet(data)\n    >>> formset.is_valid()\n    False\n    >>> formset.errors\n    [{}, {}]\n    >>> formset.non_form_errors()\n    ['Please submit 3 or more forms.']\n\nDealing with ordering and deletion of forms\n===========================================\n\nThe :func:`~django.forms.formsets.formset_factory` provides two optional\nparameters ``can_order`` and ``can_delete`` to help with ordering of forms in\nformsets and deletion of forms from a formset.\n\n``can_order``\n-------------\n\n.. attribute:: BaseFormSet.can_order\n\nDefault: ``False``\n\nLets you create a formset with the ability to order::\n\n    >>> from django.forms import formset_factory\n    >>> from myapp.forms import ArticleForm\n    >>> ArticleFormSet = formset_factory(ArticleForm, can_order=True)\n    >>> formset = ArticleFormSet(initial=[\n    ...     {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)},\n    ...     {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)},\n    ... ])\n    >>> for form in formset:\n    ...     print(form.as_table())\n    <tr><th><label for=\"id_form-0-title\">Title:</label></th><td><input type=\"text\" name=\"form-0-title\" value=\"Article #1\" id=\"id_form-0-title\"></td></tr>\n    <tr><th><label for=\"id_form-0-pub_date\">Pub date:</label></th><td><input type=\"text\" name=\"form-0-pub_date\" value=\"2008-05-10\" id=\"id_form-0-pub_date\"></td></tr>\n    <tr><th><label for=\"id_form-0-ORDER\">Order:</label></th><td><input type=\"number\" name=\"form-0-ORDER\" value=\"1\" id=\"id_form-0-ORDER\"></td></tr>\n    <tr><th><label for=\"id_form-1-title\">Title:</label></th><td><input type=\"text\" name=\"form-1-title\" value=\"Article #2\" id=\"id_form-1-title\"></td></tr>\n    <tr><th><label for=\"id_form-1-pub_date\">Pub date:</label></th><td><input type=\"text\" name=\"form-1-pub_date\" value=\"2008-05-11\" id=\"id_form-1-pub_date\"></td></tr>\n    <tr><th><label for=\"id_form-1-ORDER\">Order:</label></th><td><input type=\"number\" name=\"form-1-ORDER\" value=\"2\" id=\"id_form-1-ORDER\"></td></tr>\n    <tr><th><label for=\"id_form-2-title\">Title:</label></th><td><input type=\"text\" name=\"form-2-title\" id=\"id_form-2-title\"></td></tr>\n    <tr><th><label for=\"id_form-2-pub_date\">Pub date:</label></th><td><input type=\"text\" name=\"form-2-pub_date\" id=\"id_form-2-pub_date\"></td></tr>\n    <tr><th><label for=\"id_form-2-ORDER\">Order:</label></th><td><input type=\"number\" name=\"form-2-ORDER\" id=\"id_form-2-ORDER\"></td></tr>\n\nThis adds an additional field to each form. This new field is named ``ORDER``\nand is an ``forms.IntegerField``. For the forms that came from the initial\ndata it automatically assigned them a numeric value. Let's look at what will\nhappen when the user changes these values::\n\n    >>> data = {\n    ...     'form-TOTAL_FORMS': '3',\n    ...     'form-INITIAL_FORMS': '2',\n    ...     'form-MAX_NUM_FORMS': '',\n    ...     'form-0-title': 'Article #1',\n    ...     'form-0-pub_date': '2008-05-10',\n    ...     'form-0-ORDER': '2',\n    ...     'form-1-title': 'Article #2',\n    ...     'form-1-pub_date': '2008-05-11',\n    ...     'form-1-ORDER': '1',\n    ...     'form-2-title': 'Article #3',\n    ...     'form-2-pub_date': '2008-05-01',\n    ...     'form-2-ORDER': '0',\n    ... }\n\n    >>> formset = ArticleFormSet(data, initial=[\n    ...     {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)},\n    ...     {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)},\n    ... ])\n    >>> formset.is_valid()\n    True\n    >>> for form in formset.ordered_forms:\n    ...     print(form.cleaned_data)\n    {'pub_date': datetime.date(2008, 5, 1), 'ORDER': 0, 'title': 'Article #3'}\n    {'pub_date': datetime.date(2008, 5, 11), 'ORDER': 1, 'title': 'Article #2'}\n    {'pub_date': datetime.date(2008, 5, 10), 'ORDER': 2, 'title': 'Article #1'}\n\n:class:`~django.forms.formsets.BaseFormSet` also provides an\n:attr:`~django.forms.formsets.BaseFormSet.ordering_widget` attribute and\n:meth:`~django.forms.formsets.BaseFormSet.get_ordering_widget` method that\ncontrol the widget used with\n:attr:`~django.forms.formsets.BaseFormSet.can_order`.\n\n``ordering_widget``\n^^^^^^^^^^^^^^^^^^^\n\n.. attribute:: BaseFormSet.ordering_widget\n\nDefault: :class:`~django.forms.NumberInput`\n\nSet ``ordering_widget`` to specify the widget class to be used with\n``can_order``::\n\n    >>> from django.forms import BaseFormSet, formset_factory\n    >>> from myapp.forms import ArticleForm\n    >>> class BaseArticleFormSet(BaseFormSet):\n    ...     ordering_widget = HiddenInput\n\n    >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, can_order=True)\n\n``get_ordering_widget``\n^^^^^^^^^^^^^^^^^^^^^^^\n\n.. method:: BaseFormSet.get_ordering_widget()\n\nOverride ``get_ordering_widget()`` if you need to provide a widget instance for\nuse with ``can_order``::\n\n    >>> from django.forms import BaseFormSet, formset_factory\n    >>> from myapp.forms import ArticleForm\n    >>> class BaseArticleFormSet(BaseFormSet):\n    ...     def get_ordering_widget(self):\n    ...         return HiddenInput(attrs={'class': 'ordering'})\n\n    >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, can_order=True)\n\n``can_delete``\n--------------\n\n.. attribute:: BaseFormSet.can_delete\n\nDefault: ``False``\n\nLets you create a formset with the ability to select forms for deletion::\n\n    >>> from django.forms import formset_factory\n    >>> from myapp.forms import ArticleForm\n    >>> ArticleFormSet = formset_factory(ArticleForm, can_delete=True)\n    >>> formset = ArticleFormSet(initial=[\n    ...     {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)},\n    ...     {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)},\n    ... ])\n    >>> for form in formset:\n    ...     print(form.as_table())\n    <tr><th><label for=\"id_form-0-title\">Title:</label></th><td><input type=\"text\" name=\"form-0-title\" value=\"Article #1\" id=\"id_form-0-title\"></td></tr>\n    <tr><th><label for=\"id_form-0-pub_date\">Pub date:</label></th><td><input type=\"text\" name=\"form-0-pub_date\" value=\"2008-05-10\" id=\"id_form-0-pub_date\"></td></tr>\n    <tr><th><label for=\"id_form-0-DELETE\">Delete:</label></th><td><input type=\"checkbox\" name=\"form-0-DELETE\" id=\"id_form-0-DELETE\"></td></tr>\n    <tr><th><label for=\"id_form-1-title\">Title:</label></th><td><input type=\"text\" name=\"form-1-title\" value=\"Article #2\" id=\"id_form-1-title\"></td></tr>\n    <tr><th><label for=\"id_form-1-pub_date\">Pub date:</label></th><td><input type=\"text\" name=\"form-1-pub_date\" value=\"2008-05-11\" id=\"id_form-1-pub_date\"></td></tr>\n    <tr><th><label for=\"id_form-1-DELETE\">Delete:</label></th><td><input type=\"checkbox\" name=\"form-1-DELETE\" id=\"id_form-1-DELETE\"></td></tr>\n    <tr><th><label for=\"id_form-2-title\">Title:</label></th><td><input type=\"text\" name=\"form-2-title\" id=\"id_form-2-title\"></td></tr>\n    <tr><th><label for=\"id_form-2-pub_date\">Pub date:</label></th><td><input type=\"text\" name=\"form-2-pub_date\" id=\"id_form-2-pub_date\"></td></tr>\n    <tr><th><label for=\"id_form-2-DELETE\">Delete:</label></th><td><input type=\"checkbox\" name=\"form-2-DELETE\" id=\"id_form-2-DELETE\"></td></tr>\n\nSimilar to ``can_order`` this adds a new field to each form named ``DELETE``\nand is a ``forms.BooleanField``. When data comes through marking any of the\ndelete fields you can access them with ``deleted_forms``::\n\n    >>> data = {\n    ...     'form-TOTAL_FORMS': '3',\n    ...     'form-INITIAL_FORMS': '2',\n    ...     'form-MAX_NUM_FORMS': '',\n    ...     'form-0-title': 'Article #1',\n    ...     'form-0-pub_date': '2008-05-10',\n    ...     'form-0-DELETE': 'on',\n    ...     'form-1-title': 'Article #2',\n    ...     'form-1-pub_date': '2008-05-11',\n    ...     'form-1-DELETE': '',\n    ...     'form-2-title': '',\n    ...     'form-2-pub_date': '',\n    ...     'form-2-DELETE': '',\n    ... }\n\n    >>> formset = ArticleFormSet(data, initial=[\n    ...     {'title': 'Article #1', 'pub_date': datetime.date(2008, 5, 10)},\n    ...     {'title': 'Article #2', 'pub_date': datetime.date(2008, 5, 11)},\n    ... ])\n    >>> [form.cleaned_data for form in formset.deleted_forms]\n    [{'DELETE': True, 'pub_date': datetime.date(2008, 5, 10), 'title': 'Article #1'}]\n\nIf you are using a :class:`ModelFormSet<django.forms.models.BaseModelFormSet>`,\nmodel instances for deleted forms will be deleted when you call\n``formset.save()``.\n\nIf you call ``formset.save(commit=False)``, objects will not be deleted\nautomatically.  You'll need to call ``delete()`` on each of the\n:attr:`formset.deleted_objects\n<django.forms.models.BaseModelFormSet.deleted_objects>` to actually delete\nthem::\n\n    >>> instances = formset.save(commit=False)\n    >>> for obj in formset.deleted_objects:\n    ...     obj.delete()\n\nOn the other hand, if you are using a plain ``FormSet``, it's up to you to\nhandle ``formset.deleted_forms``, perhaps in your formset's ``save()`` method,\nas there's no general notion of what it means to delete a form.\n\nAdding additional fields to a formset\n=====================================\n\nIf you need to add additional fields to the formset this can be easily\naccomplished. The formset base class provides an ``add_fields`` method. You\ncan override this method to add your own fields or even redefine the default\nfields/attributes of the order and deletion fields::\n\n    >>> from django.forms import BaseFormSet\n    >>> from django.forms import formset_factory\n    >>> from myapp.forms import ArticleForm\n    >>> class BaseArticleFormSet(BaseFormSet):\n    ...     def add_fields(self, form, index):\n    ...         super().add_fields(form, index)\n    ...         form.fields[\"my_field\"] = forms.CharField()\n\n    >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet)\n    >>> formset = ArticleFormSet()\n    >>> for form in formset:\n    ...     print(form.as_table())\n    <tr><th><label for=\"id_form-0-title\">Title:</label></th><td><input type=\"text\" name=\"form-0-title\" id=\"id_form-0-title\"></td></tr>\n    <tr><th><label for=\"id_form-0-pub_date\">Pub date:</label></th><td><input type=\"text\" name=\"form-0-pub_date\" id=\"id_form-0-pub_date\"></td></tr>\n    <tr><th><label for=\"id_form-0-my_field\">My field:</label></th><td><input type=\"text\" name=\"form-0-my_field\" id=\"id_form-0-my_field\"></td></tr>\n\n.. _custom-formset-form-kwargs:\n\nPassing custom parameters to formset forms\n==========================================\n\nSometimes your form class takes custom parameters, like ``MyArticleForm``.\nYou can pass this parameter when instantiating the formset::\n\n    >>> from django.forms import BaseFormSet\n    >>> from django.forms import formset_factory\n    >>> from myapp.forms import ArticleForm\n\n    >>> class MyArticleForm(ArticleForm):\n    ...     def __init__(self, *args, user, **kwargs):\n    ...         self.user = user\n    ...         super().__init__(*args, **kwargs)\n\n    >>> ArticleFormSet = formset_factory(MyArticleForm)\n    >>> formset = ArticleFormSet(form_kwargs={'user': request.user})\n\nThe ``form_kwargs`` may also depend on the specific form instance. The formset\nbase class provides a ``get_form_kwargs`` method. The method takes a single\nargument - the index of the form in the formset. The index is ``None`` for the\n:ref:`empty_form`::\n\n    >>> from django.forms import BaseFormSet\n    >>> from django.forms import formset_factory\n\n    >>> class BaseArticleFormSet(BaseFormSet):\n    ...     def get_form_kwargs(self, index):\n    ...         kwargs = super().get_form_kwargs(index)\n    ...         kwargs['custom_kwarg'] = index\n    ...         return kwargs\n\n.. _formset-prefix:\n\nCustomizing a formset's prefix\n==============================\n\nIn the rendered HTML, formsets include a prefix on each field's name. By\ndefault, the prefix is ``'form'``, but it can be customized using the formset's\n``prefix`` argument.\n\nFor example, in the default case, you might see:\n\n.. code-block:: html\n\n    <label for=\"id_form-0-title\">Title:</label>\n    <input type=\"text\" name=\"form-0-title\" id=\"id_form-0-title\">\n\nBut with ``ArticleFormset(prefix='article')`` that becomes:\n\n.. code-block:: html\n\n    <label for=\"id_article-0-title\">Title:</label>\n    <input type=\"text\" name=\"article-0-title\" id=\"id_article-0-title\">\n\nThis is useful if you want to :ref:`use more than one formset in a view\n<multiple-formsets-in-view>`.\n\nUsing a formset in views and templates\n======================================\n\nUsing a formset inside a view is not very different from using a regular\n``Form`` class. The only thing you will want to be aware of is making sure to\nuse the management form inside the template. Let's look at a sample view::\n\n    from django.forms import formset_factory\n    from django.shortcuts import render\n    from myapp.forms import ArticleForm\n\n    def manage_articles(request):\n        ArticleFormSet = formset_factory(ArticleForm)\n        if request.method == 'POST':\n            formset = ArticleFormSet(request.POST, request.FILES)\n            if formset.is_valid():\n                # do something with the formset.cleaned_data\n                pass\n        else:\n            formset = ArticleFormSet()\n        return render(request, 'manage_articles.html', {'formset': formset})\n\nThe ``manage_articles.html`` template might look like this:\n\n.. code-block:: html+django\n\n    <form method=\"post\">\n        {{ formset.management_form }}\n        <table>\n            {% for form in formset %}\n            {{ form }}\n            {% endfor %}\n        </table>\n    </form>\n\nHowever there's a slight shortcut for the above by letting the formset itself\ndeal with the management form:\n\n.. code-block:: html+django\n\n    <form method=\"post\">\n        <table>\n            {{ formset }}\n        </table>\n    </form>\n\nThe above ends up calling the ``as_table`` method on the formset class.\n\n.. _manually-rendered-can-delete-and-can-order:\n\nManually rendered ``can_delete`` and ``can_order``\n--------------------------------------------------\n\nIf you manually render fields in the template, you can render\n``can_delete`` parameter with ``{{ form.DELETE }}``:\n\n.. code-block:: html+django\n\n    <form method=\"post\">\n        {{ formset.management_form }}\n        {% for form in formset %}\n            <ul>\n                <li>{{ form.title }}</li>\n                <li>{{ form.pub_date }}</li>\n                {% if formset.can_delete %}\n                    <li>{{ form.DELETE }}</li>\n                {% endif %}\n            </ul>\n        {% endfor %}\n    </form>\n\n\nSimilarly, if the formset has the ability to order (``can_order=True``), it is\npossible to render it with ``{{ form.ORDER }}``.\n\n.. _multiple-formsets-in-view:\n\nUsing more than one formset in a view\n-------------------------------------\n\nYou are able to use more than one formset in a view if you like. Formsets\nborrow much of its behavior from forms. With that said you are able to use\n``prefix`` to prefix formset form field names with a given value to allow\nmore than one formset to be sent to a view without name clashing. Let's take\na look at how this might be accomplished::\n\n    from django.forms import formset_factory\n    from django.shortcuts import render\n    from myapp.forms import ArticleForm, BookForm\n\n    def manage_articles(request):\n        ArticleFormSet = formset_factory(ArticleForm)\n        BookFormSet = formset_factory(BookForm)\n        if request.method == 'POST':\n            article_formset = ArticleFormSet(request.POST, request.FILES, prefix='articles')\n            book_formset = BookFormSet(request.POST, request.FILES, prefix='books')\n            if article_formset.is_valid() and book_formset.is_valid():\n                # do something with the cleaned_data on the formsets.\n                pass\n        else:\n            article_formset = ArticleFormSet(prefix='articles')\n            book_formset = BookFormSet(prefix='books')\n        return render(request, 'manage_articles.html', {\n            'article_formset': article_formset,\n            'book_formset': book_formset,\n        })\n\nYou would then render the formsets as normal. It is important to point out\nthat you need to pass ``prefix`` on both the POST and non-POST cases so that\nit is rendered and processed correctly.\n\nEach formset's :ref:`prefix <formset-prefix>` replaces the default ``form``\nprefix that's added to each field's ``name`` and ``id`` HTML attributes.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":313,"nodeType":"TextFile","repoName":null,"name":"timezones.txt","path":"docs/topics/i18n","text":"==========\nTime zones\n==========\n\n.. _time-zones-overview:\n\nOverview\n========\n\nWhen support for time zones is enabled, Django stores datetime information in\nUTC in the database, uses time-zone-aware datetime objects internally, and\ntranslates them to the end user's time zone in templates and forms.\n\nThis is handy if your users live in more than one time zone and you want to\ndisplay datetime information according to each user's wall clock.\n\nEven if your website is available in only one time zone, it's still good\npractice to store data in UTC in your database. The main reason is Daylight\nSaving Time (DST). Many countries have a system of DST, where clocks are moved\nforward in spring and backward in autumn. If you're working in local time,\nyou're likely to encounter errors twice a year, when the transitions happen.\n(The pytz_ documentation discusses `these issues`_ in greater detail.) This\nprobably doesn't matter for your blog, but it's a problem if you over-bill or\nunder-bill your customers by one hour, twice a year, every year. The solution\nto this problem is to use UTC in the code and use local time only when\ninteracting with end users.\n\nTime zone support is disabled by default. To enable it, set :setting:`USE_TZ =\nTrue <USE_TZ>` in your settings file. Time zone support uses pytz_, which is\ninstalled when you install Django.\n\n.. note::\n\n    The default :file:`settings.py` file created by :djadmin:`django-admin\n    startproject <startproject>` includes :setting:`USE_TZ = True <USE_TZ>`\n    for convenience.\n\n.. note::\n\n    There is also an independent but related :setting:`USE_L10N` setting that\n    controls whether Django should activate format localization. See\n    :doc:`/topics/i18n/formatting` for more details.\n\nIf you're wrestling with a particular problem, start with the :ref:`time zone\nFAQ <time-zones-faq>`.\n\nConcepts\n========\n\n.. _naive_vs_aware_datetimes:\n\nNaive and aware datetime objects\n--------------------------------\n\nPython's :class:`datetime.datetime` objects have a ``tzinfo`` attribute that\ncan be used to store time zone information, represented as an instance of a\nsubclass of :class:`datetime.tzinfo`. When this attribute is set and describes\nan offset, a datetime object is **aware**. Otherwise, it's **naive**.\n\nYou can use :func:`~django.utils.timezone.is_aware` and\n:func:`~django.utils.timezone.is_naive` to determine whether datetimes are\naware or naive.\n\nWhen time zone support is disabled, Django uses naive datetime objects in local\ntime. This is sufficient for many use cases. In this mode, to obtain the\ncurrent time, you would write::\n\n    import datetime\n\n    now = datetime.datetime.now()\n\nWhen time zone support is enabled (:setting:`USE_TZ=True <USE_TZ>`), Django uses\ntime-zone-aware datetime objects. If your code creates datetime objects, they\nshould be aware too. In this mode, the example above becomes::\n\n    from django.utils import timezone\n\n    now = timezone.now()\n\n.. warning::\n\n    Dealing with aware datetime objects isn't always intuitive. For instance,\n    the ``tzinfo`` argument of the standard datetime constructor doesn't work\n    reliably for time zones with DST. Using UTC is generally safe; if you're\n    using other time zones, you should review the `pytz`_ documentation\n    carefully.\n\n.. note::\n\n    Python's :class:`datetime.time` objects also feature a ``tzinfo``\n    attribute, and PostgreSQL has a matching ``time with time zone`` type.\n    However, as PostgreSQL's docs put it, this type \"exhibits properties which\n    lead to questionable usefulness\".\n\n    Django only supports naive time objects and will raise an exception if you\n    attempt to save an aware time object, as a timezone for a time with no\n    associated date does not make sense.\n\n.. _naive-datetime-objects:\n\nInterpretation of naive datetime objects\n----------------------------------------\n\nWhen :setting:`USE_TZ` is ``True``, Django still accepts naive datetime\nobjects, in order to preserve backwards-compatibility. When the database layer\nreceives one, it attempts to make it aware by interpreting it in the\n:ref:`default time zone <default-current-time-zone>` and raises a warning.\n\nUnfortunately, during DST transitions, some datetimes don't exist or are\nambiguous. In such situations, pytz_ raises an exception. That's why you should\nalways create aware datetime objects when time zone support is enabled.\n\nIn practice, this is rarely an issue. Django gives you aware datetime objects\nin the models and forms, and most often, new datetime objects are created from\nexisting ones through :class:`~datetime.timedelta` arithmetic. The only\ndatetime that's often created in application code is the current time, and\n:func:`timezone.now() <django.utils.timezone.now>` automatically does the\nright thing.\n\n.. _default-current-time-zone:\n\nDefault time zone and current time zone\n---------------------------------------\n\nThe **default time zone** is the time zone defined by the :setting:`TIME_ZONE`\nsetting.\n\nThe **current time zone** is the time zone that's used for rendering.\n\nYou should set the current time zone to the end user's actual time zone with\n:func:`~django.utils.timezone.activate`. Otherwise, the default time zone is\nused.\n\n.. note::\n\n    As explained in the documentation of :setting:`TIME_ZONE`, Django sets\n    environment variables so that its process runs in the default time zone.\n    This happens regardless of the value of :setting:`USE_TZ` and of the\n    current time zone.\n\n    When :setting:`USE_TZ` is ``True``, this is useful to preserve\n    backwards-compatibility with applications that still rely on local time.\n    However, :ref:`as explained above <naive-datetime-objects>`, this isn't\n    entirely reliable, and you should always work with aware datetimes in UTC\n    in your own code. For instance, use :meth:`~datetime.datetime.fromtimestamp`\n    and set the ``tz`` parameter to :data:`~django.utils.timezone.utc`.\n\nSelecting the current time zone\n-------------------------------\n\nThe current time zone is the equivalent of the current :term:`locale <locale\nname>` for translations. However, there's no equivalent of the\n``Accept-Language`` HTTP header that Django could use to determine the user's\ntime zone automatically. Instead, Django provides :ref:`time zone selection\nfunctions <time-zone-selection-functions>`. Use them to build the time zone\nselection logic that makes sense for you.\n\nMost websites that care about time zones ask users in which time zone they live\nand store this information in the user's profile. For anonymous users, they use\nthe time zone of their primary audience or UTC. pytz_ provides helpers_, like a\nlist of time zones per country, that you can use to pre-select the most likely\nchoices.\n\nHere's an example that stores the current timezone in the session. (It skips\nerror handling entirely for the sake of simplicity.)\n\nAdd the following middleware to :setting:`MIDDLEWARE`::\n\n    import pytz\n\n    from django.utils import timezone\n\n    class TimezoneMiddleware:\n        def __init__(self, get_response):\n            self.get_response = get_response\n\n        def __call__(self, request):\n            tzname = request.session.get('django_timezone')\n            if tzname:\n                timezone.activate(pytz.timezone(tzname))\n            else:\n                timezone.deactivate()\n            return self.get_response(request)\n\nCreate a view that can set the current timezone::\n\n    from django.shortcuts import redirect, render\n\n    def set_timezone(request):\n        if request.method == 'POST':\n            request.session['django_timezone'] = request.POST['timezone']\n            return redirect('/')\n        else:\n            return render(request, 'template.html', {'timezones': pytz.common_timezones})\n\nInclude a form in ``template.html`` that will ``POST`` to this view:\n\n.. code-block:: html+django\n\n    {% load tz %}\n    {% get_current_timezone as TIME_ZONE %}\n    <form action=\"{% url 'set_timezone' %}\" method=\"POST\">\n        {% csrf_token %}\n        <label for=\"timezone\">Time zone:</label>\n        <select name=\"timezone\">\n            {% for tz in timezones %}\n            <option value=\"{{ tz }}\"{% if tz == TIME_ZONE %} selected{% endif %}>{{ tz }}</option>\n            {% endfor %}\n        </select>\n        <input type=\"submit\" value=\"Set\">\n    </form>\n\n.. _time-zones-in-forms:\n\nTime zone aware input in forms\n==============================\n\nWhen you enable time zone support, Django interprets datetimes entered in\nforms in the :ref:`current time zone <default-current-time-zone>` and returns\naware datetime objects in ``cleaned_data``.\n\nIf the current time zone raises an exception for datetimes that don't exist or\nare ambiguous because they fall in a DST transition (the timezones provided by\npytz_ do this), such datetimes will be reported as invalid values.\n\n.. _time-zones-in-templates:\n\nTime zone aware output in templates\n===================================\n\nWhen you enable time zone support, Django converts aware datetime objects to\nthe :ref:`current time zone <default-current-time-zone>` when they're rendered\nin templates. This behaves very much like :doc:`format localization\n</topics/i18n/formatting>`.\n\n.. warning::\n\n    Django doesn't convert naive datetime objects, because they could be\n    ambiguous, and because your code should never produce naive datetimes when\n    time zone support is enabled. However, you can force conversion with the\n    template filters described below.\n\nConversion to local time isn't always appropriate -- you may be generating\noutput for computers rather than for humans. The following filters and tags,\nprovided by the ``tz`` template tag library, allow you to control the time zone\nconversions.\n\n.. highlight:: html+django\n\nTemplate tags\n-------------\n\n.. templatetag:: localtime\n\n``localtime``\n~~~~~~~~~~~~~\n\nEnables or disables conversion of aware datetime objects to the current time\nzone in the contained block.\n\nThis tag has exactly the same effects as the :setting:`USE_TZ` setting as far\nas the template engine is concerned. It allows a more fine grained control of\nconversion.\n\nTo activate or deactivate conversion for a template block, use::\n\n    {% load tz %}\n\n    {% localtime on %}\n        {{ value }}\n    {% endlocaltime %}\n\n    {% localtime off %}\n        {{ value }}\n    {% endlocaltime %}\n\n.. note::\n\n    The value of :setting:`USE_TZ` isn't respected inside of a\n    ``{% localtime %}`` block.\n\n.. templatetag:: timezone\n\n``timezone``\n~~~~~~~~~~~~\n\nSets or unsets the current time zone in the contained block. When the current\ntime zone is unset, the default time zone applies.\n\n::\n\n    {% load tz %}\n\n    {% timezone \"Europe/Paris\" %}\n        Paris time: {{ value }}\n    {% endtimezone %}\n\n    {% timezone None %}\n        Server time: {{ value }}\n    {% endtimezone %}\n\n.. templatetag:: get_current_timezone\n\n``get_current_timezone``\n~~~~~~~~~~~~~~~~~~~~~~~~\n\nYou can get the name of the current time zone using the\n``get_current_timezone`` tag::\n\n    {% get_current_timezone as TIME_ZONE %}\n\nAlternatively, you can activate the\n:func:`~django.template.context_processors.tz` context processor and\nuse the ``TIME_ZONE`` context variable.\n\nTemplate filters\n----------------\n\nThese filters accept both aware and naive datetimes. For conversion purposes,\nthey assume that naive datetimes are in the default time zone. They always\nreturn aware datetimes.\n\n.. templatefilter:: localtime\n\n``localtime``\n~~~~~~~~~~~~~\n\nForces conversion of a single value to the current time zone.\n\nFor example::\n\n    {% load tz %}\n\n    {{ value|localtime }}\n\n.. templatefilter:: utc\n\n``utc``\n~~~~~~~\n\nForces conversion of a single value to UTC.\n\nFor example::\n\n    {% load tz %}\n\n    {{ value|utc }}\n\n.. templatefilter:: timezone\n\n``timezone``\n~~~~~~~~~~~~\n\nForces conversion of a single value to an arbitrary timezone.\n\nThe argument must be an instance of a :class:`~datetime.tzinfo` subclass or a\ntime zone name.\n\nFor example::\n\n    {% load tz %}\n\n    {{ value|timezone:\"Europe/Paris\" }}\n\n.. highlight:: python\n\n.. _time-zones-migration-guide:\n\nMigration guide\n===============\n\nHere's how to migrate a project that was started before Django supported time\nzones.\n\nDatabase\n--------\n\nPostgreSQL\n~~~~~~~~~~\n\nThe PostgreSQL backend stores datetimes as ``timestamp with time zone``. In\npractice, this means it converts datetimes from the connection's time zone to\nUTC on storage, and from UTC to the connection's time zone on retrieval.\n\nAs a consequence, if you're using PostgreSQL, you can switch between ``USE_TZ\n= False`` and ``USE_TZ = True`` freely. The database connection's time zone\nwill be set to :setting:`TIME_ZONE` or ``UTC`` respectively, so that Django\nobtains correct datetimes in all cases. You don't need to perform any data\nconversions.\n\nOther databases\n~~~~~~~~~~~~~~~\n\nOther backends store datetimes without time zone information. If you switch\nfrom ``USE_TZ = False`` to ``USE_TZ = True``, you must convert your data from\nlocal time to UTC -- which isn't deterministic if your local time has DST.\n\nCode\n----\n\nThe first step is to add :setting:`USE_TZ = True <USE_TZ>` to your settings\nfile. At this point, things should mostly work. If you create naive datetime\nobjects in your code, Django makes them aware when necessary.\n\nHowever, these conversions may fail around DST transitions, which means you\naren't getting the full benefits of time zone support yet. Also, you're likely\nto run into a few problems because it's impossible to compare a naive datetime\nwith an aware datetime. Since Django now gives you aware datetimes, you'll get\nexceptions wherever you compare a datetime that comes from a model or a form\nwith a naive datetime that you've created in your code.\n\nSo the second step is to refactor your code wherever you instantiate datetime\nobjects to make them aware. This can be done incrementally.\n:mod:`django.utils.timezone` defines some handy helpers for compatibility\ncode: :func:`~django.utils.timezone.now`,\n:func:`~django.utils.timezone.is_aware`,\n:func:`~django.utils.timezone.is_naive`,\n:func:`~django.utils.timezone.make_aware`, and\n:func:`~django.utils.timezone.make_naive`.\n\nFinally, in order to help you locate code that needs upgrading, Django raises\na warning when you attempt to save a naive datetime to the database::\n\n    RuntimeWarning: DateTimeField ModelName.field_name received a naive\n    datetime (2012-01-01 00:00:00) while time zone support is active.\n\nDuring development, you can turn such warnings into exceptions and get a\ntraceback by adding the following to your settings file::\n\n    import warnings\n    warnings.filterwarnings(\n        'error', r\"DateTimeField .* received a naive datetime\",\n        RuntimeWarning, r'django\\.db\\.models\\.fields',\n    )\n\nFixtures\n--------\n\nWhen serializing an aware datetime, the UTC offset is included, like this::\n\n    \"2011-09-01T13:20:30+03:00\"\n\nWhile for a naive datetime, it isn't::\n\n    \"2011-09-01T13:20:30\"\n\nFor models with :class:`~django.db.models.DateTimeField`\\ s, this difference\nmakes it impossible to write a fixture that works both with and without time\nzone support.\n\nFixtures generated with ``USE_TZ = False``, or before Django 1.4, use the\n\"naive\" format. If your project contains such fixtures, after you enable time\nzone support, you'll see :exc:`RuntimeWarning`\\ s when you load them. To get\nrid of the warnings, you must convert your fixtures to the \"aware\" format.\n\nYou can regenerate fixtures with :djadmin:`loaddata` then :djadmin:`dumpdata`.\nOr, if they're small enough, you can edit them to add the UTC offset that\nmatches your :setting:`TIME_ZONE` to each serialized datetime.\n\n.. _time-zones-faq:\n\nFAQ\n===\n\nSetup\n-----\n\n#. **I don't need multiple time zones. Should I enable time zone support?**\n\n   Yes. When time zone support is enabled, Django uses a more accurate model\n   of local time. This shields you from subtle and unreproducible bugs around\n   Daylight Saving Time (DST) transitions.\n\n   When you enable time zone support, you'll encounter some errors because\n   you're using naive datetimes where Django expects aware datetimes. Such\n   errors show up when running tests. You'll quickly learn how to avoid invalid\n   operations.\n\n   On the other hand, bugs caused by the lack of time zone support are much\n   harder to prevent, diagnose and fix. Anything that involves scheduled tasks\n   or datetime arithmetic is a candidate for subtle bugs that will bite you\n   only once or twice a year.\n\n   For these reasons, time zone support is enabled by default in new projects,\n   and you should keep it unless you have a very good reason not to.\n\n#. **I've enabled time zone support. Am I safe?**\n\n   Maybe. You're better protected from DST-related bugs, but you can still\n   shoot yourself in the foot by carelessly turning naive datetimes into aware\n   datetimes, and vice-versa.\n\n   If your application connects to other systems -- for instance, if it queries\n   a Web service -- make sure datetimes are properly specified. To transmit\n   datetimes safely, their representation should include the UTC offset, or\n   their values should be in UTC (or both!).\n\n   Finally, our calendar system contains interesting edge cases. For example,\n   you can't always subtract one year directly from a given date::\n\n       >>> import datetime\n       >>> def one_year_before(value):  # Wrong example.\n       ...     return value.replace(year=value.year - 1)\n       >>> one_year_before(datetime.datetime(2012, 3, 1, 10, 0))\n       datetime.datetime(2011, 3, 1, 10, 0)\n       >>> one_year_before(datetime.datetime(2012, 2, 29, 10, 0))\n       Traceback (most recent call last):\n       ...\n       ValueError: day is out of range for month\n\n   To implement such a function correctly, you must decide whether 2012-02-29\n   minus one year is 2011-02-28 or 2011-03-01, which depends on your business\n   requirements.\n\n#. **How do I interact with a database that stores datetimes in local time?**\n\n   Set the :setting:`TIME_ZONE <DATABASE-TIME_ZONE>` option to the appropriate\n   time zone for this database in the :setting:`DATABASES` setting.\n\n   This is useful for connecting to a database that doesn't support time zones\n   and that isn't managed by Django when :setting:`USE_TZ` is ``True``.\n\nTroubleshooting\n---------------\n\n#. **My application crashes with** ``TypeError: can't compare offset-naive``\n   ``and offset-aware datetimes`` **-- what's wrong?**\n\n   Let's reproduce this error by comparing a naive and an aware datetime::\n\n       >>> import datetime\n       >>> from django.utils import timezone\n       >>> naive = datetime.datetime.utcnow()\n       >>> aware = timezone.now()\n       >>> naive == aware\n       Traceback (most recent call last):\n       ...\n       TypeError: can't compare offset-naive and offset-aware datetimes\n\n   If you encounter this error, most likely your code is comparing these two\n   things:\n\n   - a datetime provided by Django -- for instance, a value read from a form or\n     a model field. Since you enabled time zone support, it's aware.\n   - a datetime generated by your code, which is naive (or you wouldn't be\n     reading this).\n\n   Generally, the correct solution is to change your code to use an aware\n   datetime instead.\n\n   If you're writing a pluggable application that's expected to work\n   independently of the value of :setting:`USE_TZ`, you may find\n   :func:`django.utils.timezone.now` useful. This function returns the current\n   date and time as a naive datetime when ``USE_TZ = False`` and as an aware\n   datetime when ``USE_TZ = True``. You can add or subtract\n   :class:`datetime.timedelta` as needed.\n\n#. **I see lots of** ``RuntimeWarning: DateTimeField received a naive\n   datetime`` ``(YYYY-MM-DD HH:MM:SS)`` ``while time zone support is active``\n   **-- is that bad?**\n\n   When time zone support is enabled, the database layer expects to receive\n   only aware datetimes from your code. This warning occurs when it receives a\n   naive datetime. This indicates that you haven't finished porting your code\n   for time zone support. Please refer to the :ref:`migration guide\n   <time-zones-migration-guide>` for tips on this process.\n\n   In the meantime, for backwards compatibility, the datetime is considered to\n   be in the default time zone, which is generally what you expect.\n\n#. ``now.date()`` **is yesterday! (or tomorrow)**\n\n   If you've always used naive datetimes, you probably believe that you can\n   convert a datetime to a date by calling its :meth:`~datetime.datetime.date`\n   method. You also consider that a :class:`~datetime.date` is a lot like a\n   :class:`~datetime.datetime`, except that it's less accurate.\n\n   None of this is true in a time zone aware environment::\n\n       >>> import datetime\n       >>> import pytz\n       >>> paris_tz = pytz.timezone(\"Europe/Paris\")\n       >>> new_york_tz = pytz.timezone(\"America/New_York\")\n       >>> paris = paris_tz.localize(datetime.datetime(2012, 3, 3, 1, 30))\n       # This is the correct way to convert between time zones with pytz.\n       >>> new_york = new_york_tz.normalize(paris.astimezone(new_york_tz))\n       >>> paris == new_york, paris.date() == new_york.date()\n       (True, False)\n       >>> paris - new_york, paris.date() - new_york.date()\n       (datetime.timedelta(0), datetime.timedelta(1))\n       >>> paris\n       datetime.datetime(2012, 3, 3, 1, 30, tzinfo=<DstTzInfo 'Europe/Paris' CET+1:00:00 STD>)\n       >>> new_york\n       datetime.datetime(2012, 3, 2, 19, 30, tzinfo=<DstTzInfo 'America/New_York' EST-1 day, 19:00:00 STD>)\n\n   As this example shows, the same datetime has a different date, depending on\n   the time zone in which it is represented. But the real problem is more\n   fundamental.\n\n   A datetime represents a **point in time**. It's absolute: it doesn't depend\n   on anything. On the contrary, a date is a **calendaring concept**. It's a\n   period of time whose bounds depend on the time zone in which the date is\n   considered. As you can see, these two concepts are fundamentally different,\n   and converting a datetime to a date isn't a deterministic operation.\n\n   What does this mean in practice?\n\n   Generally, you should avoid converting a :class:`~datetime.datetime` to\n   :class:`~datetime.date`. For instance, you can use the :tfilter:`date`\n   template filter to only show the date part of a datetime. This filter will\n   convert the datetime into the current time zone before formatting it,\n   ensuring the results appear correctly.\n\n   If you really need to do the conversion yourself, you must ensure the\n   datetime is converted to the appropriate time zone first. Usually, this\n   will be the current timezone::\n\n       >>> from django.utils import timezone\n       >>> timezone.activate(pytz.timezone(\"Asia/Singapore\"))\n       # For this example, we set the time zone to Singapore, but here's how\n       # you would obtain the current time zone in the general case.\n       >>> current_tz = timezone.get_current_timezone()\n       # Again, this is the correct way to convert between time zones with pytz.\n       >>> local = current_tz.normalize(paris.astimezone(current_tz))\n       >>> local\n       datetime.datetime(2012, 3, 3, 8, 30, tzinfo=<DstTzInfo 'Asia/Singapore' SGT+8:00:00 STD>)\n       >>> local.date()\n       datetime.date(2012, 3, 3)\n\n#. **I get an error** \"``Are time zone definitions for your database\n   installed?``\"\n\n   If you are using MySQL, see the :ref:`mysql-time-zone-definitions` section\n   of the MySQL notes for instructions on loading time zone definitions.\n\nUsage\n-----\n\n#. **I have a string** ``\"2012-02-21 10:28:45\"`` **and I know it's in the**\n   ``\"Europe/Helsinki\"`` **time zone. How do I turn that into an aware\n   datetime?**\n\n   This is exactly what pytz_ is for.\n\n       >>> from django.utils.dateparse import parse_datetime\n       >>> naive = parse_datetime(\"2012-02-21 10:28:45\")\n       >>> import pytz\n       >>> pytz.timezone(\"Europe/Helsinki\").localize(naive, is_dst=None)\n       datetime.datetime(2012, 2, 21, 10, 28, 45, tzinfo=<DstTzInfo 'Europe/Helsinki' EET+2:00:00 STD>)\n\n   Note that ``localize`` is a pytz extension to the :class:`~datetime.tzinfo`\n   API. Also, you may want to catch ``pytz.InvalidTimeError``. The\n   documentation of pytz contains `more examples`_. You should review it\n   before attempting to manipulate aware datetimes.\n\n#. **How can I obtain the local time in the current time zone?**\n\n   Well, the first question is, do you really need to?\n\n   You should only use local time when you're interacting with humans, and the\n   template layer provides :ref:`filters and tags <time-zones-in-templates>`\n   to convert datetimes to the time zone of your choice.\n\n   Furthermore, Python knows how to compare aware datetimes, taking into\n   account UTC offsets when necessary. It's much easier (and possibly faster)\n   to write all your model and view code in UTC. So, in most circumstances,\n   the datetime in UTC returned by :func:`django.utils.timezone.now` will be\n   sufficient.\n\n   For the sake of completeness, though, if you really want the local time\n   in the current time zone, here's how you can obtain it::\n\n       >>> from django.utils import timezone\n       >>> timezone.localtime(timezone.now())\n       datetime.datetime(2012, 3, 3, 20, 10, 53, 873365, tzinfo=<DstTzInfo 'Europe/Paris' CET+1:00:00 STD>)\n\n   In this example, the current time zone is ``\"Europe/Paris\"``.\n\n#. **How can I see all available time zones?**\n\n   pytz_ provides helpers_, including a list of current time zones and a list\n   of all available time zones -- some of which are only of historical\n   interest.\n\n.. _pytz: http://pytz.sourceforge.net/\n.. _more examples: http://pytz.sourceforge.net/#example-usage\n.. _these issues: http://pytz.sourceforge.net/#problems-with-localtime\n.. _helpers: http://pytz.sourceforge.net/#helpers\n.. _tz database: https://en.wikipedia.org/wiki/Tz_database\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":314,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/topics/forms","text":"==================\nWorking with forms\n==================\n\n.. currentmodule:: django.forms\n\n.. admonition:: About this document\n\n    This document provides an introduction to the basics of web forms and how\n    they are handled in Django. For a more detailed look at specific areas of\n    the forms API, see :doc:`/ref/forms/api`, :doc:`/ref/forms/fields`, and\n    :doc:`/ref/forms/validation`.\n\nUnless you're planning to build websites and applications that do nothing but\npublish content, and don't accept input from your visitors, you're going to\nneed to understand and use forms.\n\nDjango provides a range of tools and libraries to help you build forms to\naccept input from site visitors, and then process and respond to the input.\n\nHTML forms\n==========\n\nIn HTML, a form is a collection of elements inside ``<form>...</form>`` that\nallow a visitor to do things like enter text, select options, manipulate\nobjects or controls, and so on, and then send that information back to the\nserver.\n\nSome of these form interface elements - text input or checkboxes - are built\ninto HTML itself. Others are much more complex; an interface that pops up a\ndate picker or allows you to move a slider or manipulate controls will\ntypically use JavaScript and CSS as well as HTML form ``<input>`` elements to\nachieve these effects.\n\nAs well as its ``<input>`` elements, a form must specify two things:\n\n* *where*: the URL to which the data corresponding to the user's input should\n  be returned\n\n* *how*: the HTTP method the data should be returned by\n\nAs an example, the login form for the Django admin contains several\n``<input>`` elements: one of ``type=\"text\"`` for the username, one of\n``type=\"password\"`` for the password, and one of ``type=\"submit\"`` for the\n\"Log in\" button. It also contains some hidden text fields that the user\ndoesn't see, which Django uses to determine what to do next.\n\nIt also tells the browser that the form data should be sent to the URL\nspecified in the ``<form>``’s ``action`` attribute - ``/admin/`` - and that it\nshould be sent using the HTTP mechanism specified by the ``method`` attribute -\n``post``.\n\nWhen the ``<input type=\"submit\" value=\"Log in\">`` element is triggered, the\ndata is returned to ``/admin/``.\n\n``GET`` and ``POST``\n--------------------\n\n``GET`` and ``POST`` are the only HTTP methods to use when dealing with forms.\n\nDjango's login form is returned using the ``POST`` method, in which the browser\nbundles up the form data, encodes it for transmission, sends it to the server,\nand then receives back its response.\n\n``GET``, by contrast, bundles the submitted data into a string, and uses this\nto compose a URL. The URL contains the address where the data must be sent, as\nwell as the data keys and values. You can see this in action if you do a search\nin the Django documentation, which will produce a URL of the form\n``https://docs.djangoproject.com/search/?q=forms&release=1``.\n\n``GET`` and ``POST`` are typically used for different purposes.\n\nAny request that could be used to change the state of the system - for example,\na request that makes changes in the database - should use ``POST``. ``GET``\nshould be used only for requests that do not affect the state of the system.\n\n``GET`` would also be unsuitable for a password form, because the password\nwould appear in the URL, and thus, also in browser history and server logs,\nall in plain text. Neither would it be suitable for large quantities of data,\nor for binary data, such as an image. A Web application that uses ``GET``\nrequests for admin forms is a security risk: it can be easy for an attacker to\nmimic a form's request to gain access to sensitive parts of the system.\n``POST``, coupled with other protections like Django's :doc:`CSRF protection\n</ref/csrf/>` offers more control over access.\n\nOn the other hand, ``GET`` is suitable for things like a web search form,\nbecause the URLs that represent a ``GET`` request can easily be bookmarked,\nshared, or resubmitted.\n\nDjango's role in forms\n======================\n\nHandling forms is a complex business. Consider Django's admin, where numerous\nitems of data of several different types may need to be prepared for display in\na form, rendered as HTML, edited using a convenient interface, returned to the\nserver, validated and cleaned up, and then saved or passed on for further\nprocessing.\n\nDjango's form functionality can simplify and automate vast portions of this\nwork, and can also do it more securely than most programmers would be able to\ndo in code they wrote themselves.\n\nDjango handles three distinct parts of the work involved in forms:\n\n* preparing and restructuring data to make it ready for rendering\n* creating HTML forms for the data\n* receiving and processing submitted forms and data from the client\n\nIt is *possible* to write code that does all of this manually, but Django can\ntake care of it all for you.\n\nForms in Django\n===============\n\nWe've described HTML forms briefly, but an HTML ``<form>`` is just one part of\nthe machinery required.\n\nIn the context of a Web application, 'form' might refer to that HTML\n``<form>``, or to the Django :class:`Form` that produces it, or to the\nstructured data returned when it is submitted, or to the end-to-end working\ncollection of these parts.\n\nThe Django :class:`Form` class\n------------------------------\n\nAt the heart of this system of components is Django's :class:`Form` class. In\nmuch the same way that a Django model describes the logical structure of an\nobject, its behavior, and the way its parts are represented to us, a\n:class:`Form` class describes a form and determines how it works and appears.\n\nIn a similar way that a model class's fields map to database fields, a form\nclass's fields map to HTML form ``<input>`` elements. (A :class:`ModelForm`\nmaps a model class's fields to HTML form ``<input>`` elements via a\n:class:`Form`; this is what the Django admin is based upon.)\n\nA form's fields are themselves classes; they manage form data and perform\nvalidation when a form is submitted. A :class:`DateField` and a\n:class:`FileField` handle very different kinds of data and have to do\ndifferent things with it.\n\nA form field is represented to a user in the browser as an HTML \"widget\" - a\npiece of user interface machinery. Each field type has an appropriate default\n:doc:`Widget class </ref/forms/widgets/>`, but these can be overridden as\nrequired.\n\nInstantiating, processing, and rendering forms\n----------------------------------------------\n\nWhen rendering an object in Django, we generally:\n\n#. get hold of it in the view (fetch it from the database, for example)\n#. pass it to the template context\n#. expand it to HTML markup using template variables\n\nRendering a form in a template involves nearly the same work as rendering any\nother kind of object, but there are some key differences.\n\nIn the case of a model instance that contained no data, it would rarely if ever\nbe useful to do anything with it in a template. On the other hand, it makes\nperfect sense to render an unpopulated form - that's what we do when we want\nthe user to populate it.\n\nSo when we handle a model instance in a view, we typically retrieve it from the\ndatabase. When we're dealing with a form we typically instantiate it in the\nview.\n\nWhen we instantiate a form, we can opt to leave it empty or pre-populate it, for\nexample with:\n\n* data from a saved model instance (as in the case of admin forms for editing)\n* data that we have collated from other sources\n* data received from a previous HTML form submission\n\nThe last of these cases is the most interesting, because it's what makes it\npossible for users not just to read a website, but to send information back\nto it too.\n\nBuilding a form\n===============\n\nThe work that needs to be done\n------------------------------\n\nSuppose you want to create a simple form on your website, in order to obtain\nthe user's name. You'd need something like this in your template:\n\n.. code-block:: html+django\n\n    <form action=\"/your-name/\" method=\"post\">\n        <label for=\"your_name\">Your name: </label>\n        <input id=\"your_name\" type=\"text\" name=\"your_name\" value=\"{{ current_name }}\">\n        <input type=\"submit\" value=\"OK\">\n    </form>\n\nThis tells the browser to return the form data to the URL ``/your-name/``, using\nthe ``POST`` method. It will display a text field, labeled \"Your name:\", and a\nbutton marked \"OK\". If the template context contains a ``current_name``\nvariable, that will be used to pre-fill the ``your_name`` field.\n\nYou'll need a view that renders the template containing the HTML form, and\nthat can supply the ``current_name`` field as appropriate.\n\nWhen the form is submitted, the ``POST`` request which is sent to the server\nwill contain the form data.\n\nNow you'll also need a view corresponding to that ``/your-name/`` URL which will\nfind the appropriate key/value pairs in the request, and then process them.\n\nThis is a very simple form. In practice, a form might contain dozens or\nhundreds of fields, many of which might need to be pre-populated, and we might\nexpect the user to work through the edit-submit cycle several times before\nconcluding the operation.\n\nWe might require some validation to occur in the browser, even before the form\nis submitted; we might want to use much more complex fields, that allow the\nuser to do things like pick dates from a calendar and so on.\n\nAt this point it's much easier to get Django to do most of this work for us.\n\nBuilding a form in Django\n-------------------------\n\nThe :class:`Form` class\n~~~~~~~~~~~~~~~~~~~~~~~\n\nWe already know what we want our HTML form to look like. Our starting point for\nit in Django is this:\n\n.. code-block:: python\n    :caption: forms.py\n\n    from django import forms\n\n    class NameForm(forms.Form):\n        your_name = forms.CharField(label='Your name', max_length=100)\n\nThis defines a :class:`Form` class with a single field (``your_name``). We've\napplied a human-friendly label to the field, which will appear in the\n``<label>`` when it's rendered (although in this case, the :attr:`~Field.label`\nwe specified is actually the same one that would be generated automatically if\nwe had omitted it).\n\nThe field's maximum allowable length is defined by\n:attr:`~CharField.max_length`. This does two things. It puts a\n``maxlength=\"100\"`` on the HTML ``<input>`` (so the browser should prevent the\nuser from entering more than that number of characters in the first place). It\nalso means that when Django receives the form back from the browser, it will\nvalidate the length of the data.\n\nA :class:`Form` instance has an :meth:`~Form.is_valid()` method, which runs\nvalidation routines for all its fields. When this method is called, if all\nfields contain valid data, it will:\n\n* return ``True``\n* place the form's data in its :attr:`~Form.cleaned_data` attribute.\n\nThe whole form, when rendered for the first time, will look like:\n\n.. code-block:: html+django\n\n    <label for=\"your_name\">Your name: </label>\n    <input id=\"your_name\" type=\"text\" name=\"your_name\" maxlength=\"100\" required>\n\nNote that it **does not** include the ``<form>`` tags, or a submit button.\nWe'll have to provide those ourselves in the template.\n\n.. _using-a-form-in-a-view:\n\nThe view\n~~~~~~~~\n\nForm data sent back to a Django website is processed by a view, generally the\nsame view which published the form. This allows us to reuse some of the same\nlogic.\n\nTo handle the form we need to instantiate it in the view for the URL where we\nwant it to be published:\n\n.. code-block:: python\n    :caption: views.py\n\n    from django.http import HttpResponseRedirect\n    from django.shortcuts import render\n\n    from .forms import NameForm\n\n    def get_name(request):\n        # if this is a POST request we need to process the form data\n        if request.method == 'POST':\n            # create a form instance and populate it with data from the request:\n            form = NameForm(request.POST)\n            # check whether it's valid:\n            if form.is_valid():\n                # process the data in form.cleaned_data as required\n                # ...\n                # redirect to a new URL:\n                return HttpResponseRedirect('/thanks/')\n\n        # if a GET (or any other method) we'll create a blank form\n        else:\n            form = NameForm()\n\n        return render(request, 'name.html', {'form': form})\n\nIf we arrive at this view with a ``GET`` request, it will create an empty form\ninstance and place it in the template context to be rendered. This is what we\ncan expect to happen the first time we visit the URL.\n\nIf the form is submitted using a ``POST`` request, the view will once again\ncreate a form instance and populate it with data from the request: ``form =\nNameForm(request.POST)`` This is called \"binding data to the form\" (it is now\na *bound* form).\n\nWe call the form's ``is_valid()`` method; if it's not ``True``, we go back to\nthe template with the form. This time the form is no longer empty (*unbound*)\nso the HTML form will be populated with the data previously submitted, where it\ncan be edited and corrected as required.\n\nIf ``is_valid()`` is ``True``, we'll now be able to find all the validated form\ndata in its ``cleaned_data`` attribute. We can use this data to update the\ndatabase or do other processing before sending an HTTP redirect to the browser\ntelling it where to go next.\n\n.. _topics-forms-index-basic-form-template:\n\nThe template\n~~~~~~~~~~~~\n\nWe don't need to do much in our ``name.html`` template:\n\n.. code-block:: html+django\n\n    <form action=\"/your-name/\" method=\"post\">\n        {% csrf_token %}\n        {{ form }}\n        <input type=\"submit\" value=\"Submit\">\n    </form>\n\nAll the form's fields and their attributes will be unpacked into HTML markup\nfrom that ``{{ form }}`` by Django's template language.\n\n.. admonition:: Forms and Cross Site Request Forgery protection\n\n    Django ships with an easy-to-use :doc:`protection against Cross Site Request\n    Forgeries </ref/csrf>`. When submitting a form via ``POST`` with\n    CSRF protection enabled you must use the :ttag:`csrf_token` template tag\n    as in the preceding example. However, since CSRF protection is not\n    directly tied to forms in templates, this tag is omitted from the\n    following examples in this document.\n\n.. admonition:: HTML5 input types and browser validation\n\n    If your form includes a :class:`~django.forms.URLField`, an\n    :class:`~django.forms.EmailField` or any integer field type, Django will\n    use the ``url``, ``email`` and ``number`` HTML5 input types. By default,\n    browsers may apply their own validation on these fields, which may be\n    stricter than Django's validation. If you would like to disable this\n    behavior, set the ``novalidate`` attribute on the ``form`` tag, or specify\n    a different widget on the field, like :class:`TextInput`.\n\nWe now have a working web form, described by a Django :class:`Form`, processed\nby a view, and rendered as an HTML ``<form>``.\n\nThat's all you need to get started, but the forms framework puts a lot more at\nyour fingertips. Once you understand the basics of the process described above,\nyou should be prepared to understand other features of the forms system and\nready to learn a bit more about the underlying machinery.\n\nMore about Django :class:`Form` classes\n=======================================\n\nAll form classes are created as subclasses of either :class:`django.forms.Form`\nor :class:`django.forms.ModelForm`. You can think of ``ModelForm`` as a\nsubclass of ``Form``. ``Form`` and ``ModelForm`` actually inherit common\nfunctionality from a (private) ``BaseForm`` class, but this implementation\ndetail is rarely important.\n\n.. admonition:: Models and Forms\n\n    In fact if your form is going to be used to directly add or edit a Django\n    model, a :doc:`ModelForm </topics/forms/modelforms>` can save you a great\n    deal of time, effort, and code, because it will build a form, along with the\n    appropriate fields and their attributes, from a ``Model`` class.\n\nBound and unbound form instances\n--------------------------------\n\nThe distinction between :ref:`ref-forms-api-bound-unbound` is important:\n\n* An unbound form has no data associated with it. When rendered to the user,\n  it will be empty or will contain default values.\n\n* A bound form has submitted data, and hence can be used to tell if that data\n  is valid. If an invalid bound form is rendered, it can include inline error\n  messages telling the user what data to correct.\n\nThe form's :attr:`~Form.is_bound` attribute will tell you whether a form has\ndata bound to it or not.\n\nMore on fields\n--------------\n\nConsider a more useful form than our minimal example above, which we could use\nto implement \"contact me\" functionality on a personal website:\n\n.. code-block:: python\n    :caption: forms.py\n\n    from django import forms\n\n    class ContactForm(forms.Form):\n        subject = forms.CharField(max_length=100)\n        message = forms.CharField(widget=forms.Textarea)\n        sender = forms.EmailField()\n        cc_myself = forms.BooleanField(required=False)\n\nOur earlier form used a single field, ``your_name``, a :class:`CharField`. In\nthis case, our form has four fields: ``subject``, ``message``, ``sender`` and\n``cc_myself``. :class:`CharField`, :class:`EmailField` and\n:class:`BooleanField` are just three of the available field types; a full list\ncan be found in :doc:`/ref/forms/fields`.\n\nWidgets\n~~~~~~~\n\nEach form field has a corresponding :doc:`Widget class </ref/forms/widgets/>`,\nwhich in turn corresponds to an HTML form widget such as ``<input\ntype=\"text\">``.\n\nIn most cases, the field will have a sensible default widget. For example, by\ndefault, a :class:`CharField` will have a :class:`TextInput` widget, that\nproduces an ``<input type=\"text\">`` in the HTML. If you needed ``<textarea>``\ninstead, you'd specify the appropriate widget when defining your form field,\nas we have done for the ``message`` field.\n\nField data\n~~~~~~~~~~\n\nWhatever the data submitted with a form, once it has been successfully\nvalidated by calling ``is_valid()`` (and ``is_valid()`` has returned ``True``),\nthe validated form data will be in the ``form.cleaned_data`` dictionary. This\ndata will have been nicely converted into Python types for you.\n\n.. note::\n\n    You can still access the unvalidated data directly from ``request.POST`` at\n    this point, but the validated data is better.\n\nIn the contact form example above, ``cc_myself`` will be a boolean value.\nLikewise, fields such as :class:`IntegerField` and :class:`FloatField` convert\nvalues to a Python ``int`` and ``float`` respectively.\n\nHere's how the form data could be processed in the view that handles this form:\n\n.. code-block:: python\n    :caption: views.py\n\n    from django.core.mail import send_mail\n\n    if form.is_valid():\n        subject = form.cleaned_data['subject']\n        message = form.cleaned_data['message']\n        sender = form.cleaned_data['sender']\n        cc_myself = form.cleaned_data['cc_myself']\n\n        recipients = ['info@example.com']\n        if cc_myself:\n            recipients.append(sender)\n\n        send_mail(subject, message, sender, recipients)\n        return HttpResponseRedirect('/thanks/')\n\n.. tip::\n\n    For more on sending email from Django, see :doc:`/topics/email`.\n\nSome field types need some extra handling. For example, files that are uploaded\nusing a form need to be handled differently (they can be retrieved from\n``request.FILES``, rather than ``request.POST``). For details of how to handle\nfile uploads with your form, see :ref:`binding-uploaded-files`.\n\nWorking with form templates\n===========================\n\nAll you need to do to get your form into a template is to place the form\ninstance into the template context. So if your form is called ``form`` in the\ncontext, ``{{ form }}`` will render its ``<label>`` and ``<input>`` elements\nappropriately.\n\nForm rendering options\n----------------------\n\n.. admonition:: Additional form template furniture\n\n    Don't forget that a form's output does *not* include the surrounding\n    ``<form>`` tags, or the form's ``submit`` control. You will have to provide\n    these yourself.\n\nThere are other output options though for the ``<label>``/``<input>`` pairs:\n\n* ``{{ form.as_table }}`` will render them as table cells wrapped in ``<tr>``\n  tags\n\n* ``{{ form.as_p }}`` will render them wrapped in ``<p>`` tags\n\n* ``{{ form.as_ul }}`` will render them wrapped in ``<li>`` tags\n\nNote that you'll have to provide the surrounding ``<table>`` or ``<ul>``\nelements yourself.\n\nHere's the output of ``{{ form.as_p }}`` for our ``ContactForm`` instance:\n\n.. code-block:: html+django\n\n    <p><label for=\"id_subject\">Subject:</label>\n        <input id=\"id_subject\" type=\"text\" name=\"subject\" maxlength=\"100\" required></p>\n    <p><label for=\"id_message\">Message:</label>\n        <textarea name=\"message\" id=\"id_message\" required></textarea></p>\n    <p><label for=\"id_sender\">Sender:</label>\n        <input type=\"email\" name=\"sender\" id=\"id_sender\" required></p>\n    <p><label for=\"id_cc_myself\">Cc myself:</label>\n        <input type=\"checkbox\" name=\"cc_myself\" id=\"id_cc_myself\"></p>\n\nNote that each form field has an ID attribute set to ``id_<field-name>``, which\nis referenced by the accompanying label tag. This is important in ensuring that\nforms are accessible to assistive technology such as screen reader software.\nYou can also :ref:`customize the way in which labels and ids are generated\n<ref-forms-api-configuring-label>`.\n\nSee :ref:`ref-forms-api-outputting-html` for more on this.\n\nRendering fields manually\n-------------------------\n\nWe don't have to let Django unpack the form's fields; we can do it manually if\nwe like (allowing us to reorder the fields, for example). Each field is\navailable as an attribute of the form using ``{{ form.name_of_field }}``, and\nin a Django template, will be rendered appropriately. For example:\n\n.. code-block:: html+django\n\n    {{ form.non_field_errors }}\n    <div class=\"fieldWrapper\">\n        {{ form.subject.errors }}\n        <label for=\"{{ form.subject.id_for_label }}\">Email subject:</label>\n        {{ form.subject }}\n    </div>\n    <div class=\"fieldWrapper\">\n        {{ form.message.errors }}\n        <label for=\"{{ form.message.id_for_label }}\">Your message:</label>\n        {{ form.message }}\n    </div>\n    <div class=\"fieldWrapper\">\n        {{ form.sender.errors }}\n        <label for=\"{{ form.sender.id_for_label }}\">Your email address:</label>\n        {{ form.sender }}\n    </div>\n    <div class=\"fieldWrapper\">\n        {{ form.cc_myself.errors }}\n        <label for=\"{{ form.cc_myself.id_for_label }}\">CC yourself?</label>\n        {{ form.cc_myself }}\n    </div>\n\nComplete ``<label>`` elements can also be generated using the\n:meth:`~django.forms.BoundField.label_tag`. For example:\n\n.. code-block:: html+django\n\n    <div class=\"fieldWrapper\">\n        {{ form.subject.errors }}\n        {{ form.subject.label_tag }}\n        {{ form.subject }}\n    </div>\n\n\nRendering form error messages\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe price of this flexibility is a bit more work. Until now we haven't had to\nworry about how to display form errors, because that's taken care of for us. In\nthis example we have had to make sure we take care of any errors for each field\nand any errors for the form as a whole. Note ``{{ form.non_field_errors }}`` at\nthe top of the form and the template lookup for errors on each field.\n\nUsing ``{{ form.name_of_field.errors }}`` displays a list of form errors,\nrendered as an unordered list. This might look like:\n\n.. code-block:: html+django\n\n    <ul class=\"errorlist\">\n        <li>Sender is required.</li>\n    </ul>\n\nThe list has a CSS class of ``errorlist`` to allow you to style its appearance.\nIf you wish to further customize the display of errors you can do so by looping\nover them:\n\n.. code-block:: html+django\n\n    {% if form.subject.errors %}\n        <ol>\n        {% for error in form.subject.errors %}\n            <li><strong>{{ error|escape }}</strong></li>\n        {% endfor %}\n        </ol>\n    {% endif %}\n\nNon-field errors (and/or hidden field errors that are rendered at the top of\nthe form when using helpers like ``form.as_p()``) will be rendered with an\nadditional class of ``nonfield`` to help distinguish them from field-specific\nerrors. For example, ``{{ form.non_field_errors }}`` would look like:\n\n.. code-block:: html+django\n\n    <ul class=\"errorlist nonfield\">\n        <li>Generic validation error</li>\n    </ul>\n\nSee :doc:`/ref/forms/api` for more on errors, styling, and working with form\nattributes in templates.\n\nLooping over the form's fields\n------------------------------\n\nIf you're using the same HTML for each of your form fields, you can reduce\nduplicate code by looping through each field in turn using a ``{% for %}``\nloop:\n\n.. code-block:: html+django\n\n    {% for field in form %}\n        <div class=\"fieldWrapper\">\n            {{ field.errors }}\n            {{ field.label_tag }} {{ field }}\n            {% if field.help_text %}\n            <p class=\"help\">{{ field.help_text|safe }}</p>\n            {% endif %}\n        </div>\n    {% endfor %}\n\nUseful attributes on ``{{ field }}`` include:\n\n``{{ field.label }}``\n    The label of the field, e.g. ``Email address``.\n\n``{{ field.label_tag }}``\n    The field's label wrapped in the appropriate HTML ``<label>`` tag. This\n    includes the form's :attr:`~django.forms.Form.label_suffix`. For example,\n    the default ``label_suffix`` is a colon::\n\n        <label for=\"id_email\">Email address:</label>\n\n``{{ field.id_for_label }}``\n    The ID that will be used for this field (``id_email`` in the example\n    above). If you are constructing the label manually, you may want to use\n    this in lieu of ``label_tag``. It's also useful, for example, if you have\n    some inline JavaScript and want to avoid hardcoding the field's ID.\n\n``{{ field.value }}``\n    The value of the field. e.g ``someone@example.com``.\n\n``{{ field.html_name }}``\n    The name of the field that will be used in the input element's name\n    field. This takes the form prefix into account, if it has been set.\n\n``{{ field.help_text }}``\n    Any help text that has been associated with the field.\n\n``{{ field.errors }}``\n    Outputs a ``<ul class=\"errorlist\">`` containing any validation errors\n    corresponding to this field. You can customize the presentation of\n    the errors with a ``{% for error in field.errors %}`` loop. In this\n    case, each object in the loop is a string containing the error message.\n\n``{{ field.is_hidden }}``\n    This attribute is ``True`` if the form field is a hidden field and\n    ``False`` otherwise. It's not particularly useful as a template\n    variable, but could be useful in conditional tests such as:\n\n.. code-block:: html+django\n\n    {% if field.is_hidden %}\n       {# Do something special #}\n    {% endif %}\n\n``{{ field.field }}``\n    The :class:`~django.forms.Field` instance from the form class that\n    this :class:`~django.forms.BoundField` wraps. You can use it to access\n    :class:`~django.forms.Field` attributes, e.g.\n    ``{{ char_field.field.max_length }}``.\n\n.. seealso::\n\n    For a complete list of attributes and methods, see\n    :class:`~django.forms.BoundField`.\n\nLooping over hidden and visible fields\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf you're manually laying out a form in a template, as opposed to relying on\nDjango's default form layout, you might want to treat ``<input type=\"hidden\">``\nfields differently from non-hidden fields. For example, because hidden fields\ndon't display anything, putting error messages \"next to\" the field could cause\nconfusion for your users -- so errors for those fields should be handled\ndifferently.\n\nDjango provides two methods on a form that allow you to loop over the hidden\nand visible fields independently: ``hidden_fields()`` and\n``visible_fields()``. Here's a modification of an earlier example that uses\nthese two methods:\n\n.. code-block:: html+django\n\n    {# Include the hidden fields #}\n    {% for hidden in form.hidden_fields %}\n    {{ hidden }}\n    {% endfor %}\n    {# Include the visible fields #}\n    {% for field in form.visible_fields %}\n        <div class=\"fieldWrapper\">\n            {{ field.errors }}\n            {{ field.label_tag }} {{ field }}\n        </div>\n    {% endfor %}\n\nThis example does not handle any errors in the hidden fields. Usually, an\nerror in a hidden field is a sign of form tampering, since normal form\ninteraction won't alter them. However, you could easily insert some error\ndisplays for those form errors, as well.\n\nReusable form templates\n-----------------------\n\nIf your site uses the same rendering logic for forms in multiple places, you\ncan reduce duplication by saving the form's loop in a standalone template and\nusing the :ttag:`include` tag to reuse it in other templates:\n\n.. code-block:: html+django\n\n    # In your form template:\n    {% include \"form_snippet.html\" %}\n\n    # In form_snippet.html:\n    {% for field in form %}\n        <div class=\"fieldWrapper\">\n            {{ field.errors }}\n            {{ field.label_tag }} {{ field }}\n        </div>\n    {% endfor %}\n\nIf the form object passed to a template has a different name within the\ncontext, you can alias it using the ``with`` argument of the :ttag:`include`\ntag:\n\n.. code-block:: html+django\n\n    {% include \"form_snippet.html\" with form=comment_form %}\n\nIf you find yourself doing this often, you might consider creating a custom\n:ref:`inclusion tag<howto-custom-template-tags-inclusion-tags>`.\n\nFurther topics\n==============\n\nThis covers the basics, but forms can do a whole lot more:\n\n.. toctree::\n   :maxdepth: 2\n\n   formsets\n   modelforms\n   media\n\n.. seealso::\n\n    :doc:`The Forms Reference </ref/forms/index>`\n        Covers the full API reference, including form fields, form widgets,\n        and form and field validation.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":315,"nodeType":"TextFile","repoName":null,"name":"advanced.txt","path":"docs/topics/testing","text":"=======================\nAdvanced testing topics\n=======================\n\nThe request factory\n===================\n\n.. currentmodule:: django.test\n\n.. class:: RequestFactory\n\nThe :class:`~django.test.RequestFactory` shares the same API as\nthe test client. However, instead of behaving like a browser, the\nRequestFactory provides a way to generate a request instance that can\nbe used as the first argument to any view. This means you can test a\nview function the same way as you would test any other function -- as\na black box, with exactly known inputs, testing for specific outputs.\n\nThe API for the :class:`~django.test.RequestFactory` is a slightly\nrestricted subset of the test client API:\n\n* It only has access to the HTTP methods :meth:`~Client.get()`,\n  :meth:`~Client.post()`, :meth:`~Client.put()`,\n  :meth:`~Client.delete()`, :meth:`~Client.head()`,\n  :meth:`~Client.options()`, and :meth:`~Client.trace()`.\n\n* These methods accept all the same arguments *except* for\n  ``follow``. Since this is just a factory for producing\n  requests, it's up to you to handle the response.\n\n* It does not support middleware. Session and authentication\n  attributes must be supplied by the test itself if required\n  for the view to function properly.\n\nExample\n-------\n\nThe following is a unit test using the request factory::\n\n    from django.contrib.auth.models import AnonymousUser, User\n    from django.test import RequestFactory, TestCase\n\n    from .views import MyView, my_view\n\n    class SimpleTest(TestCase):\n        def setUp(self):\n            # Every test needs access to the request factory.\n            self.factory = RequestFactory()\n            self.user = User.objects.create_user(\n                username='jacob', email='jacob@…', password='top_secret')\n\n        def test_details(self):\n            # Create an instance of a GET request.\n            request = self.factory.get('/customer/details')\n\n            # Recall that middleware are not supported. You can simulate a\n            # logged-in user by setting request.user manually.\n            request.user = self.user\n\n            # Or you can simulate an anonymous user by setting request.user to\n            # an AnonymousUser instance.\n            request.user = AnonymousUser()\n\n            # Test my_view() as if it were deployed at /customer/details\n            response = my_view(request)\n            # Use this syntax for class-based views.\n            response = MyView.as_view()(request)\n            self.assertEqual(response.status_code, 200)\n\nAsyncRequestFactory\n-------------------\n\n``RequestFactory`` creates WSGI-like requests. If you want to create ASGI-like\nrequests, including having a correct ASGI ``scope``, you can instead use\n``django.test.AsyncRequestFactory``.\n\nThis class is directly API-compatible with ``RequestFactory``, with the only\ndifference being that it returns ``ASGIRequest`` instances rather than\n``WSGIRequest`` instances. All of its methods are still synchronous callables.\n\nTesting class-based views\n=========================\n\nIn order to test class-based views outside of the request/response cycle you\nmust ensure that they are configured correctly, by calling\n:meth:`~django.views.generic.base.View.setup` after instantiation.\n\nFor example, assuming the following class-based view:\n\n.. code-block:: python\n    :caption: views.py\n\n    from django.views.generic import TemplateView\n\n\n    class HomeView(TemplateView):\n        template_name = 'myapp/home.html'\n\n        def get_context_data(self, **kwargs):\n            kwargs['environment'] = 'Production'\n            return super().get_context_data(**kwargs)\n\nYou may directly test the ``get_context_data()`` method by first instantiating\nthe view, then passing a ``request`` to ``setup()``, before proceeding with\nyour test's code:\n\n.. code-block:: python\n    :caption: tests.py\n\n    from django.test import RequestFactory, TestCase\n    from .views import HomeView\n\n\n    class HomePageTest(TestCase):\n        def test_environment_set_in_context(self):\n            request = RequestFactory().get('/')\n            view = HomeView()\n            view.setup(request)\n\n            context = view.get_context_data()\n            self.assertIn('environment', context)\n\n.. _topics-testing-advanced-multiple-hosts:\n\nTests and multiple host names\n=============================\n\nThe :setting:`ALLOWED_HOSTS` setting is validated when running tests. This\nallows the test client to differentiate between internal and external URLs.\n\nProjects that support multitenancy or otherwise alter business logic based on\nthe request's host and use custom host names in tests must include those hosts\nin :setting:`ALLOWED_HOSTS`.\n\nThe first option to do so is to add the hosts to your settings file. For\nexample, the test suite for docs.djangoproject.com includes the following::\n\n    from django.test import TestCase\n\n    class SearchFormTestCase(TestCase):\n        def test_empty_get(self):\n            response = self.client.get('/en/dev/search/', HTTP_HOST='docs.djangoproject.dev:8000')\n            self.assertEqual(response.status_code, 200)\n\nand the settings file includes a list of the domains supported by the project::\n\n    ALLOWED_HOSTS = [\n        'www.djangoproject.dev',\n        'docs.djangoproject.dev',\n        ...\n    ]\n\nAnother option is to add the required hosts to :setting:`ALLOWED_HOSTS` using\n:meth:`~django.test.override_settings()` or\n:attr:`~django.test.SimpleTestCase.modify_settings()`. This option may be\npreferable in standalone apps that can't package their own settings file or\nfor projects where the list of domains is not static (e.g., subdomains for\nmultitenancy). For example, you could write a test for the domain\n``http://otherserver/`` as follows::\n\n    from django.test import TestCase, override_settings\n\n    class MultiDomainTestCase(TestCase):\n        @override_settings(ALLOWED_HOSTS=['otherserver'])\n        def test_other_domain(self):\n            response = self.client.get('http://otherserver/foo/bar/')\n\nDisabling :setting:`ALLOWED_HOSTS` checking (``ALLOWED_HOSTS = ['*']``) when\nrunning tests prevents the test client from raising a helpful error message if\nyou follow a redirect to an external URL.\n\n.. _topics-testing-advanced-multidb:\n\nTests and multiple databases\n============================\n\n.. _topics-testing-primaryreplica:\n\nTesting primary/replica configurations\n--------------------------------------\n\nIf you're testing a multiple database configuration with primary/replica\n(referred to as master/slave by some databases) replication, this strategy of\ncreating test databases poses a problem.\nWhen the test databases are created, there won't be any replication,\nand as a result, data created on the primary won't be seen on the\nreplica.\n\nTo compensate for this, Django allows you to define that a database is\na *test mirror*. Consider the following (simplified) example database\nconfiguration::\n\n    DATABASES = {\n        'default': {\n            'ENGINE': 'django.db.backends.mysql',\n            'NAME': 'myproject',\n            'HOST': 'dbprimary',\n             # ... plus some other settings\n        },\n        'replica': {\n            'ENGINE': 'django.db.backends.mysql',\n            'NAME': 'myproject',\n            'HOST': 'dbreplica',\n            'TEST': {\n                'MIRROR': 'default',\n            },\n            # ... plus some other settings\n        }\n    }\n\nIn this setup, we have two database servers: ``dbprimary``, described\nby the database alias ``default``, and ``dbreplica`` described by the\nalias ``replica``. As you might expect, ``dbreplica`` has been configured\nby the database administrator as a read replica of ``dbprimary``, so in\nnormal activity, any write to ``default`` will appear on ``replica``.\n\nIf Django created two independent test databases, this would break any\ntests that expected replication to occur. However, the ``replica``\ndatabase has been configured as a test mirror (using the\n:setting:`MIRROR <TEST_MIRROR>` test setting), indicating that under\ntesting, ``replica`` should be treated as a mirror of ``default``.\n\nWhen the test environment is configured, a test version of ``replica``\nwill *not* be created. Instead the connection to ``replica``\nwill be redirected to point at ``default``. As a result, writes to\n``default`` will appear on ``replica`` -- but because they are actually\nthe same database, not because there is data replication between the\ntwo databases.\n\n.. _topics-testing-creation-dependencies:\n\nControlling creation order for test databases\n---------------------------------------------\n\nBy default, Django will assume all databases depend on the ``default``\ndatabase and therefore always create the ``default`` database first.\nHowever, no guarantees are made on the creation order of any other\ndatabases in your test setup.\n\nIf your database configuration requires a specific creation order, you\ncan specify the dependencies that exist using the :setting:`DEPENDENCIES\n<TEST_DEPENDENCIES>` test setting. Consider the following (simplified)\nexample database configuration::\n\n    DATABASES = {\n        'default': {\n            # ... db settings\n            'TEST': {\n                'DEPENDENCIES': ['diamonds'],\n            },\n        },\n        'diamonds': {\n            # ... db settings\n            'TEST': {\n                'DEPENDENCIES': [],\n            },\n        },\n        'clubs': {\n            # ... db settings\n            'TEST': {\n                'DEPENDENCIES': ['diamonds'],\n            },\n        },\n        'spades': {\n            # ... db settings\n            'TEST': {\n                'DEPENDENCIES': ['diamonds', 'hearts'],\n            },\n        },\n        'hearts': {\n            # ... db settings\n            'TEST': {\n                'DEPENDENCIES': ['diamonds', 'clubs'],\n            },\n        }\n    }\n\nUnder this configuration, the ``diamonds`` database will be created first,\nas it is the only database alias without dependencies. The ``default`` and\n``clubs`` alias will be created next (although the order of creation of this\npair is not guaranteed), then ``hearts``, and finally ``spades``.\n\nIf there are any circular dependencies in the :setting:`DEPENDENCIES\n<TEST_DEPENDENCIES>` definition, an\n:exc:`~django.core.exceptions.ImproperlyConfigured` exception will be raised.\n\nAdvanced features of ``TransactionTestCase``\n============================================\n\n.. attribute:: TransactionTestCase.available_apps\n\n    .. warning::\n\n        This attribute is a private API. It may be changed or removed without\n        a deprecation period in the future, for instance to accommodate changes\n        in application loading.\n\n        It's used to optimize Django's own test suite, which contains hundreds\n        of models but no relations between models in different applications.\n\n    By default, ``available_apps`` is set to ``None``. After each test, Django\n    calls :djadmin:`flush` to reset the database state. This empties all tables\n    and emits the :data:`~django.db.models.signals.post_migrate` signal, which\n    recreates one content type and four permissions for each model. This\n    operation gets expensive proportionally to the number of models.\n\n    Setting ``available_apps`` to a list of applications instructs Django to\n    behave as if only the models from these applications were available. The\n    behavior of ``TransactionTestCase`` changes as follows:\n\n    - :data:`~django.db.models.signals.post_migrate` is fired before each\n      test to create the content types and permissions for each model in\n      available apps, in case they're missing.\n    - After each test, Django empties only tables corresponding to models in\n      available apps. However, at the database level, truncation may cascade to\n      related models in unavailable apps. Furthermore\n      :data:`~django.db.models.signals.post_migrate` isn't fired; it will be\n      fired by the next ``TransactionTestCase``, after the correct set of\n      applications is selected.\n\n    Since the database isn't fully flushed, if a test creates instances of\n    models not included in ``available_apps``, they will leak and they may\n    cause unrelated tests to fail. Be careful with tests that use sessions;\n    the default session engine stores them in the database.\n\n    Since :data:`~django.db.models.signals.post_migrate` isn't emitted after\n    flushing the database, its state after a ``TransactionTestCase`` isn't the\n    same as after a ``TestCase``: it's missing the rows created by listeners\n    to :data:`~django.db.models.signals.post_migrate`. Considering the\n    :ref:`order in which tests are executed <order-of-tests>`, this isn't an\n    issue, provided either all ``TransactionTestCase`` in a given test suite\n    declare ``available_apps``, or none of them.\n\n    ``available_apps`` is mandatory in Django's own test suite.\n\n.. attribute:: TransactionTestCase.reset_sequences\n\n    Setting ``reset_sequences = True`` on a ``TransactionTestCase`` will make\n    sure sequences are always reset before the test run::\n\n        class TestsThatDependsOnPrimaryKeySequences(TransactionTestCase):\n            reset_sequences = True\n\n            def test_animal_pk(self):\n                lion = Animal.objects.create(name=\"lion\", sound=\"roar\")\n                # lion.pk is guaranteed to always be 1\n                self.assertEqual(lion.pk, 1)\n\n    Unless you are explicitly testing primary keys sequence numbers, it is\n    recommended that you do not hard code primary key values in tests.\n\n    Using ``reset_sequences = True`` will slow down the test, since the primary\n    key reset is a relatively expensive database operation.\n\n.. _topics-testing-enforce-run-sequentially:\n\nEnforce running test classes sequentially\n=========================================\n\nIf you have test classes that cannot be run in parallel (e.g. because they\nshare a common resource), you can use ``django.test.testcases.SerializeMixin``\nto run them sequentially. This mixin uses a filesystem ``lockfile``.\n\nFor example, you can use ``__file__`` to determine that all test classes in the\nsame file that inherit from ``SerializeMixin`` will run sequentially::\n\n    import os\n\n    from django.test import TestCase\n    from django.test.testcases import SerializeMixin\n\n    class ImageTestCaseMixin(SerializeMixin):\n        lockfile = __file__\n\n        def setUp(self):\n            self.filename = os.path.join(temp_storage_dir, 'my_file.png')\n            self.file = create_file(self.filename)\n\n    class RemoveImageTests(ImageTestCaseMixin, TestCase):\n        def test_remove_image(self):\n            os.remove(self.filename)\n            self.assertFalse(os.path.exists(self.filename))\n\n    class ResizeImageTests(ImageTestCaseMixin, TestCase):\n        def test_resize_image(self):\n            resize_image(self.file, (48, 48))\n            self.assertEqual(get_image_size(self.file), (48, 48))\n\n.. _testing-reusable-applications:\n\nUsing the Django test runner to test reusable applications\n==========================================================\n\nIf you are writing a :doc:`reusable application </intro/reusable-apps>`\nyou may want to use the Django test runner to run your own test suite\nand thus benefit from the Django testing infrastructure.\n\nA common practice is a *tests* directory next to the application code, with the\nfollowing structure::\n\n    runtests.py\n    polls/\n        __init__.py\n        models.py\n        ...\n    tests/\n        __init__.py\n        models.py\n        test_settings.py\n        tests.py\n\nLet's take a look inside a couple of those files:\n\n.. code-block:: python\n    :caption: runtests.py\n\n    #!/usr/bin/env python\n    import os\n    import sys\n\n    import django\n    from django.conf import settings\n    from django.test.utils import get_runner\n\n    if __name__ == \"__main__\":\n        os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings'\n        django.setup()\n        TestRunner = get_runner(settings)\n        test_runner = TestRunner()\n        failures = test_runner.run_tests([\"tests\"])\n        sys.exit(bool(failures))\n\n\nThis is the script that you invoke to run the test suite. It sets up the\nDjango environment, creates the test database and runs the tests.\n\nFor the sake of clarity, this example contains only the bare minimum\nnecessary to use the Django test runner. You may want to add\ncommand-line options for controlling verbosity, passing in specific test\nlabels to run, etc.\n\n.. code-block:: python\n    :caption: tests/test_settings.py\n\n    SECRET_KEY = 'fake-key'\n    INSTALLED_APPS = [\n        \"tests\",\n    ]\n\nThis file contains the :doc:`Django settings </topics/settings>`\nrequired to run your app's tests.\n\nAgain, this is a minimal example; your tests may require additional\nsettings to run.\n\nSince the *tests* package is included in :setting:`INSTALLED_APPS` when\nrunning your tests, you can define test-only models in its ``models.py``\nfile.\n\n\n.. _other-testing-frameworks:\n\nUsing different testing frameworks\n==================================\n\nClearly, :mod:`unittest` is not the only Python testing framework. While Django\ndoesn't provide explicit support for alternative frameworks, it does provide a\nway to invoke tests constructed for an alternative framework as if they were\nnormal Django tests.\n\nWhen you run ``./manage.py test``, Django looks at the :setting:`TEST_RUNNER`\nsetting to determine what to do. By default, :setting:`TEST_RUNNER` points to\n``'django.test.runner.DiscoverRunner'``. This class defines the default Django\ntesting behavior. This behavior involves:\n\n#. Performing global pre-test setup.\n\n#. Looking for tests in any file below the current directory whose name matches\n   the pattern ``test*.py``.\n\n#. Creating the test databases.\n\n#. Running ``migrate`` to install models and initial data into the test\n   databases.\n\n#. Running the :doc:`system checks </topics/checks>`.\n\n#. Running the tests that were found.\n\n#. Destroying the test databases.\n\n#. Performing global post-test teardown.\n\nIf you define your own test runner class and point :setting:`TEST_RUNNER` at\nthat class, Django will execute your test runner whenever you run\n``./manage.py test``. In this way, it is possible to use any test framework\nthat can be executed from Python code, or to modify the Django test execution\nprocess to satisfy whatever testing requirements you may have.\n\n.. _topics-testing-test_runner:\n\nDefining a test runner\n----------------------\n\n.. currentmodule:: django.test.runner\n\nA test runner is a class defining a ``run_tests()`` method. Django ships\nwith a ``DiscoverRunner`` class that defines the default Django testing\nbehavior. This class defines the ``run_tests()`` entry point, plus a\nselection of other methods that are used to by ``run_tests()`` to set up,\nexecute and tear down the test suite.\n\n.. class:: DiscoverRunner(pattern='test*.py', top_level=None, verbosity=1, interactive=True, failfast=False, keepdb=False, reverse=False, debug_mode=False, debug_sql=False, test_name_patterns=None, **kwargs)\n\n    ``DiscoverRunner`` will search for tests in any file matching ``pattern``.\n\n    ``top_level`` can be used to specify the directory containing your\n    top-level Python modules. Usually Django can figure this out automatically,\n    so it's not necessary to specify this option. If specified, it should\n    generally be the directory containing your ``manage.py`` file.\n\n    ``verbosity`` determines the amount of notification and debug information\n    that will be printed to the console; ``0`` is no output, ``1`` is normal\n    output, and ``2`` is verbose output.\n\n    If ``interactive`` is ``True``, the test suite has permission to ask the\n    user for instructions when the test suite is executed. An example of this\n    behavior would be asking for permission to delete an existing test\n    database. If ``interactive`` is ``False``, the test suite must be able to\n    run without any manual intervention.\n\n    If ``failfast`` is ``True``, the test suite will stop running after the\n    first test failure is detected.\n\n    If ``keepdb`` is ``True``, the test suite will use the existing database,\n    or create one if necessary. If ``False``, a new database will be created,\n    prompting the user to remove the existing one, if present.\n\n    If ``reverse`` is ``True``, test cases will be executed in the opposite\n    order. This could be useful to debug tests that aren't properly isolated\n    and have side effects. :ref:`Grouping by test class <order-of-tests>` is\n    preserved when using this option.\n\n    ``debug_mode`` specifies what the :setting:`DEBUG` setting should be\n    set to prior to running tests.\n\n    If ``debug_sql`` is ``True``, failing test cases will output SQL queries\n    logged to the :ref:`django.db.backends logger <django-db-logger>` as well\n    as the traceback. If ``verbosity`` is ``2``, then queries in all tests are\n    output.\n\n    ``test_name_patterns`` can be used to specify a set of patterns for\n    filtering test methods and classes by their names.\n\n    Django may, from time to time, extend the capabilities of the test runner\n    by adding new arguments. The ``**kwargs`` declaration allows for this\n    expansion. If you subclass ``DiscoverRunner`` or write your own test\n    runner, ensure it accepts ``**kwargs``.\n\n    Your test runner may also define additional command-line options.\n    Create or override an ``add_arguments(cls, parser)`` class method and add\n    custom arguments by calling ``parser.add_argument()`` inside the method, so\n    that the :djadmin:`test` command will be able to use those arguments.\n\nAttributes\n~~~~~~~~~~\n\n.. attribute:: DiscoverRunner.test_suite\n\n    The class used to build the test suite. By default it is set to\n    ``unittest.TestSuite``. This can be overridden if you wish to implement\n    different logic for collecting tests.\n\n.. attribute:: DiscoverRunner.test_runner\n\n    This is the class of the low-level test runner which is used to execute\n    the individual tests and format the results. By default it is set to\n    ``unittest.TextTestRunner``. Despite the unfortunate similarity in\n    naming conventions, this is not the same type of class as\n    ``DiscoverRunner``, which covers a broader set of responsibilities. You\n    can override this attribute to modify the way tests are run and reported.\n\n.. attribute:: DiscoverRunner.test_loader\n\n    This is the class that loads tests, whether from TestCases or modules or\n    otherwise and bundles them into test suites for the runner to execute.\n    By default it is set to ``unittest.defaultTestLoader``. You can override\n    this attribute if your tests are going to be loaded in unusual ways.\n\nMethods\n~~~~~~~\n\n.. method:: DiscoverRunner.run_tests(test_labels, extra_tests=None, **kwargs)\n\n    Run the test suite.\n\n    ``test_labels`` allows you to specify which tests to run and supports\n    several formats (see :meth:`DiscoverRunner.build_suite` for a list of\n    supported formats).\n\n    ``extra_tests`` is a list of extra ``TestCase`` instances to add to the\n    suite that is executed by the test runner. These extra tests are run\n    in addition to those discovered in the modules listed in ``test_labels``.\n\n    This method should return the number of tests that failed.\n\n.. classmethod:: DiscoverRunner.add_arguments(parser)\n\n    Override this class method to add custom arguments accepted by the\n    :djadmin:`test` management command. See\n    :py:meth:`argparse.ArgumentParser.add_argument()` for details about adding\n    arguments to a parser.\n\n.. method:: DiscoverRunner.setup_test_environment(**kwargs)\n\n    Sets up the test environment by calling\n    :func:`~django.test.utils.setup_test_environment` and setting\n    :setting:`DEBUG` to ``self.debug_mode`` (defaults to ``False``).\n\n.. method:: DiscoverRunner.build_suite(test_labels, extra_tests=None, **kwargs)\n\n    Constructs a test suite that matches the test labels provided.\n\n    ``test_labels`` is a list of strings describing the tests to be run. A test\n    label can take one of four forms:\n\n    * ``path.to.test_module.TestCase.test_method`` -- Run a single test method\n      in a test case.\n    * ``path.to.test_module.TestCase`` -- Run all the test methods in a test\n      case.\n    * ``path.to.module`` -- Search for and run all tests in the named Python\n      package or module.\n    * ``path/to/directory`` -- Search for and run all tests below the named\n      directory.\n\n    If ``test_labels`` has a value of ``None``, the test runner will search for\n    tests in all files below the current directory whose names match its\n    ``pattern`` (see above).\n\n    ``extra_tests`` is a list of extra ``TestCase`` instances to add to the\n    suite that is executed by the test runner. These extra tests are run\n    in addition to those discovered in the modules listed in ``test_labels``.\n\n    Returns a ``TestSuite`` instance ready to be run.\n\n.. method:: DiscoverRunner.setup_databases(**kwargs)\n\n    Creates the test databases by calling\n    :func:`~django.test.utils.setup_databases`.\n\n.. method:: DiscoverRunner.run_checks(databases)\n\n    Runs the :doc:`system checks </topics/checks>` on the test ``databases``.\n\n    .. versionadded:: 3.1\n\n        The ``databases`` parameter was added.\n\n.. method:: DiscoverRunner.run_suite(suite, **kwargs)\n\n    Runs the test suite.\n\n    Returns the result produced by the running the test suite.\n\n.. method:: DiscoverRunner.get_test_runner_kwargs()\n\n    Returns the keyword arguments to instantiate the\n    ``DiscoverRunner.test_runner`` with.\n\n.. method:: DiscoverRunner.teardown_databases(old_config, **kwargs)\n\n    Destroys the test databases, restoring pre-test conditions by calling\n    :func:`~django.test.utils.teardown_databases`.\n\n.. method:: DiscoverRunner.teardown_test_environment(**kwargs)\n\n    Restores the pre-test environment.\n\n.. method:: DiscoverRunner.suite_result(suite, result, **kwargs)\n\n    Computes and returns a return code based on a test suite, and the result\n    from that test suite.\n\n\nTesting utilities\n-----------------\n\n``django.test.utils``\n~~~~~~~~~~~~~~~~~~~~~\n\n.. module:: django.test.utils\n   :synopsis: Helpers to write custom test runners.\n\nTo assist in the creation of your own test runner, Django provides a number of\nutility methods in the ``django.test.utils`` module.\n\n.. function:: setup_test_environment(debug=None)\n\n    Performs global pre-test setup, such as installing instrumentation for the\n    template rendering system and setting up the dummy email outbox.\n\n    If ``debug`` isn't ``None``, the :setting:`DEBUG` setting is updated to its\n    value.\n\n.. function:: teardown_test_environment()\n\n    Performs global post-test teardown, such as removing instrumentation from\n    the template system and restoring normal email services.\n\n.. function:: setup_databases(verbosity, interactive, keepdb=False, debug_sql=False, parallel=0, aliases=None, **kwargs)\n\n    Creates the test databases.\n\n    Returns a data structure that provides enough detail to undo the changes\n    that have been made. This data will be provided to the\n    :func:`teardown_databases` function at the conclusion of testing.\n\n    The ``aliases`` argument determines which :setting:`DATABASES` aliases test\n    databases should be setup for. If it's not provided, it defaults to all of\n    :setting:`DATABASES` aliases.\n\n.. function:: teardown_databases(old_config, parallel=0, keepdb=False)\n\n    Destroys the test databases, restoring pre-test conditions.\n\n    ``old_config`` is a data structure defining the changes in the database\n    configuration that need to be reversed. It's the return value of the\n    :meth:`setup_databases` method.\n\n``django.db.connection.creation``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. currentmodule:: django.db.connection.creation\n\nThe creation module of the database backend also provides some utilities that\ncan be useful during testing.\n\n.. function:: create_test_db(verbosity=1, autoclobber=False, serialize=True, keepdb=False)\n\n    Creates a new test database and runs ``migrate`` against it.\n\n    ``verbosity`` has the same behavior as in ``run_tests()``.\n\n    ``autoclobber`` describes the behavior that will occur if a\n    database with the same name as the test database is discovered:\n\n    * If ``autoclobber`` is ``False``, the user will be asked to\n      approve destroying the existing database. ``sys.exit`` is\n      called if the user does not approve.\n\n    * If autoclobber is ``True``, the database will be destroyed\n      without consulting the user.\n\n    ``serialize`` determines if Django serializes the database into an\n    in-memory JSON string before running tests (used to restore the database\n    state between tests if you don't have transactions). You can set this to\n    ``False`` to speed up creation time if you don't have any test classes\n    with :ref:`serialized_rollback=True <test-case-serialized-rollback>`.\n\n    If you are using the default test runner, you can control this with the\n    the :setting:`SERIALIZE <TEST_SERIALIZE>` entry in the :setting:`TEST\n    <DATABASE-TEST>` dictionary.\n\n    ``keepdb`` determines if the test run should use an existing\n    database, or create a new one. If ``True``, the existing\n    database will be used, or created if not present. If ``False``,\n    a new database will be created, prompting the user to remove\n    the existing one, if present.\n\n    Returns the name of the test database that it created.\n\n    ``create_test_db()`` has the side effect of modifying the value of\n    :setting:`NAME` in :setting:`DATABASES` to match the name of the test\n    database.\n\n.. function:: destroy_test_db(old_database_name, verbosity=1, keepdb=False)\n\n    Destroys the database whose name is the value of :setting:`NAME` in\n    :setting:`DATABASES`, and sets :setting:`NAME` to the value of\n    ``old_database_name``.\n\n    The ``verbosity`` argument has the same behavior as for\n    :class:`~django.test.runner.DiscoverRunner`.\n\n    If the ``keepdb`` argument is ``True``, then the connection to the\n    database will be closed, but the database will not be destroyed.\n\n.. _topics-testing-code-coverage:\n\nIntegration with ``coverage.py``\n================================\n\nCode coverage describes how much source code has been tested. It shows which\nparts of your code are being exercised by tests and which are not. It's an\nimportant part of testing applications, so it's strongly recommended to check\nthe coverage of your tests.\n\nDjango can be easily integrated with `coverage.py`_, a tool for measuring code\ncoverage of Python programs. First, `install coverage.py`_. Next, run the\nfollowing from your project folder containing ``manage.py``::\n\n   coverage run --source='.' manage.py test myapp\n\nThis runs your tests and collects coverage data of the executed files in your\nproject. You can see a report of this data by typing following command::\n\n   coverage report\n\nNote that some Django code was executed while running tests, but it is not\nlisted here because of the ``source`` flag passed to the previous command.\n\nFor more options like annotated HTML listings detailing missed lines, see the\n`coverage.py`_ docs.\n\n.. _coverage.py: https://coverage.readthedocs.io/\n.. _install coverage.py: https://pypi.org/project/coverage/\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":316,"nodeType":"TextFile","repoName":null,"name":"default.txt","path":"docs/topics/auth","text":"======================================\nUsing the Django authentication system\n======================================\n\n.. currentmodule:: django.contrib.auth\n\nThis document explains the usage of Django's authentication system in its\ndefault configuration. This configuration has evolved to serve the most common\nproject needs, handling a reasonably wide range of tasks, and has a careful\nimplementation of passwords and permissions. For projects where authentication\nneeds differ from the default, Django supports extensive :doc:`extension and\ncustomization </topics/auth/customizing>` of authentication.\n\nDjango authentication provides both authentication and authorization together\nand is generally referred to as the authentication system, as these features\nare somewhat coupled.\n\n.. _user-objects:\n\n``User`` objects\n================\n\n:class:`~django.contrib.auth.models.User` objects are the core of the\nauthentication system. They typically represent the people interacting with\nyour site and are used to enable things like restricting access, registering\nuser profiles, associating content with creators etc. Only one class of user\nexists in Django's authentication framework, i.e., :attr:`'superusers'\n<django.contrib.auth.models.User.is_superuser>` or admin :attr:`'staff'\n<django.contrib.auth.models.User.is_staff>` users are just user objects with\nspecial attributes set, not different classes of user objects.\n\nThe primary attributes of the default user are:\n\n* :attr:`~django.contrib.auth.models.User.username`\n* :attr:`~django.contrib.auth.models.User.password`\n* :attr:`~django.contrib.auth.models.User.email`\n* :attr:`~django.contrib.auth.models.User.first_name`\n* :attr:`~django.contrib.auth.models.User.last_name`\n\nSee the :class:`full API documentation <django.contrib.auth.models.User>` for\nfull reference, the documentation that follows is more task oriented.\n\n.. _topics-auth-creating-users:\n\nCreating users\n--------------\n\nThe most direct way to create users is to use the included\n:meth:`~django.contrib.auth.models.UserManager.create_user` helper function::\n\n    >>> from django.contrib.auth.models import User\n    >>> user = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')\n\n    # At this point, user is a User object that has already been saved\n    # to the database. You can continue to change its attributes\n    # if you want to change other fields.\n    >>> user.last_name = 'Lennon'\n    >>> user.save()\n\nIf you have the Django admin installed, you can also :ref:`create users\ninteractively <auth-admin>`.\n\n.. _topics-auth-creating-superusers:\n\nCreating superusers\n-------------------\n\nCreate superusers using the :djadmin:`createsuperuser` command::\n\n    $ python manage.py createsuperuser --username=joe --email=joe@example.com\n\nYou will be prompted for a password. After you enter one, the user will be\ncreated immediately. If you leave off the :option:`--username <createsuperuser\n--username>` or :option:`--email <createsuperuser --email>` options, it will\nprompt you for those values.\n\nChanging passwords\n------------------\n\nDjango does not store raw (clear text) passwords on the user model, but only\na hash (see :doc:`documentation of how passwords are managed\n</topics/auth/passwords>` for full details). Because of this, do not attempt to\nmanipulate the password attribute of the user directly. This is why a helper\nfunction is used when creating a user.\n\nTo change a user's password, you have several options:\n\n:djadmin:`manage.py changepassword *username* <changepassword>` offers a method\nof changing a user's password from the command line. It prompts you to\nchange the password of a given user which you must enter twice. If\nthey both match, the new password will be changed immediately. If you\ndo not supply a user, the command will attempt to change the password\nwhose username matches the current system user.\n\nYou can also change a password programmatically, using\n:meth:`~django.contrib.auth.models.User.set_password()`:\n\n.. code-block:: pycon\n\n    >>> from django.contrib.auth.models import User\n    >>> u = User.objects.get(username='john')\n    >>> u.set_password('new password')\n    >>> u.save()\n\nIf you have the Django admin installed, you can also change user's passwords\non the :ref:`authentication system's admin pages <auth-admin>`.\n\nDjango also provides :ref:`views <built-in-auth-views>` and :ref:`forms\n<built-in-auth-forms>` that may be used to allow users to change their own\npasswords.\n\nChanging a user's password will log out all their sessions. See\n:ref:`session-invalidation-on-password-change` for details.\n\nAuthenticating users\n--------------------\n\n.. function:: authenticate(request=None, **credentials)\n\n    Use :func:`~django.contrib.auth.authenticate()` to verify a set of\n    credentials. It takes credentials as keyword arguments, ``username`` and\n    ``password`` for the default case, checks them against each\n    :ref:`authentication backend <authentication-backends>`, and returns a\n    :class:`~django.contrib.auth.models.User` object if the credentials are\n    valid for a backend. If the credentials aren't valid for any backend or if\n    a backend raises :class:`~django.core.exceptions.PermissionDenied`, it\n    returns ``None``. For example::\n\n        from django.contrib.auth import authenticate\n        user = authenticate(username='john', password='secret')\n        if user is not None:\n            # A backend authenticated the credentials\n        else:\n            # No backend authenticated the credentials\n\n    ``request`` is an optional :class:`~django.http.HttpRequest` which is\n    passed on the ``authenticate()`` method of the authentication backends.\n\n    .. note::\n\n        This is a low level way to authenticate a set of credentials; for\n        example, it's used by the\n        :class:`~django.contrib.auth.middleware.RemoteUserMiddleware`. Unless\n        you are writing your own authentication system, you probably won't use\n        this. Rather if you're looking for a way to login a user, use the\n        :class:`~django.contrib.auth.views.LoginView`.\n\n.. _topic-authorization:\n\nPermissions and Authorization\n=============================\n\nDjango comes with a built-in permissions system. It provides a way to assign\npermissions to specific users and groups of users.\n\nIt's used by the Django admin site, but you're welcome to use it in your own\ncode.\n\nThe Django admin site uses permissions as follows:\n\n* Access to view objects is limited to users with the \"view\" or \"change\"\n  permission for that type of object.\n* Access to view the \"add\" form and add an object is limited to users with\n  the \"add\" permission for that type of object.\n* Access to view the change list, view the \"change\" form and change an\n  object is limited to users with the \"change\" permission for that type of\n  object.\n* Access to delete an object is limited to users with the \"delete\"\n  permission for that type of object.\n\nPermissions can be set not only per type of object, but also per specific\nobject instance. By using the\n:meth:`~django.contrib.admin.ModelAdmin.has_view_permission`,\n:meth:`~django.contrib.admin.ModelAdmin.has_add_permission`,\n:meth:`~django.contrib.admin.ModelAdmin.has_change_permission` and\n:meth:`~django.contrib.admin.ModelAdmin.has_delete_permission` methods provided\nby the :class:`~django.contrib.admin.ModelAdmin` class, it is possible to\ncustomize permissions for different object instances of the same type.\n\n:class:`~django.contrib.auth.models.User` objects have two many-to-many\nfields: ``groups`` and ``user_permissions``.\n:class:`~django.contrib.auth.models.User` objects can access their related\nobjects in the same way as any other :doc:`Django model\n</topics/db/models>`::\n\n    myuser.groups.set([group_list])\n    myuser.groups.add(group, group, ...)\n    myuser.groups.remove(group, group, ...)\n    myuser.groups.clear()\n    myuser.user_permissions.set([permission_list])\n    myuser.user_permissions.add(permission, permission, ...)\n    myuser.user_permissions.remove(permission, permission, ...)\n    myuser.user_permissions.clear()\n\nDefault permissions\n-------------------\n\nWhen ``django.contrib.auth`` is listed in your :setting:`INSTALLED_APPS`\nsetting, it will ensure that four default permissions -- add, change, delete,\nand view -- are created for each Django model defined in one of your installed\napplications.\n\nThese permissions will be created when you run :djadmin:`manage.py migrate\n<migrate>`; the first time you run ``migrate`` after adding\n``django.contrib.auth`` to :setting:`INSTALLED_APPS`, the default permissions\nwill be created for all previously-installed models, as well as for any new\nmodels being installed at that time. Afterward, it will create default\npermissions for new models each time you run :djadmin:`manage.py migrate\n<migrate>` (the function that creates permissions is connected to the\n:data:`~django.db.models.signals.post_migrate` signal).\n\nAssuming you have an application with an\n:attr:`~django.db.models.Options.app_label` ``foo`` and a model named ``Bar``,\nto test for basic permissions you should use:\n\n* add: ``user.has_perm('foo.add_bar')``\n* change: ``user.has_perm('foo.change_bar')``\n* delete: ``user.has_perm('foo.delete_bar')``\n* view: ``user.has_perm('foo.view_bar')``\n\nThe :class:`~django.contrib.auth.models.Permission` model is rarely accessed\ndirectly.\n\nGroups\n------\n\n:class:`django.contrib.auth.models.Group` models are a generic way of\ncategorizing users so you can apply permissions, or some other label, to those\nusers. A user can belong to any number of groups.\n\nA user in a group automatically has the permissions granted to that group. For\nexample, if the group ``Site editors`` has the permission\n``can_edit_home_page``, any user in that group will have that permission.\n\nBeyond permissions, groups are a convenient way to categorize users to give\nthem some label, or extended functionality. For example, you could create a\ngroup ``'Special users'``, and you could write code that could, say, give them\naccess to a members-only portion of your site, or send them members-only email\nmessages.\n\nProgrammatically creating permissions\n-------------------------------------\n\nWhile :ref:`custom permissions <custom-permissions>` can be defined within\na model's ``Meta`` class, you can also create permissions directly. For\nexample, you can create the ``can_publish`` permission for a ``BlogPost`` model\nin ``myapp``::\n\n    from myapp.models import BlogPost\n    from django.contrib.auth.models import Permission\n    from django.contrib.contenttypes.models import ContentType\n\n    content_type = ContentType.objects.get_for_model(BlogPost)\n    permission = Permission.objects.create(\n        codename='can_publish',\n        name='Can Publish Posts',\n        content_type=content_type,\n    )\n\nThe permission can then be assigned to a\n:class:`~django.contrib.auth.models.User` via its ``user_permissions``\nattribute or to a :class:`~django.contrib.auth.models.Group` via its\n``permissions`` attribute.\n\n.. admonition:: Proxy models need their own content type\n\n    If you want to create :ref:`permissions for a proxy model\n    <proxy-models-permissions-topic>`, pass ``for_concrete_model=False`` to\n    :meth:`.ContentTypeManager.get_for_model` to get the appropriate\n    ``ContentType``::\n\n        content_type = ContentType.objects.get_for_model(BlogPostProxy, for_concrete_model=False)\n\nPermission caching\n------------------\n\nThe :class:`~django.contrib.auth.backends.ModelBackend` caches permissions on\nthe user object after the first time they need to be fetched for a permissions\ncheck. This is typically fine for the request-response cycle since permissions\naren't typically checked immediately after they are added (in the admin, for\nexample). If you are adding permissions and checking them immediately\nafterward, in a test or view for example, the easiest solution is to re-fetch\nthe user from the database. For example::\n\n    from django.contrib.auth.models import Permission, User\n    from django.contrib.contenttypes.models import ContentType\n    from django.shortcuts import get_object_or_404\n\n    from myapp.models import BlogPost\n\n    def user_gains_perms(request, user_id):\n        user = get_object_or_404(User, pk=user_id)\n        # any permission check will cache the current set of permissions\n        user.has_perm('myapp.change_blogpost')\n\n        content_type = ContentType.objects.get_for_model(BlogPost)\n        permission = Permission.objects.get(\n            codename='change_blogpost',\n            content_type=content_type,\n        )\n        user.user_permissions.add(permission)\n\n        # Checking the cached permission set\n        user.has_perm('myapp.change_blogpost')  # False\n\n        # Request new instance of User\n        # Be aware that user.refresh_from_db() won't clear the cache.\n        user = get_object_or_404(User, pk=user_id)\n\n        # Permission cache is repopulated from the database\n        user.has_perm('myapp.change_blogpost')  # True\n\n        ...\n\n.. _proxy-models-permissions-topic:\n\nProxy models\n------------\n\nProxy models work exactly the same way as concrete models. Permissions are\ncreated using the own content type of the proxy model. Proxy models don't\ninherit the permissions of the concrete model they subclass::\n\n    class Person(models.Model):\n        class Meta:\n            permissions = [('can_eat_pizzas', 'Can eat pizzas')]\n\n    class Student(Person):\n        class Meta:\n            proxy = True\n            permissions = [('can_deliver_pizzas', 'Can deliver pizzas')]\n\n    >>> # Fetch the content type for the proxy model.\n    >>> content_type = ContentType.objects.get_for_model(Student, for_concrete_model=False)\n    >>> student_permissions = Permission.objects.filter(content_type=content_type)\n    >>> [p.codename for p in student_permissions]\n    ['add_student', 'change_student', 'delete_student', 'view_student',\n    'can_deliver_pizzas']\n    >>> for permission in student_permissions:\n    ...     user.user_permissions.add(permission)\n    >>> user.has_perm('app.add_person')\n    False\n    >>> user.has_perm('app.can_eat_pizzas')\n    False\n    >>> user.has_perms(('app.add_student', 'app.can_deliver_pizzas'))\n    True\n\n.. _auth-web-requests:\n\nAuthentication in Web requests\n==============================\n\nDjango uses :doc:`sessions </topics/http/sessions>` and middleware to hook the\nauthentication system into :class:`request objects <django.http.HttpRequest>`.\n\nThese provide a :attr:`request.user <django.http.HttpRequest.user>`  attribute\non every request which represents the current user. If the current user has not\nlogged in, this attribute will be set to an instance\nof :class:`~django.contrib.auth.models.AnonymousUser`, otherwise it will be an\ninstance of :class:`~django.contrib.auth.models.User`.\n\nYou can tell them apart with\n:attr:`~django.contrib.auth.models.User.is_authenticated`, like so::\n\n    if request.user.is_authenticated:\n        # Do something for authenticated users.\n        ...\n    else:\n        # Do something for anonymous users.\n        ...\n\n.. _how-to-log-a-user-in:\n\nHow to log a user in\n--------------------\n\nIf you have an authenticated user you want to attach to the current session\n- this is done with a :func:`~django.contrib.auth.login` function.\n\n.. function:: login(request, user, backend=None)\n\n    To log a user in, from a view, use :func:`~django.contrib.auth.login()`. It\n    takes an :class:`~django.http.HttpRequest` object and a\n    :class:`~django.contrib.auth.models.User` object.\n    :func:`~django.contrib.auth.login()` saves the user's ID in the session,\n    using Django's session framework.\n\n    Note that any data set during the anonymous session is retained in the\n    session after a user logs in.\n\n    This example shows how you might use both\n    :func:`~django.contrib.auth.authenticate()` and\n    :func:`~django.contrib.auth.login()`::\n\n        from django.contrib.auth import authenticate, login\n\n        def my_view(request):\n            username = request.POST['username']\n            password = request.POST['password']\n            user = authenticate(request, username=username, password=password)\n            if user is not None:\n                login(request, user)\n                # Redirect to a success page.\n                ...\n            else:\n                # Return an 'invalid login' error message.\n                ...\n\nSelecting the authentication backend\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nWhen a user logs in, the user's ID and the backend that was used for\nauthentication are saved in the user's session. This allows the same\n:ref:`authentication backend <authentication-backends>` to fetch the user's\ndetails on a future request. The authentication backend to save in the session\nis selected as follows:\n\n#. Use the value of the optional ``backend`` argument, if provided.\n#. Use the value of the ``user.backend`` attribute, if present. This allows\n   pairing :func:`~django.contrib.auth.authenticate()` and\n   :func:`~django.contrib.auth.login()`:\n   :func:`~django.contrib.auth.authenticate()`\n   sets the ``user.backend`` attribute on the user object it returns.\n#. Use the ``backend`` in :setting:`AUTHENTICATION_BACKENDS`, if there is only\n   one.\n#. Otherwise, raise an exception.\n\nIn cases 1 and 2, the value of the ``backend`` argument or the ``user.backend``\nattribute should be a dotted import path string (like that found in\n:setting:`AUTHENTICATION_BACKENDS`), not the actual backend class.\n\nHow to log a user out\n---------------------\n\n.. function:: logout(request)\n\n    To log out a user who has been logged in via\n    :func:`django.contrib.auth.login()`, use\n    :func:`django.contrib.auth.logout()` within your view. It takes an\n    :class:`~django.http.HttpRequest` object and has no return value.\n    Example::\n\n        from django.contrib.auth import logout\n\n        def logout_view(request):\n            logout(request)\n            # Redirect to a success page.\n\n    Note that :func:`~django.contrib.auth.logout()` doesn't throw any errors if\n    the user wasn't logged in.\n\n    When you call :func:`~django.contrib.auth.logout()`, the session data for\n    the current request is completely cleaned out. All existing data is\n    removed. This is to prevent another person from using the same Web browser\n    to log in and have access to the previous user's session data. If you want\n    to put anything into the session that will be available to the user\n    immediately after logging out, do that *after* calling\n    :func:`django.contrib.auth.logout()`.\n\nLimiting access to logged-in users\n----------------------------------\n\nThe raw way\n~~~~~~~~~~~\n\nThe raw way to limit access to pages is to check\n:attr:`request.user.is_authenticated\n<django.contrib.auth.models.User.is_authenticated>` and either redirect to a\nlogin page::\n\n    from django.conf import settings\n    from django.shortcuts import redirect\n\n    def my_view(request):\n        if not request.user.is_authenticated:\n            return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))\n        # ...\n\n...or display an error message::\n\n    from django.shortcuts import render\n\n    def my_view(request):\n        if not request.user.is_authenticated:\n            return render(request, 'myapp/login_error.html')\n        # ...\n\n.. currentmodule:: django.contrib.auth.decorators\n\nThe ``login_required`` decorator\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. function:: login_required(redirect_field_name='next', login_url=None)\n\n    As a shortcut, you can use the convenient\n    :func:`~django.contrib.auth.decorators.login_required` decorator::\n\n        from django.contrib.auth.decorators import login_required\n\n        @login_required\n        def my_view(request):\n            ...\n\n    :func:`~django.contrib.auth.decorators.login_required` does the following:\n\n    * If the user isn't logged in, redirect to\n      :setting:`settings.LOGIN_URL <LOGIN_URL>`, passing the current absolute\n      path in the query string. Example: ``/accounts/login/?next=/polls/3/``.\n\n    * If the user is logged in, execute the view normally. The view code is\n      free to assume the user is logged in.\n\n    By default, the path that the user should be redirected to upon\n    successful authentication is stored in a query string parameter called\n    ``\"next\"``. If you would prefer to use a different name for this parameter,\n    :func:`~django.contrib.auth.decorators.login_required` takes an\n    optional ``redirect_field_name`` parameter::\n\n        from django.contrib.auth.decorators import login_required\n\n        @login_required(redirect_field_name='my_redirect_field')\n        def my_view(request):\n            ...\n\n    Note that if you provide a value to ``redirect_field_name``, you will most\n    likely need to customize your login template as well, since the template\n    context variable which stores the redirect path will use the value of\n    ``redirect_field_name`` as its key rather than ``\"next\"`` (the default).\n\n    :func:`~django.contrib.auth.decorators.login_required` also takes an\n    optional ``login_url`` parameter. Example::\n\n        from django.contrib.auth.decorators import login_required\n\n        @login_required(login_url='/accounts/login/')\n        def my_view(request):\n            ...\n\n    Note that if you don't specify the ``login_url`` parameter, you'll need to\n    ensure that the :setting:`settings.LOGIN_URL <LOGIN_URL>` and your login\n    view are properly associated. For example, using the defaults, add the\n    following lines to your URLconf::\n\n        from django.contrib.auth import views as auth_views\n\n        path('accounts/login/', auth_views.LoginView.as_view()),\n\n    The :setting:`settings.LOGIN_URL <LOGIN_URL>` also accepts view function\n    names and :ref:`named URL patterns <naming-url-patterns>`. This allows you\n    to freely remap your login view within your URLconf without having to\n    update the setting.\n\n.. note::\n\n    The ``login_required`` decorator does NOT check the ``is_active`` flag on a\n    user, but the default :setting:`AUTHENTICATION_BACKENDS` reject inactive\n    users.\n\n.. seealso::\n\n    If you are writing custom views for Django's admin (or need the same\n    authorization check that the built-in views use), you may find the\n    :func:`django.contrib.admin.views.decorators.staff_member_required`\n    decorator a useful alternative to ``login_required()``.\n\n.. currentmodule:: django.contrib.auth.mixins\n\nThe ``LoginRequired`` mixin\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nWhen using :doc:`class-based views </topics/class-based-views/index>`, you can\nachieve the same behavior as with ``login_required`` by using the\n``LoginRequiredMixin``. This mixin should be at the leftmost position in the\ninheritance list.\n\n.. class:: LoginRequiredMixin\n\n    If a view is using this mixin, all requests by non-authenticated users will\n    be redirected to the login page or shown an HTTP 403 Forbidden error,\n    depending on the\n    :attr:`~django.contrib.auth.mixins.AccessMixin.raise_exception` parameter.\n\n    You can set any of the parameters of\n    :class:`~django.contrib.auth.mixins.AccessMixin` to customize the handling\n    of unauthorized users::\n\n\n        from django.contrib.auth.mixins import LoginRequiredMixin\n\n        class MyView(LoginRequiredMixin, View):\n            login_url = '/login/'\n            redirect_field_name = 'redirect_to'\n\n.. note::\n\n    Just as the ``login_required`` decorator, this mixin does NOT check the\n    ``is_active`` flag on a user, but the default\n    :setting:`AUTHENTICATION_BACKENDS` reject inactive users.\n\n.. currentmodule:: django.contrib.auth.decorators\n\nLimiting access to logged-in users that pass a test\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nTo limit access based on certain permissions or some other test, you'd do\nessentially the same thing as described in the previous section.\n\nYou can run your test on :attr:`request.user <django.http.HttpRequest.user>` in\nthe view directly. For example, this view checks to make sure the user has an\nemail in the desired domain and if not, redirects to the login page::\n\n    from django.shortcuts import redirect\n\n    def my_view(request):\n        if not request.user.email.endswith('@example.com'):\n            return redirect('/login/?next=%s' % request.path)\n        # ...\n\n.. function:: user_passes_test(test_func, login_url=None, redirect_field_name='next')\n\n    As a shortcut, you can use the convenient ``user_passes_test`` decorator\n    which performs a redirect when the callable returns ``False``::\n\n        from django.contrib.auth.decorators import user_passes_test\n\n        def email_check(user):\n            return user.email.endswith('@example.com')\n\n        @user_passes_test(email_check)\n        def my_view(request):\n            ...\n\n    :func:`~django.contrib.auth.decorators.user_passes_test` takes a required\n    argument: a callable that takes a\n    :class:`~django.contrib.auth.models.User` object and returns ``True`` if\n    the user is allowed to view the page. Note that\n    :func:`~django.contrib.auth.decorators.user_passes_test` does not\n    automatically check that the :class:`~django.contrib.auth.models.User` is\n    not anonymous.\n\n    :func:`~django.contrib.auth.decorators.user_passes_test` takes two\n    optional arguments:\n\n    ``login_url``\n       Lets you specify the URL that users who don't pass the test will be\n       redirected to. It may be a login page and defaults to\n       :setting:`settings.LOGIN_URL <LOGIN_URL>` if you don't specify one.\n\n    ``redirect_field_name``\n       Same as for :func:`~django.contrib.auth.decorators.login_required`.\n       Setting it to ``None`` removes it from the URL, which you may want to do\n       if you are redirecting users that don't pass the test to a non-login\n       page where there's no \"next page\".\n\n    For example::\n\n        @user_passes_test(email_check, login_url='/login/')\n        def my_view(request):\n            ...\n\n.. currentmodule:: django.contrib.auth.mixins\n\n.. class:: UserPassesTestMixin\n\n    When using :doc:`class-based views </topics/class-based-views/index>`, you\n    can use the ``UserPassesTestMixin`` to do this.\n\n    .. method:: test_func()\n\n        You have to override the ``test_func()`` method of the class to\n        provide the test that is performed. Furthermore, you can set any of the\n        parameters of :class:`~django.contrib.auth.mixins.AccessMixin` to\n        customize the handling of unauthorized users::\n\n            from django.contrib.auth.mixins import UserPassesTestMixin\n\n            class MyView(UserPassesTestMixin, View):\n\n                def test_func(self):\n                    return self.request.user.email.endswith('@example.com')\n\n    .. method:: get_test_func()\n\n        You can also override the ``get_test_func()`` method to have the mixin\n        use a differently named function for its checks (instead of\n        :meth:`test_func`).\n\n    .. admonition:: Stacking ``UserPassesTestMixin``\n\n        Due to the way ``UserPassesTestMixin`` is implemented, you cannot stack\n        them in your inheritance list. The following does NOT work::\n\n            class TestMixin1(UserPassesTestMixin):\n                def test_func(self):\n                    return self.request.user.email.endswith('@example.com')\n\n            class TestMixin2(UserPassesTestMixin):\n                def test_func(self):\n                    return self.request.user.username.startswith('django')\n\n            class MyView(TestMixin1, TestMixin2, View):\n                ...\n\n        If ``TestMixin1`` would call ``super()`` and take that result into\n        account, ``TestMixin1`` wouldn't work standalone anymore.\n\n.. currentmodule:: django.contrib.auth.decorators\n\nThe ``permission_required`` decorator\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. function:: permission_required(perm, login_url=None, raise_exception=False)\n\n    It's a relatively common task to check whether a user has a particular\n    permission. For that reason, Django provides a shortcut for that case: the\n    :func:`~django.contrib.auth.decorators.permission_required()` decorator.::\n\n        from django.contrib.auth.decorators import permission_required\n\n        @permission_required('polls.add_choice')\n        def my_view(request):\n            ...\n\n    Just like the :meth:`~django.contrib.auth.models.User.has_perm` method,\n    permission names take the form ``\"<app label>.<permission codename>\"``\n    (i.e. ``polls.add_choice`` for a permission on a model in the ``polls``\n    application).\n\n    The decorator may also take an iterable of permissions, in which case the\n    user must have all of the permissions in order to access the view.\n\n    Note that :func:`~django.contrib.auth.decorators.permission_required()`\n    also takes an optional ``login_url`` parameter::\n\n        from django.contrib.auth.decorators import permission_required\n\n        @permission_required('polls.add_choice', login_url='/loginpage/')\n        def my_view(request):\n            ...\n\n    As in the :func:`~django.contrib.auth.decorators.login_required` decorator,\n    ``login_url`` defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>`.\n\n    If the ``raise_exception`` parameter is given, the decorator will raise\n    :exc:`~django.core.exceptions.PermissionDenied`, prompting :ref:`the 403\n    (HTTP Forbidden) view<http_forbidden_view>` instead of redirecting to the\n    login page.\n\n    If you want to use ``raise_exception`` but also give your users a chance to\n    login first, you can add the\n    :func:`~django.contrib.auth.decorators.login_required` decorator::\n\n        from django.contrib.auth.decorators import login_required, permission_required\n\n        @login_required\n        @permission_required('polls.add_choice', raise_exception=True)\n        def my_view(request):\n            ...\n\n    This also avoids a redirect loop when :class:`.LoginView`'s\n    ``redirect_authenticated_user=True`` and the logged-in user doesn't have\n    all of the required permissions.\n\n.. currentmodule:: django.contrib.auth.mixins\n\nThe ``PermissionRequiredMixin`` mixin\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nTo apply permission checks to :doc:`class-based views\n</ref/class-based-views/index>`, you can use the ``PermissionRequiredMixin``:\n\n.. class:: PermissionRequiredMixin\n\n    This mixin, just like the ``permission_required``\n    decorator, checks whether the user accessing a view has all given\n    permissions. You should specify the permission (or an iterable of\n    permissions) using the ``permission_required`` parameter::\n\n        from django.contrib.auth.mixins import PermissionRequiredMixin\n\n        class MyView(PermissionRequiredMixin, View):\n            permission_required = 'polls.add_choice'\n            # Or multiple of permissions:\n            permission_required = ('polls.view_choice', 'polls.change_choice')\n\n    You can set any of the parameters of\n    :class:`~django.contrib.auth.mixins.AccessMixin` to customize the handling\n    of unauthorized users.\n\n    You may also override these methods:\n\n    .. method:: get_permission_required()\n\n        Returns an iterable of permission names used by the mixin. Defaults to\n        the ``permission_required`` attribute, converted to a tuple if\n        necessary.\n\n    .. method:: has_permission()\n\n        Returns a boolean denoting whether the current user has permission to\n        execute the decorated view. By default, this returns the result of\n        calling :meth:`~django.contrib.auth.models.User.has_perms()` with the\n        list of permissions returned by :meth:`get_permission_required()`.\n\nRedirecting unauthorized requests in class-based views\n------------------------------------------------------\n\nTo ease the handling of access restrictions in :doc:`class-based views\n</ref/class-based-views/index>`, the ``AccessMixin`` can be used to configure\nthe behavior of a view when access is denied. Authenticated users are denied\naccess with an HTTP 403 Forbidden response. Anonymous users are redirected to\nthe login page or shown an HTTP 403 Forbidden response, depending on the\n:attr:`~django.contrib.auth.mixins.AccessMixin.raise_exception` attribute.\n\n.. class:: AccessMixin\n\n    .. attribute:: login_url\n\n        Default return value for :meth:`get_login_url`.  Defaults to ``None``\n        in which case :meth:`get_login_url` falls back to\n        :setting:`settings.LOGIN_URL <LOGIN_URL>`.\n\n    .. attribute:: permission_denied_message\n\n        Default return value for :meth:`get_permission_denied_message`.\n        Defaults to an empty string.\n\n    .. attribute:: redirect_field_name\n\n        Default return value for :meth:`get_redirect_field_name`. Defaults to\n        ``\"next\"``.\n\n    .. attribute:: raise_exception\n\n        If this attribute is set to ``True``, a\n        :class:`~django.core.exceptions.PermissionDenied` exception is raised\n        when the conditions are not met.  When ``False`` (the default),\n        anonymous users are redirected to the login page.\n\n    .. method:: get_login_url()\n\n         Returns the URL that users who don't pass the test will be redirected\n         to. Returns :attr:`login_url` if set, or :setting:`settings.LOGIN_URL\n         <LOGIN_URL>` otherwise.\n\n    .. method:: get_permission_denied_message()\n\n        When :attr:`raise_exception` is ``True``, this method can be used to\n        control the error message passed to the error handler for display to\n        the user. Returns the :attr:`permission_denied_message` attribute by\n        default.\n\n    .. method:: get_redirect_field_name()\n\n        Returns the name of the query parameter that will contain the URL the\n        user should be redirected to after a successful login. If you set this\n        to ``None``, a query parameter won't be added. Returns the\n        :attr:`redirect_field_name` attribute by default.\n\n    .. method:: handle_no_permission()\n\n        Depending on the value of ``raise_exception``, the method either raises\n        a :exc:`~django.core.exceptions.PermissionDenied` exception or\n        redirects the user to the ``login_url``, optionally including the\n        ``redirect_field_name`` if it is set.\n\n.. currentmodule:: django.contrib.auth\n\n.. _session-invalidation-on-password-change:\n\nSession invalidation on password change\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf your :setting:`AUTH_USER_MODEL` inherits from\n:class:`~django.contrib.auth.models.AbstractBaseUser` or implements its own\n:meth:`~django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash()`\nmethod, authenticated sessions will include the hash returned by this function.\nIn the :class:`~django.contrib.auth.models.AbstractBaseUser` case, this is an\nHMAC of the password field. Django verifies that the hash in the session for\neach request matches the one that's computed during the request. This allows a\nuser to log out all of their sessions by changing their password.\n\nThe default password change views included with Django,\n:class:`~django.contrib.auth.views.PasswordChangeView` and the\n``user_change_password`` view in the :mod:`django.contrib.auth` admin, update\nthe session with the new password hash so that a user changing their own\npassword won't log themselves out. If you have a custom password change view\nand wish to have similar behavior, use the :func:`update_session_auth_hash`\nfunction.\n\n.. function:: update_session_auth_hash(request, user)\n\n    This function takes the current request and the updated user object from\n    which the new session hash will be derived and updates the session hash\n    appropriately. It also rotates the session key so that a stolen session\n    cookie will be invalidated.\n\n    Example usage::\n\n        from django.contrib.auth import update_session_auth_hash\n\n        def password_change(request):\n            if request.method == 'POST':\n                form = PasswordChangeForm(user=request.user, data=request.POST)\n                if form.is_valid():\n                    form.save()\n                    update_session_auth_hash(request, form.user)\n            else:\n                ...\n\n.. note::\n\n    Since\n    :meth:`~django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash()`\n    is based on :setting:`SECRET_KEY`, updating your site to use a new secret\n    will invalidate all existing sessions.\n\n.. _built-in-auth-views:\n\nAuthentication Views\n--------------------\n\n.. module:: django.contrib.auth.views\n\nDjango provides several views that you can use for handling login, logout, and\npassword management. These make use of the :ref:`stock auth forms\n<built-in-auth-forms>` but you can pass in your own forms as well.\n\nDjango provides no default template for the authentication views. You should\ncreate your own templates for the views you want to use. The template context\nis documented in each view, see :ref:`all-authentication-views`.\n\n.. _using-the-views:\n\nUsing the views\n~~~~~~~~~~~~~~~\n\nThere are different methods to implement these views in your project. The\neasiest way is to include the provided URLconf in ``django.contrib.auth.urls``\nin your own URLconf, for example::\n\n    urlpatterns = [\n        path('accounts/', include('django.contrib.auth.urls')),\n    ]\n\nThis will include the following URL patterns::\n\n    accounts/login/ [name='login']\n    accounts/logout/ [name='logout']\n    accounts/password_change/ [name='password_change']\n    accounts/password_change/done/ [name='password_change_done']\n    accounts/password_reset/ [name='password_reset']\n    accounts/password_reset/done/ [name='password_reset_done']\n    accounts/reset/<uidb64>/<token>/ [name='password_reset_confirm']\n    accounts/reset/done/ [name='password_reset_complete']\n\nThe views provide a URL name for easier reference. See :doc:`the URL\ndocumentation </topics/http/urls>` for details on using named URL patterns.\n\nIf you want more control over your URLs, you can reference a specific view in\nyour URLconf::\n\n    from django.contrib.auth import views as auth_views\n\n    urlpatterns = [\n        path('change-password/', auth_views.PasswordChangeView.as_view()),\n    ]\n\nThe views have optional arguments you can use to alter the behavior of the\nview. For example, if you want to change the template name a view uses, you can\nprovide the ``template_name`` argument. A way to do this is to provide keyword\narguments in the URLconf, these will be passed on to the view. For example::\n\n    urlpatterns = [\n        path(\n            'change-password/',\n            auth_views.PasswordChangeView.as_view(template_name='change-password.html'),\n        ),\n    ]\n\nAll views are :doc:`class-based </topics/class-based-views/index>`, which allows\nyou to easily customize them by subclassing.\n\n.. _all-authentication-views:\n\nAll authentication views\n~~~~~~~~~~~~~~~~~~~~~~~~\n\nThis is a list with all the views ``django.contrib.auth`` provides. For\nimplementation details see :ref:`using-the-views`.\n\n.. class:: LoginView\n\n    **URL name:** ``login``\n\n    See :doc:`the URL documentation </topics/http/urls>` for details on using\n    named URL patterns.\n\n    **Attributes:**\n\n    * ``template_name``: The name of a template to display for the view used to\n      log the user in. Defaults to :file:`registration/login.html`.\n\n    * ``redirect_field_name``: The name of a ``GET`` field containing the\n      URL to redirect to after login. Defaults to ``next``.\n\n    * ``authentication_form``: A callable (typically a form class) to use for\n      authentication. Defaults to\n      :class:`~django.contrib.auth.forms.AuthenticationForm`.\n\n    * ``extra_context``: A dictionary of context data that will be added to the\n      default context data passed to the template.\n\n    * ``redirect_authenticated_user``: A boolean that controls whether or not\n      authenticated users accessing the login page will be redirected as if\n      they had just successfully logged in. Defaults to ``False``.\n\n      .. warning::\n\n        If you enable ``redirect_authenticated_user``, other websites will be\n        able to determine if their visitors are authenticated on your site by\n        requesting redirect URLs to image files on your website. To avoid\n        this \"`social media fingerprinting\n        <https://robinlinus.github.io/socialmedia-leak/>`_\" information\n        leakage, host all images and your favicon on a separate domain.\n\n        Enabling ``redirect_authenticated_user`` can also result in a redirect\n        loop when using the :func:`.permission_required` decorator\n        unless the ``raise_exception`` parameter is used.\n\n    * ``success_url_allowed_hosts``: A :class:`set` of hosts, in addition to\n      :meth:`request.get_host() <django.http.HttpRequest.get_host>`, that are\n      safe for redirecting after login. Defaults to an empty :class:`set`.\n\n    Here's what ``LoginView`` does:\n\n    * If called via ``GET``, it displays a login form that POSTs to the\n      same URL. More on this in a bit.\n\n    * If called via ``POST`` with user submitted credentials, it tries to log\n      the user in. If login is successful, the view redirects to the URL\n      specified in ``next``. If ``next`` isn't provided, it redirects to\n      :setting:`settings.LOGIN_REDIRECT_URL <LOGIN_REDIRECT_URL>` (which\n      defaults to ``/accounts/profile/``). If login isn't successful, it\n      redisplays the login form.\n\n    It's your responsibility to provide the html for the login template\n    , called ``registration/login.html`` by default. This template gets passed\n    four template context variables:\n\n    * ``form``: A :class:`~django.forms.Form` object representing the\n      :class:`~django.contrib.auth.forms.AuthenticationForm`.\n\n    * ``next``: The URL to redirect to after successful login. This may\n      contain a query string, too.\n\n    * ``site``: The current :class:`~django.contrib.sites.models.Site`,\n      according to the :setting:`SITE_ID` setting. If you don't have the\n      site framework installed, this will be set to an instance of\n      :class:`~django.contrib.sites.requests.RequestSite`, which derives the\n      site name and domain from the current\n      :class:`~django.http.HttpRequest`.\n\n    * ``site_name``: An alias for ``site.name``. If you don't have the site\n      framework installed, this will be set to the value of\n      :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.\n      For more on sites, see :doc:`/ref/contrib/sites`.\n\n    If you'd prefer not to call the template :file:`registration/login.html`,\n    you can pass the ``template_name`` parameter via the extra arguments to\n    the ``as_view`` method in your URLconf. For example, this URLconf line would\n    use :file:`myapp/login.html` instead::\n\n        path('accounts/login/', auth_views.LoginView.as_view(template_name='myapp/login.html')),\n\n    You can also specify the name of the ``GET`` field which contains the URL\n    to redirect to after login using ``redirect_field_name``. By default, the\n    field is called ``next``.\n\n    Here's a sample :file:`registration/login.html` template you can use as a\n    starting point. It assumes you have a :file:`base.html` template that\n    defines a ``content`` block:\n\n    .. code-block:: html+django\n\n        {% extends \"base.html\" %}\n\n        {% block content %}\n\n        {% if form.errors %}\n        <p>Your username and password didn't match. Please try again.</p>\n        {% endif %}\n\n        {% if next %}\n            {% if user.is_authenticated %}\n            <p>Your account doesn't have access to this page. To proceed,\n            please login with an account that has access.</p>\n            {% else %}\n            <p>Please login to see this page.</p>\n            {% endif %}\n        {% endif %}\n\n        <form method=\"post\" action=\"{% url 'login' %}\">\n        {% csrf_token %}\n        <table>\n        <tr>\n            <td>{{ form.username.label_tag }}</td>\n            <td>{{ form.username }}</td>\n        </tr>\n        <tr>\n            <td>{{ form.password.label_tag }}</td>\n            <td>{{ form.password }}</td>\n        </tr>\n        </table>\n\n        <input type=\"submit\" value=\"login\">\n        <input type=\"hidden\" name=\"next\" value=\"{{ next }}\">\n        </form>\n\n        {# Assumes you setup the password_reset view in your URLconf #}\n        <p><a href=\"{% url 'password_reset' %}\">Lost password?</a></p>\n\n        {% endblock %}\n\n    If you have customized authentication (see :doc:`Customizing Authentication\n    </topics/auth/customizing>`) you can use a custom authentication form by\n    setting the ``authentication_form`` attribute. This form must accept a\n    ``request`` keyword argument in its ``__init__()`` method and provide a\n    ``get_user()`` method which returns the authenticated user object (this\n    method is only ever called after successful form validation).\n\n.. class:: LogoutView\n\n    Logs a user out.\n\n    **URL name:** ``logout``\n\n    **Attributes:**\n\n    * ``next_page``: The URL to redirect to after logout. Defaults to\n      :setting:`settings.LOGOUT_REDIRECT_URL <LOGOUT_REDIRECT_URL>`.\n\n    * ``template_name``: The full name of a template to display after\n      logging the user out. Defaults to :file:`registration/logged_out.html`.\n\n    * ``redirect_field_name``: The name of a ``GET`` field containing the\n      URL to redirect to after log out. Defaults to ``next``. Overrides the\n      ``next_page`` URL if the given ``GET`` parameter is passed.\n\n    * ``extra_context``: A dictionary of context data that will be added to the\n      default context data passed to the template.\n\n    * ``success_url_allowed_hosts``: A :class:`set` of hosts, in addition to\n      :meth:`request.get_host() <django.http.HttpRequest.get_host>`, that are\n      safe for redirecting after logout. Defaults to an empty :class:`set`.\n\n    **Template context:**\n\n    * ``title``: The string \"Logged out\", localized.\n\n    * ``site``: The current :class:`~django.contrib.sites.models.Site`,\n      according to the :setting:`SITE_ID` setting. If you don't have the\n      site framework installed, this will be set to an instance of\n      :class:`~django.contrib.sites.requests.RequestSite`, which derives the\n      site name and domain from the current\n      :class:`~django.http.HttpRequest`.\n\n    * ``site_name``: An alias for ``site.name``. If you don't have the site\n      framework installed, this will be set to the value of\n      :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.\n      For more on sites, see :doc:`/ref/contrib/sites`.\n\n.. function:: logout_then_login(request, login_url=None)\n\n    Logs a user out, then redirects to the login page.\n\n    **URL name:** No default URL provided\n\n    **Optional arguments:**\n\n    * ``login_url``: The URL of the login page to redirect to.\n      Defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied.\n\n.. class:: PasswordChangeView\n\n    **URL name:** ``password_change``\n\n    Allows a user to change their password.\n\n    **Attributes:**\n\n    * ``template_name``: The full name of a template to use for\n      displaying the password change form. Defaults to\n      :file:`registration/password_change_form.html` if not supplied.\n\n    * ``success_url``: The URL to redirect to after a successful password\n      change. Defaults to ``'password_change_done'``.\n\n    * ``form_class``: A custom \"change password\" form which must accept a\n      ``user`` keyword argument. The form is responsible for actually changing\n      the user's password. Defaults to\n      :class:`~django.contrib.auth.forms.PasswordChangeForm`.\n\n    * ``extra_context``: A dictionary of context data that will be added to the\n      default context data passed to the template.\n\n    **Template context:**\n\n    * ``form``: The password change form (see ``form_class`` above).\n\n.. class:: PasswordChangeDoneView\n\n    **URL name:** ``password_change_done``\n\n    The page shown after a user has changed their password.\n\n    **Attributes:**\n\n    * ``template_name``: The full name of a template to use.\n      Defaults to :file:`registration/password_change_done.html` if not\n      supplied.\n\n    * ``extra_context``: A dictionary of context data that will be added to the\n      default context data passed to the template.\n\n.. class:: PasswordResetView\n\n    **URL name:** ``password_reset``\n\n    Allows a user to reset their password by generating a one-time use link\n    that can be used to reset the password, and sending that link to the\n    user's registered email address.\n\n    If the email address provided does not exist in the system, this view\n    won't send an email, but the user won't receive any error message either.\n    This prevents information leaking to potential attackers. If you want to\n    provide an error message in this case, you can subclass\n    :class:`~django.contrib.auth.forms.PasswordResetForm` and use the\n    ``form_class`` attribute.\n\n    .. note::\n\n        Be aware that sending an email costs extra time, hence you may be\n        vulnerable to an email address enumeration timing attack due to a\n        difference between the duration of a reset request for an existing\n        email address and the duration of a reset request for a nonexistent\n        email address. To reduce the overhead, you can use a 3rd party package\n        that allows to send emails asynchronously, e.g. `django-mailer\n        <https://pypi.org/project/django-mailer/>`_.\n\n    Users flagged with an unusable password (see\n    :meth:`~django.contrib.auth.models.User.set_unusable_password()` aren't\n    allowed to request a password reset to prevent misuse when using an\n    external authentication source like LDAP. Note that they won't receive any\n    error message since this would expose their account's existence but no\n    mail will be sent either.\n\n    **Attributes:**\n\n    * ``template_name``: The full name of a template to use for\n      displaying the password reset form. Defaults to\n      :file:`registration/password_reset_form.html` if not supplied.\n\n    * ``form_class``: Form that will be used to get the email of\n      the user to reset the password for. Defaults to\n      :class:`~django.contrib.auth.forms.PasswordResetForm`.\n\n    * ``email_template_name``: The full name of a template to use for\n      generating the email with the reset password link. Defaults to\n      :file:`registration/password_reset_email.html` if not supplied.\n\n    * ``subject_template_name``: The full name of a template to use for\n      the subject of the email with the reset password link. Defaults\n      to :file:`registration/password_reset_subject.txt` if not supplied.\n\n    * ``token_generator``: Instance of the class to check the one time link.\n      This will default to ``default_token_generator``, it's an instance of\n      ``django.contrib.auth.tokens.PasswordResetTokenGenerator``.\n\n    * ``success_url``: The URL to redirect to after a successful password reset\n      request. Defaults to ``'password_reset_done'``.\n\n    * ``from_email``: A valid email address. By default Django uses\n      the :setting:`DEFAULT_FROM_EMAIL`.\n\n    * ``extra_context``: A dictionary of context data that will be added to the\n      default context data passed to the template.\n\n    * ``html_email_template_name``: The full name of a template to use\n      for generating a :mimetype:`text/html` multipart email with the password\n      reset link. By default, HTML email is not sent.\n\n    * ``extra_email_context``: A dictionary of context data that will be\n      available in the email template. It can be used to override default\n      template context values listed below e.g. ``domain``.\n\n    **Template context:**\n\n    * ``form``: The form (see ``form_class`` above) for resetting the user's\n      password.\n\n    **Email template context:**\n\n    * ``email``: An alias for ``user.email``\n\n    * ``user``: The current :class:`~django.contrib.auth.models.User`,\n      according to the ``email`` form field. Only active users are able to\n      reset their passwords (``User.is_active is True``).\n\n    * ``site_name``: An alias for ``site.name``. If you don't have the site\n      framework installed, this will be set to the value of\n      :attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.\n      For more on sites, see :doc:`/ref/contrib/sites`.\n\n    * ``domain``: An alias for ``site.domain``. If you don't have the site\n      framework installed, this will be set to the value of\n      ``request.get_host()``.\n\n    * ``protocol``: http or https\n\n    * ``uid``: The user's primary key encoded in base 64.\n\n    * ``token``: Token to check that the reset link is valid.\n\n    Sample ``registration/password_reset_email.html`` (email body template):\n\n    .. code-block:: html+django\n\n        Someone asked for password reset for email {{ email }}. Follow the link below:\n        {{ protocol}}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}\n\n    The same template context is used for subject template. Subject must be\n    single line plain text string.\n\n.. class:: PasswordResetDoneView\n\n    **URL name:** ``password_reset_done``\n\n    The page shown after a user has been emailed a link to reset their\n    password. This view is called by default if the :class:`PasswordResetView`\n    doesn't have an explicit ``success_url`` URL set.\n\n    .. note::\n\n        If the email address provided does not exist in the system, the user is\n        inactive, or has an unusable password, the user will still be\n        redirected to this view but no email will be sent.\n\n    **Attributes:**\n\n    * ``template_name``: The full name of a template to use.\n      Defaults to :file:`registration/password_reset_done.html` if not\n      supplied.\n\n    * ``extra_context``: A dictionary of context data that will be added to the\n      default context data passed to the template.\n\n.. class:: PasswordResetConfirmView\n\n    **URL name:** ``password_reset_confirm``\n\n    Presents a form for entering a new password.\n\n    **Keyword arguments from the URL:**\n\n    * ``uidb64``: The user's id encoded in base 64.\n\n    * ``token``: Token to check that the password is valid.\n\n    **Attributes:**\n\n    * ``template_name``: The full name of a template to display the confirm\n      password view. Default value is\n      :file:`registration/password_reset_confirm.html`.\n\n    * ``token_generator``: Instance of the class to check the password. This\n      will default to ``default_token_generator``, it's an instance of\n      ``django.contrib.auth.tokens.PasswordResetTokenGenerator``.\n\n    * ``post_reset_login``: A boolean indicating if the user should be\n      automatically authenticated after a successful password reset. Defaults\n      to ``False``.\n\n    * ``post_reset_login_backend``: A dotted path to the authentication\n      backend to use when authenticating a user if ``post_reset_login`` is\n      ``True``. Required only if you have multiple\n      :setting:`AUTHENTICATION_BACKENDS` configured. Defaults to ``None``.\n\n    * ``form_class``: Form that will be used to set the password. Defaults to\n      :class:`~django.contrib.auth.forms.SetPasswordForm`.\n\n    * ``success_url``: URL to redirect after the password reset done. Defaults\n      to ``'password_reset_complete'``.\n\n    * ``extra_context``: A dictionary of context data that will be added to the\n      default context data passed to the template.\n\n    * ``reset_url_token``: Token parameter displayed as a component of password\n      reset URLs. Defaults to ``'set-password'``.\n\n    **Template context:**\n\n    * ``form``: The form (see ``form_class`` above) for setting the new user's\n      password.\n\n    * ``validlink``: Boolean, True if the link (combination of ``uidb64`` and\n      ``token``) is valid or unused yet.\n\n.. class:: PasswordResetCompleteView\n\n    **URL name:** ``password_reset_complete``\n\n    Presents a view which informs the user that the password has been\n    successfully changed.\n\n    **Attributes:**\n\n    * ``template_name``: The full name of a template to display the view.\n      Defaults to :file:`registration/password_reset_complete.html`.\n\n    * ``extra_context``: A dictionary of context data that will be added to the\n      default context data passed to the template.\n\nHelper functions\n----------------\n\n.. currentmodule:: django.contrib.auth.views\n\n.. function:: redirect_to_login(next, login_url=None, redirect_field_name='next')\n\n    Redirects to the login page, and then back to another URL after a\n    successful login.\n\n    **Required arguments:**\n\n    * ``next``: The URL to redirect to after a successful login.\n\n    **Optional arguments:**\n\n    * ``login_url``: The URL of the login page to redirect to.\n      Defaults to :setting:`settings.LOGIN_URL <LOGIN_URL>` if not supplied.\n\n    * ``redirect_field_name``: The name of a ``GET`` field containing the\n      URL to redirect to after log out. Overrides ``next`` if the given\n      ``GET`` parameter is passed.\n\n.. _built-in-auth-forms:\n\nBuilt-in forms\n--------------\n\n.. module:: django.contrib.auth.forms\n\nIf you don't want to use the built-in views, but want the convenience of not\nhaving to write forms for this functionality, the authentication system\nprovides several built-in forms located in :mod:`django.contrib.auth.forms`:\n\n.. note::\n    The built-in authentication forms make certain assumptions about the user\n    model that they are working with. If you're using a :ref:`custom user model\n    <auth-custom-user>`, it may be necessary to define your own forms for the\n    authentication system. For more information, refer to the documentation\n    about :ref:`using the built-in authentication forms with custom user models\n    <custom-users-and-the-built-in-auth-forms>`.\n\n.. class:: AdminPasswordChangeForm\n\n    A form used in the admin interface to change a user's password.\n\n    Takes the ``user`` as the first positional argument.\n\n.. class:: AuthenticationForm\n\n    A form for logging a user in.\n\n    Takes ``request`` as its first positional argument, which is stored on the\n    form instance for use by sub-classes.\n\n    .. method:: confirm_login_allowed(user)\n\n        By default, ``AuthenticationForm`` rejects users whose ``is_active``\n        flag is set to ``False``. You may override this behavior with a custom\n        policy to determine which users can log in. Do this with a custom form\n        that subclasses ``AuthenticationForm`` and overrides the\n        ``confirm_login_allowed()`` method. This method should raise a\n        :exc:`~django.core.exceptions.ValidationError` if the given user may\n        not log in.\n\n        For example, to allow all users to log in regardless of \"active\"\n        status::\n\n            from django.contrib.auth.forms import AuthenticationForm\n\n            class AuthenticationFormWithInactiveUsersOkay(AuthenticationForm):\n                def confirm_login_allowed(self, user):\n                    pass\n\n        (In this case, you'll also need to use an authentication backend that\n        allows inactive users, such as\n        :class:`~django.contrib.auth.backends.AllowAllUsersModelBackend`.)\n\n        Or to allow only some active users to log in::\n\n            class PickyAuthenticationForm(AuthenticationForm):\n                def confirm_login_allowed(self, user):\n                    if not user.is_active:\n                        raise ValidationError(\n                            _(\"This account is inactive.\"),\n                            code='inactive',\n                        )\n                    if user.username.startswith('b'):\n                        raise ValidationError(\n                            _(\"Sorry, accounts starting with 'b' aren't welcome here.\"),\n                            code='no_b_users',\n                        )\n\n.. class:: PasswordChangeForm\n\n    A form for allowing a user to change their password.\n\n.. class:: PasswordResetForm\n\n    A form for generating and emailing a one-time use link to reset a\n    user's password.\n\n    .. method:: send_mail(subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None)\n\n        Uses the arguments to send an ``EmailMultiAlternatives``.\n        Can be overridden to customize how the email is sent to the user.\n\n        :param subject_template_name: the template for the subject.\n        :param email_template_name: the template for the email body.\n        :param context: context passed to the ``subject_template``,\n            ``email_template``, and ``html_email_template`` (if it is not\n            ``None``).\n        :param from_email: the sender's email.\n        :param to_email: the email of the requester.\n        :param html_email_template_name: the template for the HTML body;\n            defaults to ``None``, in which case a plain text email is sent.\n\n        By default, ``save()`` populates the ``context`` with the\n        same variables that\n        :class:`~django.contrib.auth.views.PasswordResetView` passes to its\n        email context.\n\n.. class:: SetPasswordForm\n\n    A form that lets a user change their password without entering the old\n    password.\n\n.. class:: UserChangeForm\n\n    A form used in the admin interface to change a user's information and\n    permissions.\n\n.. class:: UserCreationForm\n\n    A :class:`~django.forms.ModelForm` for creating a new user.\n\n    It has three fields: ``username`` (from the user model), ``password1``,\n    and ``password2``. It verifies that ``password1`` and ``password2`` match,\n    validates the password using\n    :func:`~django.contrib.auth.password_validation.validate_password`, and\n    sets the user's password using\n    :meth:`~django.contrib.auth.models.User.set_password()`.\n\n.. currentmodule:: django.contrib.auth\n\nAuthentication data in templates\n--------------------------------\n\nThe currently logged-in user and their permissions are made available in the\n:doc:`template context </ref/templates/api>` when you use\n:class:`~django.template.RequestContext`.\n\n.. admonition:: Technicality\n\n    Technically, these variables are only made available in the template\n    context if you use :class:`~django.template.RequestContext` and the\n    ``'django.contrib.auth.context_processors.auth'`` context processor is\n    enabled. It is in the default generated settings file. For more, see the\n    :ref:`RequestContext docs <subclassing-context-requestcontext>`.\n\nUsers\n~~~~~\n\nWhen rendering a template :class:`~django.template.RequestContext`, the\ncurrently logged-in user, either a  :class:`~django.contrib.auth.models.User`\ninstance or an :class:`~django.contrib.auth.models.AnonymousUser` instance, is\nstored in the template variable ``{{ user }}``:\n\n.. code-block:: html+django\n\n    {% if user.is_authenticated %}\n        <p>Welcome, {{ user.username }}. Thanks for logging in.</p>\n    {% else %}\n        <p>Welcome, new user. Please log in.</p>\n    {% endif %}\n\nThis template context variable is not available if a ``RequestContext`` is not\nbeing used.\n\nPermissions\n~~~~~~~~~~~\n\nThe currently logged-in user's permissions are stored in the template variable\n``{{ perms }}``. This is an instance of\n``django.contrib.auth.context_processors.PermWrapper``, which is a\ntemplate-friendly proxy of permissions.\n\nEvaluating a single-attribute lookup of ``{{ perms }}`` as a boolean is a proxy\nto :meth:`User.has_module_perms()\n<django.contrib.auth.models.User.has_module_perms>`. For example, to check if\nthe logged-in user has any permissions in the ``foo`` app::\n\n    {% if perms.foo %}\n\nEvaluating a two-level-attribute lookup as a boolean is a proxy to\n:meth:`User.has_perm() <django.contrib.auth.models.User.has_perm>`. For example,\nto check if the logged-in user has the permission ``foo.add_vote``::\n\n    {% if perms.foo.add_vote %}\n\nHere's a more complete example of checking permissions in a template:\n\n.. code-block:: html+django\n\n    {% if perms.foo %}\n        <p>You have permission to do something in the foo app.</p>\n        {% if perms.foo.add_vote %}\n            <p>You can vote!</p>\n        {% endif %}\n        {% if perms.foo.add_driving %}\n            <p>You can drive!</p>\n        {% endif %}\n    {% else %}\n        <p>You don't have permission to do anything in the foo app.</p>\n    {% endif %}\n\nIt is possible to also look permissions up by ``{% if in %}`` statements.\nFor example:\n\n.. code-block:: html+django\n\n    {% if 'foo' in perms %}\n        {% if 'foo.add_vote' in perms %}\n            <p>In lookup works, too.</p>\n        {% endif %}\n    {% endif %}\n\n.. _auth-admin:\n\nManaging users in the admin\n===========================\n\nWhen you have both ``django.contrib.admin`` and ``django.contrib.auth``\ninstalled, the admin provides a convenient way to view and manage users,\ngroups, and permissions. Users can be created and deleted like any Django\nmodel. Groups can be created, and permissions can be assigned to users or\ngroups. A log of user edits to models made within the admin is also stored and\ndisplayed.\n\nCreating users\n--------------\n\nYou should see a link to \"Users\" in the \"Auth\"\nsection of the main admin index page. The \"Add user\" admin page is different\nthan standard admin pages in that it requires you to choose a username and\npassword before allowing you to edit the rest of the user's fields.\n\nAlso note: if you want a user account to be able to create users using the\nDjango admin site, you'll need to give them permission to add users *and*\nchange users (i.e., the \"Add user\" and \"Change user\" permissions). If an\naccount has permission to add users but not to change them, that account won't\nbe able to add users. Why? Because if you have permission to add users, you\nhave the power to create superusers, which can then, in turn, change other\nusers. So Django requires add *and* change permissions as a slight security\nmeasure.\n\nBe thoughtful about how you allow users to manage permissions. If you give a\nnon-superuser the ability to edit users, this is ultimately the same as giving\nthem superuser status because they will be able to elevate permissions of\nusers including themselves!\n\nChanging passwords\n------------------\n\nUser passwords are not displayed in the admin (nor stored in the database), but\nthe :doc:`password storage details </topics/auth/passwords>` are displayed.\nIncluded in the display of this information is a link to\na password change form that allows admins to change user passwords.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":317,"nodeType":"TextFile","repoName":null,"name":"mixins.txt","path":"docs/topics/class-based-views","text":"===================================\nUsing mixins with class-based views\n===================================\n\n.. caution::\n\n    This is an advanced topic. A working knowledge of :doc:`Django's\n    class-based views<index>` is advised before exploring these\n    techniques.\n\nDjango's built-in class-based views provide a lot of functionality,\nbut some of it you may want to use separately. For instance, you may\nwant to write a view that renders a template to make the HTTP\nresponse, but you can't use\n:class:`~django.views.generic.base.TemplateView`; perhaps you need to\nrender a template only on ``POST``, with ``GET`` doing something else\nentirely. While you could use\n:class:`~django.template.response.TemplateResponse` directly, this\nwill likely result in duplicate code.\n\nFor this reason, Django also provides a number of mixins that provide\nmore discrete functionality. Template rendering, for instance, is\nencapsulated in the\n:class:`~django.views.generic.base.TemplateResponseMixin`. The Django\nreference documentation contains :doc:`full documentation of all the\nmixins</ref/class-based-views/mixins>`.\n\nContext and template responses\n==============================\n\nTwo central mixins are provided that help in providing a consistent\ninterface to working with templates in class-based views.\n\n:class:`~django.views.generic.base.TemplateResponseMixin`\n    Every built in view which returns a\n    :class:`~django.template.response.TemplateResponse` will call the\n    :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response()`\n    method that ``TemplateResponseMixin`` provides. Most of the time this\n    will be called for you (for instance, it is called by the ``get()`` method\n    implemented by both :class:`~django.views.generic.base.TemplateView` and\n    :class:`~django.views.generic.detail.DetailView`); similarly, it's unlikely\n    that you'll need to override it, although if you want your response to\n    return something not rendered via a Django template then you'll want to do\n    it. For an example of this, see the :ref:`JSONResponseMixin example\n    <jsonresponsemixin-example>`.\n\n    ``render_to_response()`` itself calls\n    :meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names`,\n    which by default will look up\n    :attr:`~django.views.generic.base.TemplateResponseMixin.template_name` on\n    the class-based view; two other mixins\n    (:class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`\n    and\n    :class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`)\n    override this to provide more flexible defaults when dealing with actual\n    objects.\n\n:class:`~django.views.generic.base.ContextMixin`\n    Every built in view which needs context data, such as for rendering a\n    template (including ``TemplateResponseMixin`` above), should call\n    :meth:`~django.views.generic.base.ContextMixin.get_context_data()` passing\n    any data they want to ensure is in there as keyword arguments.\n    ``get_context_data()`` returns a dictionary; in ``ContextMixin`` it\n    returns its keyword arguments, but it is common to override this to add\n    more members to the dictionary. You can also use the\n    :attr:`~django.views.generic.base.ContextMixin.extra_context` attribute.\n\nBuilding up Django's generic class-based views\n==============================================\n\nLet's look at how two of Django's generic class-based views are built\nout of mixins providing discrete functionality. We'll consider\n:class:`~django.views.generic.detail.DetailView`, which renders a\n\"detail\" view of an object, and\n:class:`~django.views.generic.list.ListView`, which will render a list\nof objects, typically from a queryset, and optionally paginate\nthem. This will introduce us to four mixins which between them provide\nuseful functionality when working with either a single Django object,\nor multiple objects.\n\nThere are also mixins involved in the generic edit views\n(:class:`~django.views.generic.edit.FormView`, and the model-specific\nviews :class:`~django.views.generic.edit.CreateView`,\n:class:`~django.views.generic.edit.UpdateView` and\n:class:`~django.views.generic.edit.DeleteView`), and in the\ndate-based generic views. These are\ncovered in the :doc:`mixin reference\ndocumentation</ref/class-based-views/mixins>`.\n\n``DetailView``: working with a single Django object\n---------------------------------------------------\n\nTo show the detail of an object, we basically need to do two things:\nwe need to look up the object and then we need to make a\n:class:`~django.template.response.TemplateResponse` with a suitable template,\nand that object as context.\n\nTo get the object, :class:`~django.views.generic.detail.DetailView`\nrelies on :class:`~django.views.generic.detail.SingleObjectMixin`,\nwhich provides a\n:meth:`~django.views.generic.detail.SingleObjectMixin.get_object`\nmethod that figures out the object based on the URL of the request (it\nlooks for ``pk`` and ``slug`` keyword arguments as declared in the\nURLConf, and looks the object up either from the\n:attr:`~django.views.generic.detail.SingleObjectMixin.model` attribute\non the view, or the\n:attr:`~django.views.generic.detail.SingleObjectMixin.queryset`\nattribute if that's provided). ``SingleObjectMixin`` also overrides\n:meth:`~django.views.generic.base.ContextMixin.get_context_data()`,\nwhich is used across all Django's built in class-based views to supply\ncontext data for template renders.\n\nTo then make a :class:`~django.template.response.TemplateResponse`,\n:class:`DetailView` uses\n:class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`,\nwhich extends :class:`~django.views.generic.base.TemplateResponseMixin`,\noverriding\n:meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names()`\nas discussed above. It actually provides a fairly sophisticated set of options,\nbut the main one that most people are going to use is\n``<app_label>/<model_name>_detail.html``. The ``_detail`` part can be changed\nby setting\n:attr:`~django.views.generic.detail.SingleObjectTemplateResponseMixin.template_name_suffix`\non a subclass to something else. (For instance, the :doc:`generic edit\nviews<generic-editing>` use ``_form`` for create and update views, and\n``_confirm_delete`` for delete views.)\n\n``ListView``: working with many Django objects\n----------------------------------------------\n\nLists of objects follow roughly the same pattern: we need a (possibly\npaginated) list of objects, typically a\n:class:`~django.db.models.query.QuerySet`, and then we need to make a\n:class:`~django.template.response.TemplateResponse` with a suitable template\nusing that list of objects.\n\nTo get the objects, :class:`~django.views.generic.list.ListView` uses\n:class:`~django.views.generic.list.MultipleObjectMixin`, which\nprovides both\n:meth:`~django.views.generic.list.MultipleObjectMixin.get_queryset`\nand\n:meth:`~django.views.generic.list.MultipleObjectMixin.paginate_queryset`. Unlike\nwith :class:`~django.views.generic.detail.SingleObjectMixin`, there's no need\nto key off parts of the URL to figure out the queryset to work with, so the\ndefault uses the\n:attr:`~django.views.generic.list.MultipleObjectMixin.queryset` or\n:attr:`~django.views.generic.list.MultipleObjectMixin.model` attribute\non the view class. A common reason to override\n:meth:`~django.views.generic.list.MultipleObjectMixin.get_queryset`\nhere would be to dynamically vary the objects, such as depending on\nthe current user or to exclude posts in the future for a blog.\n\n:class:`~django.views.generic.list.MultipleObjectMixin` also overrides\n:meth:`~django.views.generic.base.ContextMixin.get_context_data()` to\ninclude appropriate context variables for pagination (providing\ndummies if pagination is disabled). It relies on ``object_list`` being\npassed in as a keyword argument, which :class:`ListView` arranges for\nit.\n\nTo make a :class:`~django.template.response.TemplateResponse`,\n:class:`ListView` then uses\n:class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`;\nas with :class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`\nabove, this overrides ``get_template_names()`` to provide :meth:`a range of\noptions <django.views.generic.list.MultipleObjectTemplateResponseMixin>`,\nwith the most commonly-used being\n``<app_label>/<model_name>_list.html``, with the ``_list`` part again\nbeing taken from the\n:attr:`~django.views.generic.list.MultipleObjectTemplateResponseMixin.template_name_suffix`\nattribute. (The date based generic views use suffixes such as ``_archive``,\n``_archive_year`` and so on to use different templates for the various\nspecialized date-based list views.)\n\nUsing Django's class-based view mixins\n======================================\n\nNow we've seen how Django's generic class-based views use the provided mixins,\nlet's look at other ways we can combine them. We're still going to be combining\nthem with either built-in class-based views, or other generic class-based\nviews, but there are a range of rarer problems you can solve than are provided\nfor by Django out of the box.\n\n.. warning::\n\n    Not all mixins can be used together, and not all generic class\n    based views can be used with all other mixins. Here we present a\n    few examples that do work; if you want to bring together other\n    functionality then you'll have to consider interactions between\n    attributes and methods that overlap between the different classes\n    you're using, and how `method resolution order`_ will affect which\n    versions of the methods will be called in what order.\n\n    The reference documentation for Django's :doc:`class-based\n    views</ref/class-based-views/index>` and :doc:`class-based view\n    mixins</ref/class-based-views/mixins>` will help you in\n    understanding which attributes and methods are likely to cause\n    conflict between different classes and mixins.\n\n    If in doubt, it's often better to back off and base your work on\n    :class:`View` or :class:`TemplateView`, perhaps with\n    :class:`~django.views.generic.detail.SingleObjectMixin` and\n    :class:`~django.views.generic.list.MultipleObjectMixin`. Although you\n    will probably end up writing more code, it is more likely to be clearly\n    understandable to someone else coming to it later, and with fewer\n    interactions to worry about you will save yourself some thinking. (Of\n    course, you can always dip into Django's implementation of the generic\n    class-based views for inspiration on how to tackle problems.)\n\n.. _method resolution order: https://www.python.org/download/releases/2.3/mro/\n\nUsing ``SingleObjectMixin`` with View\n-------------------------------------\n\nIf we want to write a class-based view that responds only to ``POST``, we'll\nsubclass :class:`~django.views.generic.base.View` and write a ``post()`` method\nin the subclass. However if we want our processing to work on a particular\nobject, identified from the URL, we'll want the functionality provided by\n:class:`~django.views.generic.detail.SingleObjectMixin`.\n\nWe'll demonstrate this with the ``Author`` model we used in the\n:doc:`generic class-based views introduction<generic-display>`.\n\n.. code-block:: python\n    :caption: views.py\n\n    from django.http import HttpResponseForbidden, HttpResponseRedirect\n    from django.urls import reverse\n    from django.views import View\n    from django.views.generic.detail import SingleObjectMixin\n    from books.models import Author\n\n    class RecordInterest(SingleObjectMixin, View):\n        \"\"\"Records the current user's interest in an author.\"\"\"\n        model = Author\n\n        def post(self, request, *args, **kwargs):\n            if not request.user.is_authenticated:\n                return HttpResponseForbidden()\n\n            # Look up the author we're interested in.\n            self.object = self.get_object()\n            # Actually record interest somehow here!\n\n            return HttpResponseRedirect(reverse('author-detail', kwargs={'pk': self.object.pk}))\n\nIn practice you'd probably want to record the interest in a key-value\nstore rather than in a relational database, so we've left that bit\nout. The only bit of the view that needs to worry about using\n:class:`~django.views.generic.detail.SingleObjectMixin` is where we want to\nlook up the author we're interested in, which it does with a call to\n``self.get_object()``. Everything else is taken care of for us by the mixin.\n\nWe can hook this into our URLs easily enough:\n\n.. code-block:: python\n    :caption: urls.py\n\n    from django.urls import path\n    from books.views import RecordInterest\n\n    urlpatterns = [\n        #...\n        path('author/<int:pk>/interest/', RecordInterest.as_view(), name='author-interest'),\n    ]\n\nNote the ``pk`` named group, which\n:meth:`~django.views.generic.detail.SingleObjectMixin.get_object` uses\nto look up the ``Author`` instance. You could also use a slug, or\nany of the other features of\n:class:`~django.views.generic.detail.SingleObjectMixin`.\n\nUsing ``SingleObjectMixin`` with ``ListView``\n---------------------------------------------\n\n:class:`~django.views.generic.list.ListView` provides built-in\npagination, but you might want to paginate a list of objects that are\nall linked (by a foreign key) to another object. In our publishing\nexample, you might want to paginate through all the books by a\nparticular publisher.\n\nOne way to do this is to combine :class:`ListView` with\n:class:`~django.views.generic.detail.SingleObjectMixin`, so that the queryset\nfor the paginated list of books can hang off the publisher found as the single\nobject. In order to do this, we need to have two different querysets:\n\n``Book`` queryset for use by :class:`~django.views.generic.list.ListView`\n    Since we have access to the ``Publisher`` whose books we want to list, we\n    override ``get_queryset()`` and use the ``Publisher``’s :ref:`reverse\n    foreign key manager<backwards-related-objects>`.\n\n``Publisher`` queryset for use in :meth:`~django.views.generic.detail.SingleObjectMixin.get_object()`\n    We'll rely on the default implementation of ``get_object()`` to fetch the\n    correct ``Publisher`` object.\n    However, we need to explicitly pass a ``queryset`` argument because\n    otherwise the default implementation of ``get_object()`` would call\n    ``get_queryset()`` which we have overridden to return ``Book`` objects\n    instead of ``Publisher`` ones.\n\n.. note::\n\n    We have to think carefully about ``get_context_data()``.\n    Since both :class:`~django.views.generic.detail.SingleObjectMixin` and\n    :class:`ListView` will\n    put things in the context data under the value of\n    ``context_object_name`` if it's set, we'll instead explicitly\n    ensure the ``Publisher`` is in the context data. :class:`ListView`\n    will add in the suitable ``page_obj`` and ``paginator`` for us\n    providing we remember to call ``super()``.\n\nNow we can write a new ``PublisherDetail``::\n\n    from django.views.generic import ListView\n    from django.views.generic.detail import SingleObjectMixin\n    from books.models import Publisher\n\n    class PublisherDetail(SingleObjectMixin, ListView):\n        paginate_by = 2\n        template_name = \"books/publisher_detail.html\"\n\n        def get(self, request, *args, **kwargs):\n            self.object = self.get_object(queryset=Publisher.objects.all())\n            return super().get(request, *args, **kwargs)\n\n        def get_context_data(self, **kwargs):\n            context = super().get_context_data(**kwargs)\n            context['publisher'] = self.object\n            return context\n\n        def get_queryset(self):\n            return self.object.book_set.all()\n\nNotice how we set ``self.object`` within ``get()`` so we\ncan use it again later in ``get_context_data()`` and ``get_queryset()``.\nIf you don't set ``template_name``, the template will default to the normal\n:class:`ListView` choice, which in this case would be\n``\"books/book_list.html\"`` because it's a list of books;\n:class:`ListView` knows nothing about\n:class:`~django.views.generic.detail.SingleObjectMixin`, so it doesn't have\nany clue this view is anything to do with a ``Publisher``.\n\nThe ``paginate_by`` is deliberately small in the example so you don't\nhave to create lots of books to see the pagination working! Here's the\ntemplate you'd want to use:\n\n.. code-block:: html+django\n\n    {% extends \"base.html\" %}\n\n    {% block content %}\n        <h2>Publisher {{ publisher.name }}</h2>\n\n        <ol>\n          {% for book in page_obj %}\n            <li>{{ book.title }}</li>\n          {% endfor %}\n        </ol>\n\n        <div class=\"pagination\">\n            <span class=\"step-links\">\n                {% if page_obj.has_previous %}\n                    <a href=\"?page={{ page_obj.previous_page_number }}\">previous</a>\n                {% endif %}\n\n                <span class=\"current\">\n                    Page {{ page_obj.number }} of {{ paginator.num_pages }}.\n                </span>\n\n                {% if page_obj.has_next %}\n                    <a href=\"?page={{ page_obj.next_page_number }}\">next</a>\n                {% endif %}\n            </span>\n        </div>\n    {% endblock %}\n\nAvoid anything more complex\n===========================\n\nGenerally you can use\n:class:`~django.views.generic.base.TemplateResponseMixin` and\n:class:`~django.views.generic.detail.SingleObjectMixin` when you need\ntheir functionality. As shown above, with a bit of care you can even\ncombine ``SingleObjectMixin`` with\n:class:`~django.views.generic.list.ListView`. However things get\nincreasingly complex as you try to do so, and a good rule of thumb is:\n\n.. hint::\n\n    Each of your views should use only mixins or views from one of the\n    groups of generic class-based views: :doc:`detail,\n    list<generic-display>`, :doc:`editing<generic-editing>` and\n    date. For example it's fine to combine\n    :class:`TemplateView` (built in view) with\n    :class:`~django.views.generic.list.MultipleObjectMixin` (generic list), but\n    you're likely to have problems combining ``SingleObjectMixin`` (generic\n    detail) with ``MultipleObjectMixin`` (generic list).\n\nTo show what happens when you try to get more sophisticated, we show\nan example that sacrifices readability and maintainability when there\nis a simpler solution. First, let's look at a naive attempt to combine\n:class:`~django.views.generic.detail.DetailView` with\n:class:`~django.views.generic.edit.FormMixin` to enable us to\n``POST`` a Django :class:`~django.forms.Form` to the same URL as we're\ndisplaying an object using :class:`DetailView`.\n\nUsing ``FormMixin`` with ``DetailView``\n---------------------------------------\n\nThink back to our earlier example of using :class:`View` and\n:class:`~django.views.generic.detail.SingleObjectMixin` together. We were\nrecording a user's interest in a particular author; say now that we want to\nlet them leave a message saying why they like them. Again, let's assume we're\nnot going to store this in a relational database but instead in\nsomething more esoteric that we won't worry about here.\n\nAt this point it's natural to reach for a :class:`~django.forms.Form` to\nencapsulate the information sent from the user's browser to Django. Say also\nthat we're heavily invested in `REST`_, so we want to use the same URL for\ndisplaying the author as for capturing the message from the\nuser. Let's rewrite our ``AuthorDetailView`` to do that.\n\n.. _REST: https://en.wikipedia.org/wiki/Representational_state_transfer\n\nWe'll keep the ``GET`` handling from :class:`DetailView`, although\nwe'll have to add a :class:`~django.forms.Form` into the context data so we can\nrender it in the template. We'll also want to pull in form processing\nfrom :class:`~django.views.generic.edit.FormMixin`, and write a bit of\ncode so that on ``POST`` the form gets called appropriately.\n\n.. note::\n\n    We use :class:`~django.views.generic.edit.FormMixin` and implement\n    ``post()`` ourselves rather than try to mix :class:`DetailView` with\n    :class:`FormView` (which provides a suitable ``post()`` already) because\n    both of the views implement ``get()``, and things would get much more\n    confusing.\n\nOur new ``AuthorDetail`` looks like this::\n\n    # CAUTION: you almost certainly do not want to do this.\n    # It is provided as part of a discussion of problems you can\n    # run into when combining different generic class-based view\n    # functionality that is not designed to be used together.\n\n    from django import forms\n    from django.http import HttpResponseForbidden\n    from django.urls import reverse\n    from django.views.generic import DetailView\n    from django.views.generic.edit import FormMixin\n    from books.models import Author\n\n    class AuthorInterestForm(forms.Form):\n        message = forms.CharField()\n\n    class AuthorDetail(FormMixin, DetailView):\n        model = Author\n        form_class = AuthorInterestForm\n\n        def get_success_url(self):\n            return reverse('author-detail', kwargs={'pk': self.object.pk})\n\n        def post(self, request, *args, **kwargs):\n            if not request.user.is_authenticated:\n                return HttpResponseForbidden()\n            self.object = self.get_object()\n            form = self.get_form()\n            if form.is_valid():\n                return self.form_valid(form)\n            else:\n                return self.form_invalid(form)\n\n        def form_valid(self, form):\n            # Here, we would record the user's interest using the message\n            # passed in form.cleaned_data['message']\n            return super().form_valid(form)\n\n``get_success_url()`` provides somewhere to redirect to, which gets used\nin the default implementation of ``form_valid()``. We have to provide our\nown ``post()`` as noted earlier.\n\nA better solution\n-----------------\n\nThe number of subtle interactions between\n:class:`~django.views.generic.edit.FormMixin` and :class:`DetailView` is\nalready testing our ability to manage things. It's unlikely you'd want to\nwrite this kind of class yourself.\n\nIn this case, you could write the ``post()`` method yourself, keeping\n:class:`DetailView` as the only generic functionality, although writing\n:class:`~django.forms.Form` handling code involves a lot of duplication.\n\nAlternatively, it would still be less work than the above approach to\nhave a separate view for processing the form, which could use\n:class:`~django.views.generic.edit.FormView` distinct from\n:class:`DetailView` without concerns.\n\nAn alternative better solution\n------------------------------\n\nWhat we're really trying to do here is to use two different class\nbased views from the same URL. So why not do just that? We have a very\nclear division here: ``GET`` requests should get the\n:class:`DetailView` (with the :class:`~django.forms.Form` added to the context\ndata), and ``POST`` requests should get the :class:`FormView`. Let's\nset up those views first.\n\nThe ``AuthorDisplay`` view is almost the same as :ref:`when we\nfirst introduced AuthorDetail<generic-views-extra-work>`; we have to\nwrite our own ``get_context_data()`` to make the\n``AuthorInterestForm`` available to the template. We'll skip the\n``get_object()`` override from before for clarity::\n\n    from django import forms\n    from django.views.generic import DetailView\n    from books.models import Author\n\n    class AuthorInterestForm(forms.Form):\n        message = forms.CharField()\n\n    class AuthorDisplay(DetailView):\n        model = Author\n\n        def get_context_data(self, **kwargs):\n            context = super().get_context_data(**kwargs)\n            context['form'] = AuthorInterestForm()\n            return context\n\nThen the ``AuthorInterest`` is a :class:`FormView`, but we have to bring in\n:class:`~django.views.generic.detail.SingleObjectMixin` so we can find the\nauthor we're talking about, and we have to remember to set ``template_name`` to\nensure that form errors will render the same template as ``AuthorDisplay`` is\nusing on ``GET``::\n\n    from django.http import HttpResponseForbidden\n    from django.urls import reverse\n    from django.views.generic import FormView\n    from django.views.generic.detail import SingleObjectMixin\n\n    class AuthorInterest(SingleObjectMixin, FormView):\n        template_name = 'books/author_detail.html'\n        form_class = AuthorInterestForm\n        model = Author\n\n        def post(self, request, *args, **kwargs):\n            if not request.user.is_authenticated:\n                return HttpResponseForbidden()\n            self.object = self.get_object()\n            return super().post(request, *args, **kwargs)\n\n        def get_success_url(self):\n            return reverse('author-detail', kwargs={'pk': self.object.pk})\n\nFinally we bring this together in a new ``AuthorDetail`` view. We\nalready know that calling :meth:`~django.views.generic.base.View.as_view()` on\na class-based view gives us something that behaves exactly like a function\nbased view, so we can do that at the point we choose between the two subviews.\n\nYou can pass through keyword arguments to\n:meth:`~django.views.generic.base.View.as_view()` in the same way you\nwould in your URLconf, such as if you wanted the ``AuthorInterest`` behavior\nto also appear at another URL but using a different template::\n\n    from django.views import View\n\n    class AuthorDetail(View):\n\n        def get(self, request, *args, **kwargs):\n            view = AuthorDisplay.as_view()\n            return view(request, *args, **kwargs)\n\n        def post(self, request, *args, **kwargs):\n            view = AuthorInterest.as_view()\n            return view(request, *args, **kwargs)\n\nThis approach can also be used with any other generic class-based\nviews or your own class-based views inheriting directly from\n:class:`View` or :class:`TemplateView`, as it keeps the different\nviews as separate as possible.\n\n.. _jsonresponsemixin-example:\n\nMore than just HTML\n===================\n\nWhere class-based views shine is when you want to do the same thing many times.\nSuppose you're writing an API, and every view should return JSON instead of\nrendered HTML.\n\nWe can create a mixin class to use in all of our views, handling the\nconversion to JSON once.\n\nFor example, a JSON mixin might look something like this::\n\n    from django.http import JsonResponse\n\n    class JSONResponseMixin:\n        \"\"\"\n        A mixin that can be used to render a JSON response.\n        \"\"\"\n        def render_to_json_response(self, context, **response_kwargs):\n            \"\"\"\n            Returns a JSON response, transforming 'context' to make the payload.\n            \"\"\"\n            return JsonResponse(\n                self.get_data(context),\n                **response_kwargs\n            )\n\n        def get_data(self, context):\n            \"\"\"\n            Returns an object that will be serialized as JSON by json.dumps().\n            \"\"\"\n            # Note: This is *EXTREMELY* naive; in reality, you'll need\n            # to do much more complex handling to ensure that arbitrary\n            # objects -- such as Django model instances or querysets\n            # -- can be serialized as JSON.\n            return context\n\n.. note::\n\n    Check out the :doc:`/topics/serialization` documentation for more\n    information on how to correctly transform Django models and querysets into\n    JSON.\n\nThis mixin provides a ``render_to_json_response()`` method with the same signature\nas :func:`~django.views.generic.base.TemplateResponseMixin.render_to_response()`.\nTo use it, we need to mix it into a ``TemplateView`` for example, and override\n``render_to_response()`` to call ``render_to_json_response()`` instead::\n\n    from django.views.generic import TemplateView\n\n    class JSONView(JSONResponseMixin, TemplateView):\n        def render_to_response(self, context, **response_kwargs):\n            return self.render_to_json_response(context, **response_kwargs)\n\nEqually we could use our mixin with one of the generic views. We can make our\nown version of :class:`~django.views.generic.detail.DetailView` by mixing\n``JSONResponseMixin`` with the\n``django.views.generic.detail.BaseDetailView`` -- (the\n:class:`~django.views.generic.detail.DetailView` before template\nrendering behavior has been mixed in)::\n\n    from django.views.generic.detail import BaseDetailView\n\n    class JSONDetailView(JSONResponseMixin, BaseDetailView):\n        def render_to_response(self, context, **response_kwargs):\n            return self.render_to_json_response(context, **response_kwargs)\n\nThis view can then be deployed in the same way as any other\n:class:`~django.views.generic.detail.DetailView`, with exactly the\nsame behavior -- except for the format of the response.\n\nIf you want to be really adventurous, you could even mix a\n:class:`~django.views.generic.detail.DetailView` subclass that is able\nto return *both* HTML and JSON content, depending on some property of\nthe HTTP request, such as a query argument or a HTTP header. Mix in both the\n``JSONResponseMixin`` and a\n:class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`,\nand override the implementation of\n:func:`~django.views.generic.base.TemplateResponseMixin.render_to_response()`\nto defer to the appropriate rendering method depending on the type of response\nthat the user requested::\n\n    from django.views.generic.detail import SingleObjectTemplateResponseMixin\n\n    class HybridDetailView(JSONResponseMixin, SingleObjectTemplateResponseMixin, BaseDetailView):\n        def render_to_response(self, context):\n            # Look for a 'format=json' GET argument\n            if self.request.GET.get('format') == 'json':\n                return self.render_to_json_response(context)\n            else:\n                return super().render_to_response(context)\n\nBecause of the way that Python resolves method overloading, the call to\n``super().render_to_response(context)`` ends up calling the\n:meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response()`\nimplementation of :class:`~django.views.generic.base.TemplateResponseMixin`.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":318,"nodeType":"TextFile","repoName":null,"name":"customizing.txt","path":"docs/topics/auth","text":"====================================\nCustomizing authentication in Django\n====================================\n\nThe authentication that comes with Django is good enough for most common cases,\nbut you may have needs not met by the out-of-the-box defaults. Customizing\nauthentication in your projects requires understanding what points of the\nprovided system are extensible or replaceable. This document provides details\nabout how the auth system can be customized.\n\n:ref:`Authentication backends <authentication-backends>` provide an extensible\nsystem for when a username and password stored with the user model need to be\nauthenticated against a different service than Django's default.\n\nYou can give your models :ref:`custom permissions <custom-permissions>` that\ncan be checked through Django's authorization system.\n\nYou can :ref:`extend <extending-user>` the default ``User`` model, or\n:ref:`substitute <auth-custom-user>` a completely customized model.\n\n.. _authentication-backends:\n\nOther authentication sources\n============================\n\nThere may be times you have the need to hook into another authentication source\n-- that is, another source of usernames and passwords or authentication\nmethods.\n\nFor example, your company may already have an LDAP setup that stores a username\nand password for every employee. It'd be a hassle for both the network\nadministrator and the users themselves if users had separate accounts in LDAP\nand the Django-based applications.\n\nSo, to handle situations like this, the Django authentication system lets you\nplug in other authentication sources. You can override Django's default\ndatabase-based scheme, or you can use the default system in tandem with other\nsystems.\n\nSee the :ref:`authentication backend reference\n<authentication-backends-reference>` for information on the authentication\nbackends included with Django.\n\nSpecifying authentication backends\n----------------------------------\n\nBehind the scenes, Django maintains a list of \"authentication backends\" that it\nchecks for authentication. When somebody calls\n:func:`django.contrib.auth.authenticate()` -- as described in :ref:`How to log\na user in <how-to-log-a-user-in>` -- Django tries authenticating across\nall of its authentication backends. If the first authentication method fails,\nDjango tries the second one, and so on, until all backends have been attempted.\n\nThe list of authentication backends to use is specified in the\n:setting:`AUTHENTICATION_BACKENDS` setting. This should be a list of Python\npath names that point to Python classes that know how to authenticate. These\nclasses can be anywhere on your Python path.\n\nBy default, :setting:`AUTHENTICATION_BACKENDS` is set to::\n\n    ['django.contrib.auth.backends.ModelBackend']\n\nThat's the basic authentication backend that checks the Django users database\nand queries the built-in permissions. It does not provide protection against\nbrute force attacks via any rate limiting mechanism. You may either implement\nyour own rate limiting mechanism in a custom auth backend, or use the\nmechanisms provided by most Web servers.\n\nThe order of :setting:`AUTHENTICATION_BACKENDS` matters, so if the same\nusername and password is valid in multiple backends, Django will stop\nprocessing at the first positive match.\n\nIf a backend raises a :class:`~django.core.exceptions.PermissionDenied`\nexception, authentication will immediately fail. Django won't check the\nbackends that follow.\n\n.. note::\n\n    Once a user has authenticated, Django stores which backend was used to\n    authenticate the user in the user's session, and re-uses the same backend\n    for the duration of that session whenever access to the currently\n    authenticated user is needed. This effectively means that authentication\n    sources are cached on a per-session basis, so if you change\n    :setting:`AUTHENTICATION_BACKENDS`, you'll need to clear out session data if\n    you need to force users to re-authenticate using different methods. A\n    simple way to do that is to execute ``Session.objects.all().delete()``.\n\nWriting an authentication backend\n---------------------------------\n\nAn authentication backend is a class that implements two required methods:\n``get_user(user_id)`` and ``authenticate(request, **credentials)``, as well as\na set of optional permission related :ref:`authorization methods\n<authorization_methods>`.\n\nThe ``get_user`` method takes a ``user_id`` -- which could be a username,\ndatabase ID or whatever, but has to be the primary key of your user object --\nand returns a user object or ``None``.\n\nThe ``authenticate`` method takes a ``request`` argument and credentials as\nkeyword arguments. Most of the time, it'll look like this::\n\n    from django.contrib.auth.backends import BaseBackend\n\n    class MyBackend(BaseBackend):\n        def authenticate(self, request, username=None, password=None):\n            # Check the username/password and return a user.\n            ...\n\nBut it could also authenticate a token, like so::\n\n    from django.contrib.auth.backends import BaseBackend\n\n    class MyBackend(BaseBackend):\n        def authenticate(self, request, token=None):\n            # Check the token and return a user.\n            ...\n\nEither way, ``authenticate()`` should check the credentials it gets and return\na user object that matches those credentials if the credentials are valid. If\nthey're not valid, it should return ``None``.\n\n``request`` is an :class:`~django.http.HttpRequest` and may be ``None`` if it\nwasn't provided to :func:`~django.contrib.auth.authenticate` (which passes it\non to the backend).\n\nThe Django admin is tightly coupled to the Django :ref:`User object\n<user-objects>`. The best way to deal with this is to create a Django ``User``\nobject for each user that exists for your backend (e.g., in your LDAP\ndirectory, your external SQL database, etc.) You can either write a script to\ndo this in advance, or your ``authenticate`` method can do it the first time a\nuser logs in.\n\nHere's an example backend that authenticates against a username and password\nvariable defined in your ``settings.py`` file and creates a Django ``User``\nobject the first time a user authenticates::\n\n    from django.conf import settings\n    from django.contrib.auth.backends import BaseBackend\n    from django.contrib.auth.hashers import check_password\n    from django.contrib.auth.models import User\n\n    class SettingsBackend(BaseBackend):\n        \"\"\"\n        Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.\n\n        Use the login name and a hash of the password. For example:\n\n        ADMIN_LOGIN = 'admin'\n        ADMIN_PASSWORD = 'pbkdf2_sha256$30000$Vo0VlMnkR4Bk$qEvtdyZRWTcOsCnI/oQ7fVOu1XAURIZYoOZ3iq8Dr4M='\n        \"\"\"\n\n        def authenticate(self, request, username=None, password=None):\n            login_valid = (settings.ADMIN_LOGIN == username)\n            pwd_valid = check_password(password, settings.ADMIN_PASSWORD)\n            if login_valid and pwd_valid:\n                try:\n                    user = User.objects.get(username=username)\n                except User.DoesNotExist:\n                    # Create a new user. There's no need to set a password\n                    # because only the password from settings.py is checked.\n                    user = User(username=username)\n                    user.is_staff = True\n                    user.is_superuser = True\n                    user.save()\n                return user\n            return None\n\n        def get_user(self, user_id):\n            try:\n                return User.objects.get(pk=user_id)\n            except User.DoesNotExist:\n                return None\n\n.. _authorization_methods:\n\nHandling authorization in custom backends\n-----------------------------------------\n\nCustom auth backends can provide their own permissions.\n\nThe user model and its manager will delegate permission lookup functions\n(:meth:`~django.contrib.auth.models.User.get_user_permissions()`,\n:meth:`~django.contrib.auth.models.User.get_group_permissions()`,\n:meth:`~django.contrib.auth.models.User.get_all_permissions()`,\n:meth:`~django.contrib.auth.models.User.has_perm()`,\n:meth:`~django.contrib.auth.models.User.has_module_perms()`, and\n:meth:`~django.contrib.auth.models.UserManager.with_perm()`) to any\nauthentication backend that implements these functions.\n\nThe permissions given to the user will be the superset of all permissions\nreturned by all backends. That is, Django grants a permission to a user that\nany one backend grants.\n\nIf a backend raises a :class:`~django.core.exceptions.PermissionDenied`\nexception in :meth:`~django.contrib.auth.models.User.has_perm()` or\n:meth:`~django.contrib.auth.models.User.has_module_perms()`, the authorization\nwill immediately fail and Django won't check the backends that follow.\n\nA backend could implement permissions for the magic admin like this::\n\n    from django.contrib.auth.backends import BaseBackend\n\n    class MagicAdminBackend(BaseBackend):\n        def has_perm(self, user_obj, perm, obj=None):\n            return user_obj.username == settings.ADMIN_LOGIN\n\nThis gives full permissions to the user granted access in the above example.\nNotice that in addition to the same arguments given to the associated\n:class:`django.contrib.auth.models.User` functions, the backend auth functions\nall take the user object, which may be an anonymous user, as an argument.\n\nA full authorization implementation can be found in the ``ModelBackend`` class\nin :source:`django/contrib/auth/backends.py`, which is the default backend and\nqueries the ``auth_permission`` table most of the time.\n\n.. _anonymous_auth:\n\nAuthorization for anonymous users\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nAn anonymous user is one that is not authenticated i.e. they have provided no\nvalid authentication details. However, that does not necessarily mean they are\nnot authorized to do anything. At the most basic level, most websites\nauthorize anonymous users to browse most of the site, and many allow anonymous\nposting of comments etc.\n\nDjango's permission framework does not have a place to store permissions for\nanonymous users. However, the user object passed to an authentication backend\nmay be an :class:`django.contrib.auth.models.AnonymousUser` object, allowing\nthe backend to specify custom authorization behavior for anonymous users. This\nis especially useful for the authors of re-usable apps, who can delegate all\nquestions of authorization to the auth backend, rather than needing settings,\nfor example, to control anonymous access.\n\n.. _inactive_auth:\n\nAuthorization for inactive users\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nAn inactive user is one that has its\n:attr:`~django.contrib.auth.models.User.is_active` field set to ``False``. The\n:class:`~django.contrib.auth.backends.ModelBackend` and\n:class:`~django.contrib.auth.backends.RemoteUserBackend` authentication\nbackends prohibits these users from authenticating. If a custom user model\ndoesn't have an :attr:`~django.contrib.auth.models.CustomUser.is_active` field,\nall users will be allowed to authenticate.\n\nYou can use :class:`~django.contrib.auth.backends.AllowAllUsersModelBackend`\nor :class:`~django.contrib.auth.backends.AllowAllUsersRemoteUserBackend` if you\nwant to allow inactive users to authenticate.\n\nThe support for anonymous users in the permission system allows for a scenario\nwhere anonymous users have permissions to do something while inactive\nauthenticated users do not.\n\nDo not forget to test for the ``is_active`` attribute of the user in your own\nbackend permission methods.\n\nHandling object permissions\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nDjango's permission framework has a foundation for object permissions, though\nthere is no implementation for it in the core. That means that checking for\nobject permissions will always return ``False`` or an empty list (depending on\nthe check performed). An authentication backend will receive the keyword\nparameters ``obj`` and ``user_obj`` for each object related authorization\nmethod and can return the object level permission as appropriate.\n\n.. _custom-permissions:\n\nCustom permissions\n==================\n\nTo create custom permissions for a given model object, use the ``permissions``\n:ref:`model Meta attribute <meta-options>`.\n\nThis example ``Task`` model creates two custom permissions, i.e., actions users\ncan or cannot do with ``Task`` instances, specific to your application::\n\n    class Task(models.Model):\n        ...\n        class Meta:\n            permissions = [\n                (\"change_task_status\", \"Can change the status of tasks\"),\n                (\"close_task\", \"Can remove a task by setting its status as closed\"),\n            ]\n\nThe only thing this does is create those extra permissions when you run\n:djadmin:`manage.py migrate <migrate>` (the function that creates permissions\nis connected to the :data:`~django.db.models.signals.post_migrate` signal).\nYour code is in charge of checking the value of these permissions when a user\nis trying to access the functionality provided by the application (changing the\nstatus of tasks or closing tasks.) Continuing the above example, the following\nchecks if a user may close tasks::\n\n    user.has_perm('app.close_task')\n\n.. _extending-user:\n\nExtending the existing ``User`` model\n=====================================\n\nThere are two ways to extend the default\n:class:`~django.contrib.auth.models.User` model without substituting your own\nmodel. If the changes you need are purely behavioral, and don't require any\nchange to what is stored in the database, you can create a :ref:`proxy model\n<proxy-models>` based on :class:`~django.contrib.auth.models.User`. This\nallows for any of the features offered by proxy models including default\nordering, custom managers, or custom model methods.\n\nIf you wish to store information related to ``User``, you can use a\n:class:`~django.db.models.OneToOneField` to a model containing the fields for\nadditional information. This one-to-one model is often called a profile model,\nas it might store non-auth related information about a site user. For example\nyou might create an Employee model::\n\n    from django.contrib.auth.models import User\n\n    class Employee(models.Model):\n        user = models.OneToOneField(User, on_delete=models.CASCADE)\n        department = models.CharField(max_length=100)\n\nAssuming an existing Employee Fred Smith who has both a User and Employee\nmodel, you can access the related information using Django's standard related\nmodel conventions::\n\n    >>> u = User.objects.get(username='fsmith')\n    >>> freds_department = u.employee.department\n\nTo add a profile model's fields to the user page in the admin, define an\n:class:`~django.contrib.admin.InlineModelAdmin` (for this example, we'll use a\n:class:`~django.contrib.admin.StackedInline`) in your app's ``admin.py`` and\nadd it to a ``UserAdmin`` class which is registered with the\n:class:`~django.contrib.auth.models.User` class::\n\n    from django.contrib import admin\n    from django.contrib.auth.admin import UserAdmin as BaseUserAdmin\n    from django.contrib.auth.models import User\n\n    from my_user_profile_app.models import Employee\n\n    # Define an inline admin descriptor for Employee model\n    # which acts a bit like a singleton\n    class EmployeeInline(admin.StackedInline):\n        model = Employee\n        can_delete = False\n        verbose_name_plural = 'employee'\n\n    # Define a new User admin\n    class UserAdmin(BaseUserAdmin):\n        inlines = (EmployeeInline,)\n\n    # Re-register UserAdmin\n    admin.site.unregister(User)\n    admin.site.register(User, UserAdmin)\n\nThese profile models are not special in any way - they are just Django models\nthat happen to have a one-to-one link with a user model. As such, they aren't\nauto created when a user is created, but\na :attr:`django.db.models.signals.post_save` could be used to create or update\nrelated models as appropriate.\n\nUsing related models results in additional queries or joins to retrieve the\nrelated data. Depending on your needs, a custom user model that includes the\nrelated fields may be your better option, however, existing relations to the\ndefault user model within your project's apps may justify the extra database\nload.\n\n.. _auth-custom-user:\n\nSubstituting a custom ``User`` model\n====================================\n\nSome kinds of projects may have authentication requirements for which Django's\nbuilt-in :class:`~django.contrib.auth.models.User` model is not always\nappropriate. For instance, on some sites it makes more sense to use an email\naddress as your identification token instead of a username.\n\nDjango allows you to override the default user model by providing a value for\nthe :setting:`AUTH_USER_MODEL` setting that references a custom model::\n\n     AUTH_USER_MODEL = 'myapp.MyUser'\n\nThis dotted pair describes the name of the Django app (which must be in your\n:setting:`INSTALLED_APPS`), and the name of the Django model that you wish to\nuse as your user model.\n\nUsing a custom user model when starting a project\n-------------------------------------------------\n\nIf you're starting a new project, it's highly recommended to set up a custom\nuser model, even if the default :class:`~django.contrib.auth.models.User` model\nis sufficient for you. This model behaves identically to the default user\nmodel, but you'll be able to customize it in the future if the need arises::\n\n    from django.contrib.auth.models import AbstractUser\n\n    class User(AbstractUser):\n        pass\n\nDon't forget to point :setting:`AUTH_USER_MODEL` to it. Do this before creating\nany migrations or running ``manage.py migrate`` for the first time.\n\nAlso, register the model in the app's ``admin.py``::\n\n    from django.contrib import admin\n    from django.contrib.auth.admin import UserAdmin\n    from .models import User\n\n    admin.site.register(User, UserAdmin)\n\nChanging to a custom user model mid-project\n-------------------------------------------\n\nChanging :setting:`AUTH_USER_MODEL` after you've created database tables is\nsignificantly more difficult since it affects foreign keys and many-to-many\nrelationships, for example.\n\nThis change can't be done automatically and requires manually fixing your\nschema, moving your data from the old user table, and possibly manually\nreapplying some migrations. See :ticket:`25313` for an outline of the steps.\n\nDue to limitations of Django's dynamic dependency feature for swappable\nmodels, the model referenced by :setting:`AUTH_USER_MODEL` must be created in\nthe first migration of its app (usually called ``0001_initial``); otherwise,\nyou'll have dependency issues.\n\nIn addition, you may run into a ``CircularDependencyError`` when running your\nmigrations as Django won't be able to automatically break the dependency loop\ndue to the dynamic dependency. If you see this error, you should break the loop\nby moving the models depended on by your user model into a second migration.\n(You can try making two normal models that have a ``ForeignKey`` to each other\nand seeing how ``makemigrations`` resolves that circular dependency if you want\nto see how it's usually done.)\n\nReusable apps and ``AUTH_USER_MODEL``\n-------------------------------------\n\nReusable apps shouldn't implement a custom user model. A project may use many\napps, and two reusable apps that implemented a custom user model couldn't be\nused together. If you need to store per user information in your app, use\na :class:`~django.db.models.ForeignKey` or\n:class:`~django.db.models.OneToOneField` to ``settings.AUTH_USER_MODEL``\nas described below.\n\nReferencing the ``User`` model\n------------------------------\n\n.. currentmodule:: django.contrib.auth\n\nIf you reference :class:`~django.contrib.auth.models.User` directly (for\nexample, by referring to it in a foreign key), your code will not work in\nprojects where the :setting:`AUTH_USER_MODEL` setting has been changed to a\ndifferent user model.\n\n.. function:: get_user_model()\n\n    Instead of referring to :class:`~django.contrib.auth.models.User` directly,\n    you should reference the user model using\n    ``django.contrib.auth.get_user_model()``. This method will return the\n    currently active user model -- the custom user model if one is specified, or\n    :class:`~django.contrib.auth.models.User` otherwise.\n\n    When you define a foreign key or many-to-many relations to the user model,\n    you should specify the custom model using the :setting:`AUTH_USER_MODEL`\n    setting. For example::\n\n        from django.conf import settings\n        from django.db import models\n\n        class Article(models.Model):\n            author = models.ForeignKey(\n                settings.AUTH_USER_MODEL,\n                on_delete=models.CASCADE,\n            )\n\n    When connecting to signals sent by the user model, you should specify\n    the custom model using the :setting:`AUTH_USER_MODEL` setting. For example::\n\n        from django.conf import settings\n        from django.db.models.signals import post_save\n\n        def post_save_receiver(sender, instance, created, **kwargs):\n            pass\n\n        post_save.connect(post_save_receiver, sender=settings.AUTH_USER_MODEL)\n\n    Generally speaking, it's easiest to refer to the user model with the\n    :setting:`AUTH_USER_MODEL` setting in code that's executed at import time,\n    however, it's also possible to call ``get_user_model()`` while Django\n    is importing models, so you could use\n    ``models.ForeignKey(get_user_model(), ...)``.\n\n    If your app is tested with multiple user models, using\n    ``@override_settings(AUTH_USER_MODEL=...)`` for example, and you cache the\n    result of ``get_user_model()`` in a module-level variable, you may need to\n    listen to the  :data:`~django.test.signals.setting_changed` signal to clear\n    the cache. For example::\n\n        from django.apps import apps\n        from django.contrib.auth import get_user_model\n        from django.core.signals import setting_changed\n        from django.dispatch import receiver\n\n        @receiver(setting_changed)\n        def user_model_swapped(**kwargs):\n            if kwargs['setting'] == 'AUTH_USER_MODEL':\n                apps.clear_cache()\n                from myapp import some_module\n                some_module.UserModel = get_user_model()\n\n.. _specifying-custom-user-model:\n\nSpecifying a custom user model\n------------------------------\n\nWhen you start your project with a custom user model, stop to consider if this\nis the right choice for your project.\n\nKeeping all user related information in one model removes the need for\nadditional or more complex database queries to retrieve related models. On the\nother hand, it may be more suitable to store app-specific user information in a\nmodel that has a relation with your custom user model. That allows each app to\nspecify its own user data requirements without potentially conflicting or\nbreaking assumptions by other apps. It also means that you would keep your user\nmodel as simple as possible, focused on authentication, and following the\nminimum requirements Django expects custom user models to meet.\n\nIf you use the default authentication backend, then your model must have a\nsingle unique field that can be used for identification purposes. This can\nbe a username, an email address, or any other unique attribute. A non-unique\nusername field is allowed if you use a custom authentication backend that\ncan support it.\n\nThe easiest way to construct a compliant custom user model is to inherit from\n:class:`~django.contrib.auth.models.AbstractBaseUser`.\n:class:`~django.contrib.auth.models.AbstractBaseUser` provides the core\nimplementation of a user model, including hashed passwords and tokenized\npassword resets. You must then provide some key implementation details:\n\n.. currentmodule:: django.contrib.auth\n\n.. class:: models.CustomUser\n\n    .. attribute:: USERNAME_FIELD\n\n        A string describing the name of the field on the user model that is\n        used as the unique identifier. This will usually be a username of some\n        kind, but it can also be an email address, or any other unique\n        identifier. The field *must* be unique (i.e., have ``unique=True`` set\n        in its definition), unless you use a custom authentication backend that\n        can support non-unique usernames.\n\n        In the following example, the field ``identifier`` is used\n        as the identifying field::\n\n            class MyUser(AbstractBaseUser):\n                identifier = models.CharField(max_length=40, unique=True)\n                ...\n                USERNAME_FIELD = 'identifier'\n\n    .. attribute:: EMAIL_FIELD\n\n        A string describing the name of the email field on the ``User`` model.\n        This value is returned by\n        :meth:`~models.AbstractBaseUser.get_email_field_name`.\n\n    .. attribute:: REQUIRED_FIELDS\n\n        A list of the field names that will be prompted for when creating a\n        user via the :djadmin:`createsuperuser` management command. The user\n        will be prompted to supply a value for each of these fields. It must\n        include any field for which :attr:`~django.db.models.Field.blank` is\n        ``False`` or undefined and may include additional fields you want\n        prompted for when a user is created interactively.\n        ``REQUIRED_FIELDS`` has no effect in other parts of Django, like\n        creating a user in the admin.\n\n        For example, here is the partial definition for a user model that\n        defines two required fields - a date of birth and height::\n\n            class MyUser(AbstractBaseUser):\n                ...\n                date_of_birth = models.DateField()\n                height = models.FloatField()\n                ...\n                REQUIRED_FIELDS = ['date_of_birth', 'height']\n\n        .. note::\n\n            ``REQUIRED_FIELDS`` must contain all required fields on your user\n            model, but should *not* contain the ``USERNAME_FIELD`` or\n            ``password`` as these fields will always be prompted for.\n\n    .. attribute:: is_active\n\n        A boolean attribute that indicates whether the user is considered\n        \"active\".  This attribute is provided as an attribute on\n        ``AbstractBaseUser`` defaulting to ``True``. How you choose to\n        implement it will depend on the details of your chosen auth backends.\n        See the documentation of the :attr:`is_active attribute on the built-in\n        user model <django.contrib.auth.models.User.is_active>` for details.\n\n    .. method:: get_full_name()\n\n        Optional. A longer formal identifier for the user such as their full\n        name. If implemented, this appears alongside the username in an\n        object's history in :mod:`django.contrib.admin`.\n\n    .. method:: get_short_name()\n\n        Optional. A short, informal identifier for the user such as their\n        first name. If implemented, this replaces the username in the greeting\n        to the user in the header of :mod:`django.contrib.admin`.\n\n    .. admonition:: Importing ``AbstractBaseUser``\n\n        ``AbstractBaseUser`` and ``BaseUserManager`` are importable from\n        ``django.contrib.auth.base_user`` so that they can be imported without\n        including ``django.contrib.auth`` in :setting:`INSTALLED_APPS`.\n\nThe following attributes and methods are available on any subclass of\n:class:`~django.contrib.auth.models.AbstractBaseUser`:\n\n.. class:: models.AbstractBaseUser\n\n    .. method:: get_username()\n\n        Returns the value of the field nominated by ``USERNAME_FIELD``.\n\n    .. method:: clean()\n\n        Normalizes the username by calling :meth:`normalize_username`. If you\n        override this method, be sure to call ``super()`` to retain the\n        normalization.\n\n    .. classmethod:: get_email_field_name()\n\n       Returns the name of the email field specified by the\n       :attr:`~models.CustomUser.EMAIL_FIELD` attribute. Defaults to\n       ``'email'`` if ``EMAIL_FIELD`` isn't specified.\n\n    .. classmethod:: normalize_username(username)\n\n        Applies NFKC Unicode normalization to usernames so that visually\n        identical characters with different Unicode code points are considered\n        identical.\n\n    .. attribute:: models.AbstractBaseUser.is_authenticated\n\n        Read-only attribute which is always ``True`` (as opposed to\n        ``AnonymousUser.is_authenticated`` which is always ``False``).\n        This is a way to tell if the user has been authenticated. This does not\n        imply any permissions and doesn't check if the user is active or has\n        a valid session. Even though normally you will check this attribute on\n        ``request.user`` to find out whether it has been populated by the\n        :class:`~django.contrib.auth.middleware.AuthenticationMiddleware`\n        (representing the currently logged-in user), you should know this\n        attribute is ``True`` for any :class:`~models.User` instance.\n\n    .. attribute:: models.AbstractBaseUser.is_anonymous\n\n        Read-only attribute which is always ``False``. This is a way of\n        differentiating :class:`~models.User` and :class:`~models.AnonymousUser`\n        objects. Generally, you should prefer using\n        :attr:`~models.User.is_authenticated` to this attribute.\n\n    .. method:: models.AbstractBaseUser.set_password(raw_password)\n\n        Sets the user's password to the given raw string, taking care of the\n        password hashing. Doesn't save the\n        :class:`~django.contrib.auth.models.AbstractBaseUser` object.\n\n        When the raw_password is ``None``, the password will be set to an\n        unusable password, as if\n        :meth:`~django.contrib.auth.models.AbstractBaseUser.set_unusable_password()`\n        were used.\n\n    .. method:: models.AbstractBaseUser.check_password(raw_password)\n\n        Returns ``True`` if the given raw string is the correct password for\n        the user. (This takes care of the password hashing in making the\n        comparison.)\n\n    .. method:: models.AbstractBaseUser.set_unusable_password()\n\n        Marks the user as having no password set.  This isn't the same as\n        having a blank string for a password.\n        :meth:`~django.contrib.auth.models.AbstractBaseUser.check_password()` for this user\n        will never return ``True``. Doesn't save the\n        :class:`~django.contrib.auth.models.AbstractBaseUser` object.\n\n        You may need this if authentication for your application takes place\n        against an existing external source such as an LDAP directory.\n\n    .. method:: models.AbstractBaseUser.has_usable_password()\n\n        Returns ``False`` if\n        :meth:`~django.contrib.auth.models.AbstractBaseUser.set_unusable_password()` has\n        been called for this user.\n\n    .. method:: models.AbstractBaseUser.get_session_auth_hash()\n\n        Returns an HMAC of the password field. Used for\n        :ref:`session-invalidation-on-password-change`.\n\n        .. versionchanged:: 3.1\n\n            The hashing algorithm was changed to the SHA-256.\n\n:class:`~models.AbstractUser` subclasses :class:`~models.AbstractBaseUser`:\n\n.. class:: models.AbstractUser\n\n    .. method:: clean()\n\n        Normalizes the email by calling\n        :meth:`.BaseUserManager.normalize_email`. If you override this method,\n        be sure to call ``super()`` to retain the normalization.\n\nWriting a manager for a custom user model\n-----------------------------------------\n\nYou should also define a custom manager for your user model. If your user model\ndefines ``username``, ``email``, ``is_staff``, ``is_active``, ``is_superuser``,\n``last_login``, and ``date_joined`` fields the same as Django's default user,\nyou can install Django's :class:`~django.contrib.auth.models.UserManager`;\nhowever, if your user model defines different fields, you'll need to define a\ncustom manager that extends :class:`~django.contrib.auth.models.BaseUserManager`\nproviding two additional methods:\n\n.. class:: models.CustomUserManager\n\n    .. method:: models.CustomUserManager.create_user(username_field, password=None, **other_fields)\n\n        The prototype of ``create_user()`` should accept the username field,\n        plus all required fields as arguments. For example, if your user model\n        uses ``email`` as the username field, and has ``date_of_birth`` as a\n        required field, then ``create_user`` should be defined as::\n\n            def create_user(self, email, date_of_birth, password=None):\n                # create user here\n                ...\n\n    .. method:: models.CustomUserManager.create_superuser(username_field, password=None, **other_fields)\n\n        The prototype of ``create_superuser()`` should accept the username\n        field, plus all required fields as arguments. For example, if your user\n        model uses ``email`` as the username field, and has ``date_of_birth``\n        as a required field, then ``create_superuser`` should be defined as::\n\n            def create_superuser(self, email, date_of_birth, password=None):\n                # create superuser here\n                ...\n\nFor a :class:`~.ForeignKey` in :attr:`.USERNAME_FIELD` or\n:attr:`.REQUIRED_FIELDS`, these methods receive the value of the\n:attr:`~.ForeignKey.to_field` (the :attr:`~django.db.models.Field.primary_key`\nby default) of an existing instance.\n\n:class:`~django.contrib.auth.models.BaseUserManager` provides the following\nutility methods:\n\n.. class:: models.BaseUserManager\n\n    .. classmethod:: models.BaseUserManager.normalize_email(email)\n\n        Normalizes email addresses by lowercasing the domain portion of the\n        email address.\n\n    .. method:: models.BaseUserManager.get_by_natural_key(username)\n\n        Retrieves a user instance using the contents of the field\n        nominated by ``USERNAME_FIELD``.\n\n    .. method:: models.BaseUserManager.make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')\n\n        Returns a random password with the given length and given string of\n        allowed characters. Note that the default value of ``allowed_chars``\n        doesn't contain letters that can cause user confusion, including:\n\n        * ``i``, ``l``, ``I``, and ``1`` (lowercase letter i, lowercase\n          letter L, uppercase letter i, and the number one)\n        * ``o``, ``O``, and ``0`` (lowercase letter o, uppercase letter o,\n          and zero)\n\nExtending Django's default ``User``\n-----------------------------------\n\nIf you're entirely happy with Django's :class:`~django.contrib.auth.models.User`\nmodel, but you want to add some additional profile information, you could\nsubclass :class:`django.contrib.auth.models.AbstractUser` and add your custom\nprofile fields, although we'd recommend a separate model as described in the\n\"Model design considerations\" note of :ref:`specifying-custom-user-model`.\n``AbstractUser`` provides the full implementation of the default\n:class:`~django.contrib.auth.models.User` as an :ref:`abstract model\n<abstract-base-classes>`.\n\n.. _custom-users-and-the-built-in-auth-forms:\n\nCustom users and the built-in auth forms\n----------------------------------------\n\nDjango's built-in :ref:`forms <built-in-auth-forms>` and :ref:`views\n<built-in-auth-views>` make certain assumptions about the user model that they\nare working with.\n\nThe following forms are compatible with any subclass of\n:class:`~django.contrib.auth.models.AbstractBaseUser`:\n\n* :class:`~django.contrib.auth.forms.AuthenticationForm`: Uses the username\n  field specified by :attr:`~models.CustomUser.USERNAME_FIELD`.\n* :class:`~django.contrib.auth.forms.SetPasswordForm`\n* :class:`~django.contrib.auth.forms.PasswordChangeForm`\n* :class:`~django.contrib.auth.forms.AdminPasswordChangeForm`\n\nThe following forms make assumptions about the user model and can be used as-is\nif those assumptions are met:\n\n* :class:`~django.contrib.auth.forms.PasswordResetForm`: Assumes that the user\n  model has a field that stores the user's email address with the name returned\n  by :meth:`~models.AbstractBaseUser.get_email_field_name` (``email`` by\n  default) that can be used to identify the user and a boolean field named\n  ``is_active`` to prevent password resets for inactive users.\n\nFinally, the following forms are tied to\n:class:`~django.contrib.auth.models.User` and need to be rewritten or extended\nto work with a custom user model:\n\n* :class:`~django.contrib.auth.forms.UserCreationForm`\n* :class:`~django.contrib.auth.forms.UserChangeForm`\n\nIf your custom user model is a subclass of ``AbstractUser``, then you can\nextend these forms in this manner::\n\n    from django.contrib.auth.forms import UserCreationForm\n    from myapp.models import CustomUser\n\n    class CustomUserCreationForm(UserCreationForm):\n\n        class Meta(UserCreationForm.Meta):\n            model = CustomUser\n            fields = UserCreationForm.Meta.fields + ('custom_field',)\n\nCustom users and :mod:`django.contrib.admin`\n--------------------------------------------\n\nIf you want your custom user model to also work with the admin, your user model\nmust define some additional attributes and methods. These methods allow the\nadmin to control access of the user to admin content:\n\n.. class:: models.CustomUser\n    :noindex:\n\n.. attribute:: is_staff\n\n    Returns ``True`` if the user is allowed to have access to the admin site.\n\n.. attribute:: is_active\n\n    Returns ``True`` if the user account is currently active.\n\n.. method:: has_perm(perm, obj=None):\n\n    Returns ``True`` if the user has the named permission. If ``obj`` is\n    provided, the permission needs to be checked against a specific object\n    instance.\n\n.. method:: has_module_perms(app_label):\n\n    Returns ``True`` if the user has permission to access models in\n    the given app.\n\nYou will also need to register your custom user model with the admin. If\nyour custom user model extends ``django.contrib.auth.models.AbstractUser``,\nyou can use Django's existing ``django.contrib.auth.admin.UserAdmin``\nclass. However, if your user model extends\n:class:`~django.contrib.auth.models.AbstractBaseUser`, you'll need to define\na custom ``ModelAdmin`` class. It may be possible to subclass the default\n``django.contrib.auth.admin.UserAdmin``; however, you'll need to\noverride any of the definitions that refer to fields on\n``django.contrib.auth.models.AbstractUser`` that aren't on your\ncustom user class.\n\n.. note::\n\n    If you are using a custom ``ModelAdmin`` which is a subclass of\n    ``django.contrib.auth.admin.UserAdmin``, then you need to add your custom\n    fields to ``fieldsets`` (for fields to be used in editing users) and to\n    ``add_fieldsets`` (for fields to be used when creating a user). For\n    example::\n\n        from django.contrib.auth.admin import UserAdmin\n\n        class CustomUserAdmin(UserAdmin):\n            ...\n            fieldsets = UserAdmin.fieldsets + (\n                (None, {'fields': ('custom_field',)}),\n            )\n            add_fieldsets = UserAdmin.add_fieldsets + (\n                (None, {'fields': ('custom_field',)}),\n            )\n\n    See :ref:`a full example <custom-users-admin-full-example>` for more\n    details.\n\nCustom users and permissions\n----------------------------\n\nTo make it easy to include Django's permission framework into your own user\nclass, Django provides :class:`~django.contrib.auth.models.PermissionsMixin`.\nThis is an abstract model you can include in the class hierarchy for your user\nmodel, giving you all the methods and database fields necessary to support\nDjango's permission model.\n\n:class:`~django.contrib.auth.models.PermissionsMixin` provides the following\nmethods and attributes:\n\n.. class:: models.PermissionsMixin\n\n    .. attribute:: models.PermissionsMixin.is_superuser\n\n        Boolean. Designates that this user has all permissions without\n        explicitly assigning them.\n\n    .. method:: models.PermissionsMixin.get_user_permissions(obj=None)\n\n        Returns a set of permission strings that the user has directly.\n\n        If ``obj`` is passed in, only returns the user permissions for this\n        specific object.\n\n    .. method:: models.PermissionsMixin.get_group_permissions(obj=None)\n\n        Returns a set of permission strings that the user has, through their\n        groups.\n\n        If ``obj`` is passed in, only returns the group permissions for\n        this specific object.\n\n    .. method:: models.PermissionsMixin.get_all_permissions(obj=None)\n\n        Returns a set of permission strings that the user has, both through\n        group and user permissions.\n\n        If ``obj`` is passed in, only returns the permissions for this\n        specific object.\n\n    .. method:: models.PermissionsMixin.has_perm(perm, obj=None)\n\n        Returns ``True`` if the user has the specified permission, where\n        ``perm`` is in the format ``\"<app label>.<permission codename>\"`` (see\n        :ref:`permissions <topic-authorization>`). If :attr:`.User.is_active`\n        and :attr:`~.User.is_superuser` are both ``True``, this method always\n        returns ``True``.\n\n        If ``obj`` is passed in, this method won't check for a permission for\n        the model, but for this specific object.\n\n    .. method:: models.PermissionsMixin.has_perms(perm_list, obj=None)\n\n        Returns ``True`` if the user has each of the specified permissions,\n        where each perm is in the format\n        ``\"<app label>.<permission codename>\"``. If :attr:`.User.is_active` and\n        :attr:`~.User.is_superuser` are both ``True``, this method always\n        returns ``True``.\n\n        If ``obj`` is passed in, this method won't check for permissions for\n        the model, but for the specific object.\n\n    .. method:: models.PermissionsMixin.has_module_perms(package_name)\n\n        Returns ``True`` if the user has any permissions in the given package\n        (the Django app label). If :attr:`.User.is_active` and\n        :attr:`~.User.is_superuser` are both ``True``, this method always\n        returns ``True``.\n\n.. admonition:: ``PermissionsMixin`` and ``ModelBackend``\n\n    If you don't include the\n    :class:`~django.contrib.auth.models.PermissionsMixin`, you must ensure you\n    don't invoke the permissions methods on ``ModelBackend``. ``ModelBackend``\n    assumes that certain fields are available on your user model. If your user\n    model doesn't provide  those fields, you'll receive database errors when\n    you check permissions.\n\nCustom users and proxy models\n-----------------------------\n\nOne limitation of custom user models is that installing a custom user model\nwill break any proxy model extending :class:`~django.contrib.auth.models.User`.\nProxy models must be based on a concrete base class; by defining a custom user\nmodel, you remove the ability of Django to reliably identify the base class.\n\nIf your project uses proxy models, you must either modify the proxy to extend\nthe user model that's in use in your project, or merge your proxy's behavior\ninto your :class:`~django.contrib.auth.models.User` subclass.\n\n.. _custom-users-admin-full-example:\n\nA full example\n--------------\n\nHere is an example of an admin-compliant custom user app. This user model uses\nan email address as the username, and has a required date of birth; it\nprovides no permission checking beyond an ``admin`` flag on the user account.\nThis model would be compatible with all the built-in auth forms and views,\nexcept for the user creation forms. This example illustrates how most of the\ncomponents work together, but is not intended to be copied directly into\nprojects for production use.\n\nThis code would all live in a ``models.py`` file for a custom\nauthentication app::\n\n    from django.db import models\n    from django.contrib.auth.models import (\n        BaseUserManager, AbstractBaseUser\n    )\n\n\n    class MyUserManager(BaseUserManager):\n        def create_user(self, email, date_of_birth, password=None):\n            \"\"\"\n            Creates and saves a User with the given email, date of\n            birth and password.\n            \"\"\"\n            if not email:\n                raise ValueError('Users must have an email address')\n\n            user = self.model(\n                email=self.normalize_email(email),\n                date_of_birth=date_of_birth,\n            )\n\n            user.set_password(password)\n            user.save(using=self._db)\n            return user\n\n        def create_superuser(self, email, date_of_birth, password=None):\n            \"\"\"\n            Creates and saves a superuser with the given email, date of\n            birth and password.\n            \"\"\"\n            user = self.create_user(\n                email,\n                password=password,\n                date_of_birth=date_of_birth,\n            )\n            user.is_admin = True\n            user.save(using=self._db)\n            return user\n\n\n    class MyUser(AbstractBaseUser):\n        email = models.EmailField(\n            verbose_name='email address',\n            max_length=255,\n            unique=True,\n        )\n        date_of_birth = models.DateField()\n        is_active = models.BooleanField(default=True)\n        is_admin = models.BooleanField(default=False)\n\n        objects = MyUserManager()\n\n        USERNAME_FIELD = 'email'\n        REQUIRED_FIELDS = ['date_of_birth']\n\n        def __str__(self):\n            return self.email\n\n        def has_perm(self, perm, obj=None):\n            \"Does the user have a specific permission?\"\n            # Simplest possible answer: Yes, always\n            return True\n\n        def has_module_perms(self, app_label):\n            \"Does the user have permissions to view the app `app_label`?\"\n            # Simplest possible answer: Yes, always\n            return True\n\n        @property\n        def is_staff(self):\n            \"Is the user a member of staff?\"\n            # Simplest possible answer: All admins are staff\n            return self.is_admin\n\nThen, to register this custom user model with Django's admin, the following\ncode would be required in the app's ``admin.py`` file::\n\n    from django import forms\n    from django.contrib import admin\n    from django.contrib.auth.models import Group\n    from django.contrib.auth.admin import UserAdmin as BaseUserAdmin\n    from django.contrib.auth.forms import ReadOnlyPasswordHashField\n    from django.core.exceptions import ValidationError\n\n    from customauth.models import MyUser\n\n\n    class UserCreationForm(forms.ModelForm):\n        \"\"\"A form for creating new users. Includes all the required\n        fields, plus a repeated password.\"\"\"\n        password1 = forms.CharField(label='Password', widget=forms.PasswordInput)\n        password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)\n\n        class Meta:\n            model = MyUser\n            fields = ('email', 'date_of_birth')\n\n        def clean_password2(self):\n            # Check that the two password entries match\n            password1 = self.cleaned_data.get(\"password1\")\n            password2 = self.cleaned_data.get(\"password2\")\n            if password1 and password2 and password1 != password2:\n                raise ValidationError(\"Passwords don't match\")\n            return password2\n\n        def save(self, commit=True):\n            # Save the provided password in hashed format\n            user = super().save(commit=False)\n            user.set_password(self.cleaned_data[\"password1\"])\n            if commit:\n                user.save()\n            return user\n\n\n    class UserChangeForm(forms.ModelForm):\n        \"\"\"A form for updating users. Includes all the fields on\n        the user, but replaces the password field with admin's\n        password hash display field.\n        \"\"\"\n        password = ReadOnlyPasswordHashField()\n\n        class Meta:\n            model = MyUser\n            fields = ('email', 'password', 'date_of_birth', 'is_active', 'is_admin')\n\n        def clean_password(self):\n            # Regardless of what the user provides, return the initial value.\n            # This is done here, rather than on the field, because the\n            # field does not have access to the initial value\n            return self.initial[\"password\"]\n\n\n    class UserAdmin(BaseUserAdmin):\n        # The forms to add and change user instances\n        form = UserChangeForm\n        add_form = UserCreationForm\n\n        # The fields to be used in displaying the User model.\n        # These override the definitions on the base UserAdmin\n        # that reference specific fields on auth.User.\n        list_display = ('email', 'date_of_birth', 'is_admin')\n        list_filter = ('is_admin',)\n        fieldsets = (\n            (None, {'fields': ('email', 'password')}),\n            ('Personal info', {'fields': ('date_of_birth',)}),\n            ('Permissions', {'fields': ('is_admin',)}),\n        )\n        # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin\n        # overrides get_fieldsets to use this attribute when creating a user.\n        add_fieldsets = (\n            (None, {\n                'classes': ('wide',),\n                'fields': ('email', 'date_of_birth', 'password1', 'password2'),\n            }),\n        )\n        search_fields = ('email',)\n        ordering = ('email',)\n        filter_horizontal = ()\n\n\n    # Now register the new UserAdmin...\n    admin.site.register(MyUser, UserAdmin)\n    # ... and, since we're not using Django's built-in permissions,\n    # unregister the Group model from admin.\n    admin.site.unregister(Group)\n\nFinally, specify the custom model as the default user model for your project\nusing the :setting:`AUTH_USER_MODEL` setting in your ``settings.py``::\n\n    AUTH_USER_MODEL = 'customauth.MyUser'\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":319,"nodeType":"TextFile","repoName":null,"name":"models.txt","path":"docs/topics/db","text":"======\nModels\n======\n\n.. module:: django.db.models\n\nA model is the single, definitive source of information about your data. It\ncontains the essential fields and behaviors of the data you're storing.\nGenerally, each model maps to a single database table.\n\nThe basics:\n\n* Each model is a Python class that subclasses\n  :class:`django.db.models.Model`.\n\n* Each attribute of the model represents a database field.\n\n* With all of this, Django gives you an automatically-generated\n  database-access API; see :doc:`/topics/db/queries`.\n\n\nQuick example\n=============\n\nThis example model defines a ``Person``, which has a ``first_name`` and\n``last_name``::\n\n    from django.db import models\n\n    class Person(models.Model):\n        first_name = models.CharField(max_length=30)\n        last_name = models.CharField(max_length=30)\n\n``first_name`` and ``last_name`` are fields_ of the model. Each field is\nspecified as a class attribute, and each attribute maps to a database column.\n\nThe above ``Person`` model would create a database table like this:\n\n.. code-block:: sql\n\n    CREATE TABLE myapp_person (\n        \"id\" serial NOT NULL PRIMARY KEY,\n        \"first_name\" varchar(30) NOT NULL,\n        \"last_name\" varchar(30) NOT NULL\n    );\n\nSome technical notes:\n\n* The name of the table, ``myapp_person``, is automatically derived from\n  some model metadata but can be overridden. See :ref:`table-names` for more\n  details.\n\n* An ``id`` field is added automatically, but this behavior can be\n  overridden. See :ref:`automatic-primary-key-fields`.\n\n* The ``CREATE TABLE`` SQL in this example is formatted using PostgreSQL\n  syntax, but it's worth noting Django uses SQL tailored to the database\n  backend specified in your :doc:`settings file </topics/settings>`.\n\nUsing models\n============\n\nOnce you have defined your models, you need to tell Django you're going to *use*\nthose models. Do this by editing your settings file and changing the\n:setting:`INSTALLED_APPS` setting to add the name of the module that contains\nyour ``models.py``.\n\nFor example, if the models for your application live in the module\n``myapp.models`` (the package structure that is created for an\napplication by the :djadmin:`manage.py startapp <startapp>` script),\n:setting:`INSTALLED_APPS` should read, in part::\n\n    INSTALLED_APPS = [\n        #...\n        'myapp',\n        #...\n    ]\n\nWhen you add new apps to :setting:`INSTALLED_APPS`, be sure to run\n:djadmin:`manage.py migrate <migrate>`, optionally making migrations\nfor them first with :djadmin:`manage.py makemigrations <makemigrations>`.\n\nFields\n======\n\nThe most important part of a model -- and the only required part of a model --\nis the list of database fields it defines. Fields are specified by class\nattributes. Be careful not to choose field names that conflict with the\n:doc:`models API </ref/models/instances>` like ``clean``, ``save``, or\n``delete``.\n\nExample::\n\n    from django.db import models\n\n    class Musician(models.Model):\n        first_name = models.CharField(max_length=50)\n        last_name = models.CharField(max_length=50)\n        instrument = models.CharField(max_length=100)\n\n    class Album(models.Model):\n        artist = models.ForeignKey(Musician, on_delete=models.CASCADE)\n        name = models.CharField(max_length=100)\n        release_date = models.DateField()\n        num_stars = models.IntegerField()\n\nField types\n-----------\n\nEach field in your model should be an instance of the appropriate\n:class:`~django.db.models.Field` class. Django uses the field class types to\ndetermine a few things:\n\n* The column type, which tells the database what kind of data to store (e.g.\n  ``INTEGER``, ``VARCHAR``, ``TEXT``).\n\n* The default HTML :doc:`widget </ref/forms/widgets>` to use when rendering a form\n  field (e.g. ``<input type=\"text\">``, ``<select>``).\n\n* The minimal validation requirements, used in Django's admin and in\n  automatically-generated forms.\n\nDjango ships with dozens of built-in field types; you can find the complete list\nin the :ref:`model field reference <model-field-types>`. You can easily write\nyour own fields if Django's built-in ones don't do the trick; see\n:doc:`/howto/custom-model-fields`.\n\nField options\n-------------\n\nEach field takes a certain set of field-specific arguments (documented in the\n:ref:`model field reference <model-field-types>`). For example,\n:class:`~django.db.models.CharField` (and its subclasses) require a\n:attr:`~django.db.models.CharField.max_length` argument which specifies the size\nof the ``VARCHAR`` database field used to store the data.\n\nThere's also a set of common arguments available to all field types. All are\noptional. They're fully explained in the :ref:`reference\n<common-model-field-options>`, but here's a quick summary of the most often-used\nones:\n\n:attr:`~Field.null`\n    If ``True``, Django will store empty values as ``NULL`` in the database.\n    Default is ``False``.\n\n:attr:`~Field.blank`\n    If ``True``, the field is allowed to be blank. Default is ``False``.\n\n    Note that this is different than :attr:`~Field.null`.\n    :attr:`~Field.null` is purely database-related, whereas\n    :attr:`~Field.blank` is validation-related. If a field has\n    :attr:`blank=True <Field.blank>`, form validation will\n    allow entry of an empty value. If a field has :attr:`blank=False\n    <Field.blank>`, the field will be required.\n\n:attr:`~Field.choices`\n    A :term:`sequence` of 2-tuples to use as choices for this field. If this\n    is given, the default form widget will be a select box instead of the\n    standard text field and will limit choices to the choices given.\n\n    A choices list looks like this::\n\n        YEAR_IN_SCHOOL_CHOICES = [\n            ('FR', 'Freshman'),\n            ('SO', 'Sophomore'),\n            ('JR', 'Junior'),\n            ('SR', 'Senior'),\n            ('GR', 'Graduate'),\n        ]\n\n    .. note::\n        A new migration is created each time the order of ``choices`` changes.\n\n    The first element in each tuple is the value that will be stored in the\n    database. The second element is displayed by the field's form widget.\n\n    Given a model instance, the display value for a field with ``choices`` can\n    be accessed using the :meth:`~django.db.models.Model.get_FOO_display`\n    method. For example::\n\n        from django.db import models\n\n        class Person(models.Model):\n            SHIRT_SIZES = (\n                ('S', 'Small'),\n                ('M', 'Medium'),\n                ('L', 'Large'),\n            )\n            name = models.CharField(max_length=60)\n            shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES)\n\n    ::\n\n        >>> p = Person(name=\"Fred Flintstone\", shirt_size=\"L\")\n        >>> p.save()\n        >>> p.shirt_size\n        'L'\n        >>> p.get_shirt_size_display()\n        'Large'\n\n    You can also use enumeration classes to define ``choices`` in a concise\n    way::\n\n        from django.db import models\n\n        class Runner(models.Model):\n            MedalType = models.TextChoices('MedalType', 'GOLD SILVER BRONZE')\n            name = models.CharField(max_length=60)\n            medal = models.CharField(blank=True, choices=MedalType.choices, max_length=10)\n\n    Further examples are available in the :ref:`model field reference\n    <field-choices>`.\n\n:attr:`~Field.default`\n    The default value for the field. This can be a value or a callable\n    object. If callable it will be called every time a new object is\n    created.\n\n:attr:`~Field.help_text`\n    Extra \"help\" text to be displayed with the form widget. It's useful for\n    documentation even if your field isn't used on a form.\n\n:attr:`~Field.primary_key`\n    If ``True``, this field is the primary key for the model.\n\n    If you don't specify :attr:`primary_key=True <Field.primary_key>` for\n    any fields in your model, Django will automatically add an\n    :class:`IntegerField` to hold the primary key, so you don't need to set\n    :attr:`primary_key=True <Field.primary_key>` on any of your fields\n    unless you want to override the default primary-key behavior. For more,\n    see :ref:`automatic-primary-key-fields`.\n\n    The primary key field is read-only. If you change the value of the primary\n    key on an existing object and then save it, a new object will be created\n    alongside the old one. For example::\n\n        from django.db import models\n\n        class Fruit(models.Model):\n            name = models.CharField(max_length=100, primary_key=True)\n\n    .. code-block:: pycon\n\n        >>> fruit = Fruit.objects.create(name='Apple')\n        >>> fruit.name = 'Pear'\n        >>> fruit.save()\n        >>> Fruit.objects.values_list('name', flat=True)\n        <QuerySet ['Apple', 'Pear']>\n\n:attr:`~Field.unique`\n    If ``True``, this field must be unique throughout the table.\n\nAgain, these are just short descriptions of the most common field options. Full\ndetails can be found in the :ref:`common model field option reference\n<common-model-field-options>`.\n\n.. _automatic-primary-key-fields:\n\nAutomatic primary key fields\n----------------------------\n\nBy default, Django gives each model the following field::\n\n    id = models.AutoField(primary_key=True)\n\nThis is an auto-incrementing primary key.\n\nIf you'd like to specify a custom primary key, specify\n:attr:`primary_key=True <Field.primary_key>` on one of your fields. If Django\nsees you've explicitly set :attr:`Field.primary_key`, it won't add the automatic\n``id`` column.\n\nEach model requires exactly one field to have :attr:`primary_key=True\n<Field.primary_key>` (either explicitly declared or automatically added).\n\n.. _verbose-field-names:\n\nVerbose field names\n-------------------\n\nEach field type, except for :class:`~django.db.models.ForeignKey`,\n:class:`~django.db.models.ManyToManyField` and\n:class:`~django.db.models.OneToOneField`, takes an optional first positional\nargument -- a verbose name. If the verbose name isn't given, Django will\nautomatically create it using the field's attribute name, converting underscores\nto spaces.\n\nIn this example, the verbose name is ``\"person's first name\"``::\n\n    first_name = models.CharField(\"person's first name\", max_length=30)\n\nIn this example, the verbose name is ``\"first name\"``::\n\n    first_name = models.CharField(max_length=30)\n\n:class:`~django.db.models.ForeignKey`,\n:class:`~django.db.models.ManyToManyField` and\n:class:`~django.db.models.OneToOneField` require the first argument to be a\nmodel class, so use the :attr:`~Field.verbose_name` keyword argument::\n\n    poll = models.ForeignKey(\n        Poll,\n        on_delete=models.CASCADE,\n        verbose_name=\"the related poll\",\n    )\n    sites = models.ManyToManyField(Site, verbose_name=\"list of sites\")\n    place = models.OneToOneField(\n        Place,\n        on_delete=models.CASCADE,\n        verbose_name=\"related place\",\n    )\n\nThe convention is not to capitalize the first letter of the\n:attr:`~Field.verbose_name`. Django will automatically capitalize the first\nletter where it needs to.\n\nRelationships\n-------------\n\nClearly, the power of relational databases lies in relating tables to each\nother. Django offers ways to define the three most common types of database\nrelationships: many-to-one, many-to-many and one-to-one.\n\nMany-to-one relationships\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\nTo define a many-to-one relationship, use :class:`django.db.models.ForeignKey`.\nYou use it just like any other :class:`~django.db.models.Field` type: by\nincluding it as a class attribute of your model.\n\n:class:`~django.db.models.ForeignKey` requires a positional argument: the class\nto which the model is related.\n\nFor example, if a ``Car`` model has a ``Manufacturer`` -- that is, a\n``Manufacturer`` makes multiple cars but each ``Car`` only has one\n``Manufacturer`` -- use the following definitions::\n\n    from django.db import models\n\n    class Manufacturer(models.Model):\n        # ...\n        pass\n\n    class Car(models.Model):\n        manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE)\n        # ...\n\nYou can also create :ref:`recursive relationships <recursive-relationships>` (an\nobject with a many-to-one relationship to itself) and :ref:`relationships to\nmodels not yet defined <lazy-relationships>`; see :ref:`the model field\nreference <ref-foreignkey>` for details.\n\nIt's suggested, but not required, that the name of a\n:class:`~django.db.models.ForeignKey` field (``manufacturer`` in the example\nabove) be the name of the model, lowercase. You can call the field whatever you\nwant. For example::\n\n    class Car(models.Model):\n        company_that_makes_it = models.ForeignKey(\n            Manufacturer,\n            on_delete=models.CASCADE,\n        )\n        # ...\n\n.. seealso::\n\n    :class:`~django.db.models.ForeignKey` fields accept a number of extra\n    arguments which are explained in :ref:`the model field reference\n    <foreign-key-arguments>`. These options help define how the relationship\n    should work; all are optional.\n\n    For details on accessing backwards-related objects, see the\n    :ref:`Following relationships backward example <backwards-related-objects>`.\n\n    For sample code, see the :doc:`Many-to-one relationship model example\n    </topics/db/examples/many_to_one>`.\n\n\nMany-to-many relationships\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nTo define a many-to-many relationship, use\n:class:`~django.db.models.ManyToManyField`. You use it just like any other\n:class:`~django.db.models.Field` type: by including it as a class attribute of\nyour model.\n\n:class:`~django.db.models.ManyToManyField` requires a positional argument: the\nclass to which the model is related.\n\nFor example, if a ``Pizza`` has multiple ``Topping`` objects -- that is, a\n``Topping`` can be on multiple pizzas and each ``Pizza`` has multiple toppings\n-- here's how you'd represent that::\n\n    from django.db import models\n\n    class Topping(models.Model):\n        # ...\n        pass\n\n    class Pizza(models.Model):\n        # ...\n        toppings = models.ManyToManyField(Topping)\n\nAs with :class:`~django.db.models.ForeignKey`, you can also create\n:ref:`recursive relationships <recursive-relationships>` (an object with a\nmany-to-many relationship to itself) and :ref:`relationships to models not yet\ndefined <lazy-relationships>`.\n\nIt's suggested, but not required, that the name of a\n:class:`~django.db.models.ManyToManyField` (``toppings`` in the example above)\nbe a plural describing the set of related model objects.\n\nIt doesn't matter which model has the\n:class:`~django.db.models.ManyToManyField`, but you should only put it in one\nof the models -- not both.\n\nGenerally, :class:`~django.db.models.ManyToManyField` instances should go in\nthe object that's going to be edited on a form. In the above example,\n``toppings`` is in ``Pizza`` (rather than ``Topping`` having a ``pizzas``\n:class:`~django.db.models.ManyToManyField` ) because it's more natural to think\nabout a pizza having toppings than a topping being on multiple pizzas. The way\nit's set up above, the ``Pizza`` form would let users select the toppings.\n\n.. seealso::\n\n    See the :doc:`Many-to-many relationship model example\n    </topics/db/examples/many_to_many>` for a full example.\n\n:class:`~django.db.models.ManyToManyField` fields also accept a number of\nextra arguments which are explained in :ref:`the model field reference\n<manytomany-arguments>`. These options help define how the relationship\nshould work; all are optional.\n\n.. _intermediary-manytomany:\n\nExtra fields on many-to-many relationships\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nWhen you're only dealing with many-to-many relationships such as mixing and\nmatching pizzas and toppings, a standard\n:class:`~django.db.models.ManyToManyField` is all you need. However, sometimes\nyou may need to associate data with the relationship between two models.\n\nFor example, consider the case of an application tracking the musical groups\nwhich musicians belong to. There is a many-to-many relationship between a person\nand the groups of which they are a member, so you could use a\n:class:`~django.db.models.ManyToManyField` to represent this relationship.\nHowever, there is a lot of detail about the membership that you might want to\ncollect, such as the date at which the person joined the group.\n\nFor these situations, Django allows you to specify the model that will be used\nto govern the many-to-many relationship. You can then put extra fields on the\nintermediate model. The intermediate model is associated with the\n:class:`~django.db.models.ManyToManyField` using the\n:attr:`through <ManyToManyField.through>` argument to point to the model\nthat will act as an intermediary. For our musician example, the code would look\nsomething like this::\n\n    from django.db import models\n\n    class Person(models.Model):\n        name = models.CharField(max_length=128)\n\n        def __str__(self):\n            return self.name\n\n    class Group(models.Model):\n        name = models.CharField(max_length=128)\n        members = models.ManyToManyField(Person, through='Membership')\n\n        def __str__(self):\n            return self.name\n\n    class Membership(models.Model):\n        person = models.ForeignKey(Person, on_delete=models.CASCADE)\n        group = models.ForeignKey(Group, on_delete=models.CASCADE)\n        date_joined = models.DateField()\n        invite_reason = models.CharField(max_length=64)\n\nWhen you set up the intermediary model, you explicitly specify foreign\nkeys to the models that are involved in the many-to-many relationship. This\nexplicit declaration defines how the two models are related.\n\nThere are a few restrictions on the intermediate model:\n\n* Your intermediate model must contain one - and *only* one - foreign key\n  to the source model (this would be ``Group`` in our example), or you must\n  explicitly specify the foreign keys Django should use for the relationship\n  using :attr:`ManyToManyField.through_fields <ManyToManyField.through_fields>`.\n  If you have more than one foreign key and ``through_fields`` is not\n  specified, a validation error will be raised. A similar restriction applies\n  to the foreign key to the target model (this would be ``Person`` in our\n  example).\n\n* For a model which has a many-to-many relationship to itself through an\n  intermediary model, two foreign keys to the same model are permitted, but\n  they will be treated as the two (different) sides of the many-to-many\n  relationship. If there are *more* than two foreign keys though, you\n  must also specify ``through_fields`` as above, or a validation error\n  will be raised.\n\nNow that you have set up your :class:`~django.db.models.ManyToManyField` to use\nyour intermediary model (``Membership``, in this case), you're ready to start\ncreating some many-to-many relationships. You do this by creating instances of\nthe intermediate model::\n\n    >>> ringo = Person.objects.create(name=\"Ringo Starr\")\n    >>> paul = Person.objects.create(name=\"Paul McCartney\")\n    >>> beatles = Group.objects.create(name=\"The Beatles\")\n    >>> m1 = Membership(person=ringo, group=beatles,\n    ...     date_joined=date(1962, 8, 16),\n    ...     invite_reason=\"Needed a new drummer.\")\n    >>> m1.save()\n    >>> beatles.members.all()\n    <QuerySet [<Person: Ringo Starr>]>\n    >>> ringo.group_set.all()\n    <QuerySet [<Group: The Beatles>]>\n    >>> m2 = Membership.objects.create(person=paul, group=beatles,\n    ...     date_joined=date(1960, 8, 1),\n    ...     invite_reason=\"Wanted to form a band.\")\n    >>> beatles.members.all()\n    <QuerySet [<Person: Ringo Starr>, <Person: Paul McCartney>]>\n\nYou can also use ``add()``, ``create()``, or ``set()`` to create relationships,\nas long as you specify ``through_defaults`` for any required fields::\n\n    >>> beatles.members.add(john, through_defaults={'date_joined': date(1960, 8, 1)})\n    >>> beatles.members.create(name=\"George Harrison\", through_defaults={'date_joined': date(1960, 8, 1)})\n    >>> beatles.members.set([john, paul, ringo, george], through_defaults={'date_joined': date(1960, 8, 1)})\n\nYou may prefer to create instances of the intermediate model directly.\n\nIf the custom through table defined by the intermediate model does not enforce\nuniqueness on the ``(model1, model2)`` pair, allowing multiple values, the\n:meth:`~django.db.models.fields.related.RelatedManager.remove` call will\nremove all intermediate model instances::\n\n    >>> Membership.objects.create(person=ringo, group=beatles,\n    ...     date_joined=date(1968, 9, 4),\n    ...     invite_reason=\"You've been gone for a month and we miss you.\")\n    >>> beatles.members.all()\n    <QuerySet [<Person: Ringo Starr>, <Person: Paul McCartney>, <Person: Ringo Starr>]>\n    >>> # This deletes both of the intermediate model instances for Ringo Starr\n    >>> beatles.members.remove(ringo)\n    >>> beatles.members.all()\n    <QuerySet [<Person: Paul McCartney>]>\n\nThe :meth:`~django.db.models.fields.related.RelatedManager.clear`\nmethod can be used to remove all many-to-many relationships for an instance::\n\n    >>> # Beatles have broken up\n    >>> beatles.members.clear()\n    >>> # Note that this deletes the intermediate model instances\n    >>> Membership.objects.all()\n    <QuerySet []>\n\nOnce you have established the many-to-many relationships, you can issue\nqueries. Just as with normal many-to-many relationships, you can query using\nthe attributes of the many-to-many-related model::\n\n    # Find all the groups with a member whose name starts with 'Paul'\n    >>> Group.objects.filter(members__name__startswith='Paul')\n    <QuerySet [<Group: The Beatles>]>\n\nAs you are using an intermediate model, you can also query on its attributes::\n\n    # Find all the members of the Beatles that joined after 1 Jan 1961\n    >>> Person.objects.filter(\n    ...     group__name='The Beatles',\n    ...     membership__date_joined__gt=date(1961,1,1))\n    <QuerySet [<Person: Ringo Starr]>\n\nIf you need to access a membership's information you may do so by directly\nquerying the ``Membership`` model::\n\n    >>> ringos_membership = Membership.objects.get(group=beatles, person=ringo)\n    >>> ringos_membership.date_joined\n    datetime.date(1962, 8, 16)\n    >>> ringos_membership.invite_reason\n    'Needed a new drummer.'\n\nAnother way to access the same information is by querying the\n:ref:`many-to-many reverse relationship<m2m-reverse-relationships>` from a\n``Person`` object::\n\n    >>> ringos_membership = ringo.membership_set.get(group=beatles)\n    >>> ringos_membership.date_joined\n    datetime.date(1962, 8, 16)\n    >>> ringos_membership.invite_reason\n    'Needed a new drummer.'\n\nOne-to-one relationships\n~~~~~~~~~~~~~~~~~~~~~~~~\n\nTo define a one-to-one relationship, use\n:class:`~django.db.models.OneToOneField`. You use it just like any other\n``Field`` type: by including it as a class attribute of your model.\n\nThis is most useful on the primary key of an object when that object \"extends\"\nanother object in some way.\n\n:class:`~django.db.models.OneToOneField` requires a positional argument: the\nclass to which the model is related.\n\nFor example, if you were building a database of \"places\", you would\nbuild pretty standard stuff such as address, phone number, etc. in the\ndatabase. Then, if you wanted to build a database of restaurants on\ntop of the places, instead of repeating yourself and replicating those\nfields in the ``Restaurant`` model, you could make ``Restaurant`` have\na :class:`~django.db.models.OneToOneField` to ``Place`` (because a\nrestaurant \"is a\" place; in fact, to handle this you'd typically use\n:ref:`inheritance <model-inheritance>`, which involves an implicit\none-to-one relation).\n\nAs with :class:`~django.db.models.ForeignKey`, a :ref:`recursive relationship\n<recursive-relationships>` can be defined and :ref:`references to as-yet\nundefined models <lazy-relationships>` can be made.\n\n.. seealso::\n\n    See the :doc:`One-to-one relationship model example\n    </topics/db/examples/one_to_one>` for a full example.\n\n:class:`~django.db.models.OneToOneField` fields also accept an optional\n:attr:`~django.db.models.OneToOneField.parent_link` argument.\n\n:class:`~django.db.models.OneToOneField` classes used to automatically become\nthe primary key on a model. This is no longer true (although you can manually\npass in the :attr:`~django.db.models.Field.primary_key` argument if you like).\nThus, it's now possible to have multiple fields of type\n:class:`~django.db.models.OneToOneField` on a single model.\n\nModels across files\n-------------------\n\nIt's perfectly OK to relate a model to one from another app. To do this, import\nthe related model at the top of the file where your model is defined. Then,\nrefer to the other model class wherever needed. For example::\n\n    from django.db import models\n    from geography.models import ZipCode\n\n    class Restaurant(models.Model):\n        # ...\n        zip_code = models.ForeignKey(\n            ZipCode,\n            on_delete=models.SET_NULL,\n            blank=True,\n            null=True,\n        )\n\nField name restrictions\n-----------------------\n\nDjango places some restrictions on model field names:\n\n#. A field name cannot be a Python reserved word, because that would result\n   in a Python syntax error. For example::\n\n       class Example(models.Model):\n           pass = models.IntegerField() # 'pass' is a reserved word!\n\n#. A field name cannot contain more than one underscore in a row, due to\n   the way Django's query lookup syntax works. For example::\n\n       class Example(models.Model):\n           foo__bar = models.IntegerField() # 'foo__bar' has two underscores!\n\n#. A field name cannot end with an underscore, for similar reasons.\n\nThese limitations can be worked around, though, because your field name doesn't\nnecessarily have to match your database column name. See the\n:attr:`~Field.db_column` option.\n\nSQL reserved words, such as ``join``, ``where`` or ``select``, *are* allowed as\nmodel field names, because Django escapes all database table names and column\nnames in every underlying SQL query. It uses the quoting syntax of your\nparticular database engine.\n\nCustom field types\n------------------\n\nIf one of the existing model fields cannot be used to fit your purposes, or if\nyou wish to take advantage of some less common database column types, you can\ncreate your own field class. Full coverage of creating your own fields is\nprovided in :doc:`/howto/custom-model-fields`.\n\n.. _meta-options:\n\n``Meta`` options\n================\n\nGive your model metadata by using an inner ``class Meta``, like so::\n\n    from django.db import models\n\n    class Ox(models.Model):\n        horn_length = models.IntegerField()\n\n        class Meta:\n            ordering = [\"horn_length\"]\n            verbose_name_plural = \"oxen\"\n\nModel metadata is \"anything that's not a field\", such as ordering options\n(:attr:`~Options.ordering`), database table name (:attr:`~Options.db_table`), or\nhuman-readable singular and plural names (:attr:`~Options.verbose_name` and\n:attr:`~Options.verbose_name_plural`). None are required, and adding ``class\nMeta`` to a model is completely optional.\n\nA complete list of all possible ``Meta`` options can be found in the :doc:`model\noption reference </ref/models/options>`.\n\n.. _model-attributes:\n\nModel attributes\n================\n\n``objects``\n    The most important attribute of a model is the\n    :class:`~django.db.models.Manager`. It's the interface through which\n    database query operations are provided to Django models and is used to\n    :ref:`retrieve the instances <retrieving-objects>` from the database. If no\n    custom ``Manager`` is defined, the default name is\n    :attr:`~django.db.models.Model.objects`. Managers are only accessible via\n    model classes, not the model instances.\n\n.. _model-methods:\n\nModel methods\n=============\n\nDefine custom methods on a model to add custom \"row-level\" functionality to your\nobjects. Whereas :class:`~django.db.models.Manager` methods are intended to do\n\"table-wide\" things, model methods should act on a particular model instance.\n\nThis is a valuable technique for keeping business logic in one place -- the\nmodel.\n\nFor example, this model has a few custom methods::\n\n    from django.db import models\n\n    class Person(models.Model):\n        first_name = models.CharField(max_length=50)\n        last_name = models.CharField(max_length=50)\n        birth_date = models.DateField()\n\n        def baby_boomer_status(self):\n            \"Returns the person's baby-boomer status.\"\n            import datetime\n            if self.birth_date < datetime.date(1945, 8, 1):\n                return \"Pre-boomer\"\n            elif self.birth_date < datetime.date(1965, 1, 1):\n                return \"Baby boomer\"\n            else:\n                return \"Post-boomer\"\n\n        @property\n        def full_name(self):\n            \"Returns the person's full name.\"\n            return '%s %s' % (self.first_name, self.last_name)\n\nThe last method in this example is a :term:`property`.\n\nThe :doc:`model instance reference </ref/models/instances>` has a complete list\nof :ref:`methods automatically given to each model <model-instance-methods>`.\nYou can override most of these -- see `overriding predefined model methods`_,\nbelow -- but there are a couple that you'll almost always want to define:\n\n:meth:`~Model.__str__`\n    A Python \"magic method\" that returns a string representation of any\n    object. This is what Python and Django will use whenever a model\n    instance needs to be coerced and displayed as a plain string. Most\n    notably, this happens when you display an object in an interactive\n    console or in the admin.\n\n    You'll always want to define this method; the default isn't very helpful\n    at all.\n\n:meth:`~Model.get_absolute_url`\n    This tells Django how to calculate the URL for an object. Django uses\n    this in its admin interface, and any time it needs to figure out a URL\n    for an object.\n\n    Any object that has a URL that uniquely identifies it should define this\n    method.\n\n.. _overriding-model-methods:\n\nOverriding predefined model methods\n-----------------------------------\n\nThere's another set of :ref:`model methods <model-instance-methods>` that\nencapsulate a bunch of database behavior that you'll want to customize. In\nparticular you'll often want to change the way :meth:`~Model.save` and\n:meth:`~Model.delete` work.\n\nYou're free to override these methods (and any other model method) to alter\nbehavior.\n\nA classic use-case for overriding the built-in methods is if you want something\nto happen whenever you save an object. For example (see\n:meth:`~Model.save` for documentation of the parameters it accepts)::\n\n    from django.db import models\n\n    class Blog(models.Model):\n        name = models.CharField(max_length=100)\n        tagline = models.TextField()\n\n        def save(self, *args, **kwargs):\n            do_something()\n            super().save(*args, **kwargs)  # Call the \"real\" save() method.\n            do_something_else()\n\nYou can also prevent saving::\n\n    from django.db import models\n\n    class Blog(models.Model):\n        name = models.CharField(max_length=100)\n        tagline = models.TextField()\n\n        def save(self, *args, **kwargs):\n            if self.name == \"Yoko Ono's blog\":\n                return # Yoko shall never have her own blog!\n            else:\n                super().save(*args, **kwargs)  # Call the \"real\" save() method.\n\nIt's important to remember to call the superclass method -- that's\nthat ``super().save(*args, **kwargs)`` business -- to ensure\nthat the object still gets saved into the database. If you forget to\ncall the superclass method, the default behavior won't happen and the\ndatabase won't get touched.\n\nIt's also important that you pass through the arguments that can be\npassed to the model method -- that's what the ``*args, **kwargs`` bit\ndoes. Django will, from time to time, extend the capabilities of\nbuilt-in model methods, adding new arguments. If you use ``*args,\n**kwargs`` in your method definitions, you are guaranteed that your\ncode will automatically support those arguments when they are added.\n\n.. admonition:: Overridden model methods are not called on bulk operations\n\n    Note that the :meth:`~Model.delete()` method for an object is not\n    necessarily called when :ref:`deleting objects in bulk using a\n    QuerySet <topics-db-queries-delete>` or as a result of a :attr:`cascading\n    delete <django.db.models.ForeignKey.on_delete>`. To ensure customized\n    delete logic gets executed, you can use\n    :data:`~django.db.models.signals.pre_delete` and/or\n    :data:`~django.db.models.signals.post_delete` signals.\n\n    Unfortunately, there isn't a workaround when\n    :meth:`creating<django.db.models.query.QuerySet.bulk_create>` or\n    :meth:`updating<django.db.models.query.QuerySet.update>` objects in bulk,\n    since none of :meth:`~Model.save()`,\n    :data:`~django.db.models.signals.pre_save`, and\n    :data:`~django.db.models.signals.post_save` are called.\n\nExecuting custom SQL\n--------------------\n\nAnother common pattern is writing custom SQL statements in model methods and\nmodule-level methods. For more details on using raw SQL, see the documentation\non :doc:`using raw SQL</topics/db/sql>`.\n\n.. _model-inheritance:\n\nModel inheritance\n=================\n\nModel inheritance in Django works almost identically to the way normal\nclass inheritance works in Python, but the basics at the beginning of the page\nshould still be followed. That means the base class should subclass\n:class:`django.db.models.Model`.\n\nThe only decision you have to make is whether you want the parent models to be\nmodels in their own right (with their own database tables), or if the parents\nare just holders of common information that will only be visible through the\nchild models.\n\nThere are three styles of inheritance that are possible in Django.\n\n1. Often, you will just want to use the parent class to hold information that\n   you don't want to have to type out for each child model. This class isn't\n   going to ever be used in isolation, so :ref:`abstract-base-classes` are\n   what you're after.\n2. If you're subclassing an existing model (perhaps something from another\n   application entirely) and want each model to have its own database table,\n   :ref:`multi-table-inheritance` is the way to go.\n3. Finally, if you only want to modify the Python-level behavior of a model,\n   without changing the models fields in any way, you can use\n   :ref:`proxy-models`.\n\n.. _abstract-base-classes:\n\nAbstract base classes\n---------------------\n\nAbstract base classes are useful when you want to put some common\ninformation into a number of other models. You write your base class\nand put ``abstract=True`` in the :ref:`Meta <meta-options>`\nclass. This model will then not be used to create any database\ntable. Instead, when it is used as a base class for other models, its\nfields will be added to those of the child class.\n\nAn example::\n\n    from django.db import models\n\n    class CommonInfo(models.Model):\n        name = models.CharField(max_length=100)\n        age = models.PositiveIntegerField()\n\n        class Meta:\n            abstract = True\n\n    class Student(CommonInfo):\n        home_group = models.CharField(max_length=5)\n\nThe ``Student`` model will have three fields: ``name``, ``age`` and\n``home_group``. The ``CommonInfo`` model cannot be used as a normal Django\nmodel, since it is an abstract base class. It does not generate a database\ntable or have a manager, and cannot be instantiated or saved directly.\n\nFields inherited from abstract base classes can be overridden with another\nfield or value, or be removed with ``None``.\n\nFor many uses, this type of model inheritance will be exactly what you want.\nIt provides a way to factor out common information at the Python level, while\nstill only creating one database table per child model at the database level.\n\n``Meta`` inheritance\n~~~~~~~~~~~~~~~~~~~~\n\nWhen an abstract base class is created, Django makes any :ref:`Meta <meta-options>`\ninner class you declared in the base class available as an\nattribute. If a child class does not declare its own :ref:`Meta <meta-options>`\nclass, it will inherit the parent's :ref:`Meta <meta-options>`. If the child wants to\nextend the parent's :ref:`Meta <meta-options>` class, it can subclass it. For example::\n\n    from django.db import models\n\n    class CommonInfo(models.Model):\n        # ...\n        class Meta:\n            abstract = True\n            ordering = ['name']\n\n    class Student(CommonInfo):\n        # ...\n        class Meta(CommonInfo.Meta):\n            db_table = 'student_info'\n\nDjango does make one adjustment to the :ref:`Meta <meta-options>` class of an\nabstract base class: before installing the :ref:`Meta <meta-options>`\nattribute, it sets ``abstract=False``. This means that children of abstract\nbase classes don't automatically become abstract classes themselves. To make\nan abstract base class that inherits from another abstract base class, you need\nto explicitly set ``abstract=True`` on the child.\n\nSome attributes won't make sense to include in the :ref:`Meta <meta-options>` class of an\nabstract base class. For example, including ``db_table`` would mean that all\nthe child classes (the ones that don't specify their own :ref:`Meta <meta-options>`) would use\nthe same database table, which is almost certainly not what you want.\n\nDue to the way Python inheritance works, if a child class inherits from\nmultiple abstract base classes, only the :ref:`Meta <meta-options>` options\nfrom the first listed class will be inherited by default. To inherit :ref:`Meta\n<meta-options>` options from multiple abstract base classes, you must\nexplicitly declare the :ref:`Meta <meta-options>` inheritance. For example::\n\n    from django.db import models\n\n    class CommonInfo(models.Model):\n        name = models.CharField(max_length=100)\n        age = models.PositiveIntegerField()\n\n        class Meta:\n            abstract = True\n            ordering = ['name']\n\n    class Unmanaged(models.Model):\n        class Meta:\n            abstract = True\n            managed = False\n\n    class Student(CommonInfo, Unmanaged):\n        home_group = models.CharField(max_length=5)\n\n        class Meta(CommonInfo.Meta, Unmanaged.Meta):\n            pass\n\n.. _abstract-related-name:\n\nBe careful with ``related_name`` and ``related_query_name``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf you are using :attr:`~django.db.models.ForeignKey.related_name` or\n:attr:`~django.db.models.ForeignKey.related_query_name` on a ``ForeignKey`` or\n``ManyToManyField``, you must always specify a *unique* reverse name and query\nname for the field. This would normally cause a problem in abstract base\nclasses, since the fields on this class are included into each of the child\nclasses, with exactly the same values for the attributes (including\n:attr:`~django.db.models.ForeignKey.related_name` and\n:attr:`~django.db.models.ForeignKey.related_query_name`) each time.\n\nTo work around this problem, when you are using\n:attr:`~django.db.models.ForeignKey.related_name` or\n:attr:`~django.db.models.ForeignKey.related_query_name` in an abstract base\nclass (only), part of the value should contain ``'%(app_label)s'`` and\n``'%(class)s'``.\n\n- ``'%(class)s'`` is replaced by the lowercased name of the child class that\n  the field is used in.\n- ``'%(app_label)s'`` is replaced by the lowercased name of the app the child\n  class is contained within. Each installed application name must be unique and\n  the model class names within each app must also be unique, therefore the\n  resulting name will end up being different.\n\nFor example, given an app ``common/models.py``::\n\n    from django.db import models\n\n    class Base(models.Model):\n        m2m = models.ManyToManyField(\n            OtherModel,\n            related_name=\"%(app_label)s_%(class)s_related\",\n            related_query_name=\"%(app_label)s_%(class)ss\",\n        )\n\n        class Meta:\n            abstract = True\n\n    class ChildA(Base):\n        pass\n\n    class ChildB(Base):\n        pass\n\nAlong with another app ``rare/models.py``::\n\n    from common.models import Base\n\n    class ChildB(Base):\n        pass\n\nThe reverse name of the ``common.ChildA.m2m`` field will be\n``common_childa_related`` and the reverse query name will be ``common_childas``.\nThe reverse name of the ``common.ChildB.m2m`` field will be\n``common_childb_related`` and the reverse query name will be\n``common_childbs``. Finally, the reverse name of the ``rare.ChildB.m2m`` field\nwill be ``rare_childb_related`` and the reverse query name will be\n``rare_childbs``. It's up to you how you use the ``'%(class)s'`` and\n``'%(app_label)s'`` portion to construct your related name or related query name\nbut if you forget to use it, Django will raise errors when you perform system\nchecks (or run :djadmin:`migrate`).\n\nIf you don't specify a :attr:`~django.db.models.ForeignKey.related_name`\nattribute for a field in an abstract base class, the default reverse name will\nbe the name of the child class followed by ``'_set'``, just as it normally\nwould be if you'd declared the field directly on the child class. For example,\nin the above code, if the :attr:`~django.db.models.ForeignKey.related_name`\nattribute was omitted, the reverse name for the ``m2m`` field would be\n``childa_set`` in the ``ChildA`` case and ``childb_set`` for the ``ChildB``\nfield.\n\n.. _multi-table-inheritance:\n\nMulti-table inheritance\n-----------------------\n\nThe second type of model inheritance supported by Django is when each model in\nthe hierarchy is a model all by itself. Each model corresponds to its own\ndatabase table and can be queried and created individually. The inheritance\nrelationship introduces links between the child model and each of its parents\n(via an automatically-created :class:`~django.db.models.OneToOneField`).\nFor example::\n\n    from django.db import models\n\n    class Place(models.Model):\n        name = models.CharField(max_length=50)\n        address = models.CharField(max_length=80)\n\n    class Restaurant(Place):\n        serves_hot_dogs = models.BooleanField(default=False)\n        serves_pizza = models.BooleanField(default=False)\n\nAll of the fields of ``Place`` will also be available in ``Restaurant``,\nalthough the data will reside in a different database table. So these are both\npossible::\n\n    >>> Place.objects.filter(name=\"Bob's Cafe\")\n    >>> Restaurant.objects.filter(name=\"Bob's Cafe\")\n\nIf you have a ``Place`` that is also a ``Restaurant``, you can get from the\n``Place`` object to the ``Restaurant`` object by using the lowercase version of\nthe model name::\n\n    >>> p = Place.objects.get(id=12)\n    # If p is a Restaurant object, this will give the child class:\n    >>> p.restaurant\n    <Restaurant: ...>\n\nHowever, if ``p`` in the above example was *not* a ``Restaurant`` (it had been\ncreated directly as a ``Place`` object or was the parent of some other class),\nreferring to ``p.restaurant`` would raise a ``Restaurant.DoesNotExist``\nexception.\n\nThe automatically-created :class:`~django.db.models.OneToOneField` on\n``Restaurant`` that links it to ``Place`` looks like this::\n\n    place_ptr = models.OneToOneField(\n        Place, on_delete=models.CASCADE,\n        parent_link=True,\n        primary_key=True,\n    )\n\nYou can override that field by declaring your own\n:class:`~django.db.models.OneToOneField` with :attr:`parent_link=True\n<django.db.models.OneToOneField.parent_link>` on ``Restaurant``.\n\n.. _meta-and-multi-table-inheritance:\n\n``Meta`` and multi-table inheritance\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIn the multi-table inheritance situation, it doesn't make sense for a child\nclass to inherit from its parent's :ref:`Meta <meta-options>` class. All the :ref:`Meta <meta-options>` options\nhave already been applied to the parent class and applying them again would\nnormally only lead to contradictory behavior (this is in contrast with the\nabstract base class case, where the base class doesn't exist in its own\nright).\n\nSo a child model does not have access to its parent's :ref:`Meta\n<meta-options>` class. However, there are a few limited cases where the child\ninherits behavior from the parent: if the child does not specify an\n:attr:`~django.db.models.Options.ordering` attribute or a\n:attr:`~django.db.models.Options.get_latest_by` attribute, it will inherit\nthese from its parent.\n\nIf the parent has an ordering and you don't want the child to have any natural\nordering, you can explicitly disable it::\n\n    class ChildModel(ParentModel):\n        # ...\n        class Meta:\n            # Remove parent's ordering effect\n            ordering = []\n\nInheritance and reverse relations\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nBecause multi-table inheritance uses an implicit\n:class:`~django.db.models.OneToOneField` to link the child and\nthe parent, it's possible to move from the parent down to the child,\nas in the above example. However, this uses up the name that is the\ndefault :attr:`~django.db.models.ForeignKey.related_name` value for\n:class:`~django.db.models.ForeignKey` and\n:class:`~django.db.models.ManyToManyField` relations.  If you\nare putting those types of relations on a subclass of the parent model, you\n**must** specify the :attr:`~django.db.models.ForeignKey.related_name`\nattribute on each such field. If you forget, Django will raise a validation\nerror.\n\nFor example, using the above ``Place`` class again, let's create another\nsubclass with a :class:`~django.db.models.ManyToManyField`::\n\n    class Supplier(Place):\n        customers = models.ManyToManyField(Place)\n\nThis results in the error::\n\n    Reverse query name for 'Supplier.customers' clashes with reverse query\n    name for 'Supplier.place_ptr'.\n\n    HINT: Add or change a related_name argument to the definition for\n    'Supplier.customers' or 'Supplier.place_ptr'.\n\nAdding ``related_name`` to the ``customers`` field as follows would resolve the\nerror: ``models.ManyToManyField(Place, related_name='provider')``.\n\nSpecifying the parent link field\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nAs mentioned, Django will automatically create a\n:class:`~django.db.models.OneToOneField` linking your child\nclass back to any non-abstract parent models. If you want to control the\nname of the attribute linking back to the parent, you can create your\nown :class:`~django.db.models.OneToOneField` and set\n:attr:`parent_link=True <django.db.models.OneToOneField.parent_link>`\nto indicate that your field is the link back to the parent class.\n\n.. _proxy-models:\n\nProxy models\n------------\n\nWhen using :ref:`multi-table inheritance <multi-table-inheritance>`, a new\ndatabase table is created for each subclass of a model. This is usually the\ndesired behavior, since the subclass needs a place to store any additional\ndata fields that are not present on the base class. Sometimes, however, you\nonly want to change the Python behavior of a model -- perhaps to change the\ndefault manager, or add a new method.\n\nThis is what proxy model inheritance is for: creating a *proxy* for the\noriginal model. You can create, delete and update instances of the proxy model\nand all the data will be saved as if you were using the original (non-proxied)\nmodel. The difference is that you can change things like the default model\nordering or the default manager in the proxy, without having to alter the\noriginal.\n\nProxy models are declared like normal models. You tell Django that it's a\nproxy model by setting the :attr:`~django.db.models.Options.proxy` attribute of\nthe ``Meta`` class to ``True``.\n\nFor example, suppose you want to add a method to the ``Person`` model. You can do it like this::\n\n    from django.db import models\n\n    class Person(models.Model):\n        first_name = models.CharField(max_length=30)\n        last_name = models.CharField(max_length=30)\n\n    class MyPerson(Person):\n        class Meta:\n            proxy = True\n\n        def do_something(self):\n            # ...\n            pass\n\nThe ``MyPerson`` class operates on the same database table as its parent\n``Person`` class. In particular, any new instances of ``Person`` will also be\naccessible through ``MyPerson``, and vice-versa::\n\n    >>> p = Person.objects.create(first_name=\"foobar\")\n    >>> MyPerson.objects.get(first_name=\"foobar\")\n    <MyPerson: foobar>\n\nYou could also use a proxy model to define a different default ordering on\na model. You might not always want to order the ``Person`` model, but regularly\norder by the ``last_name`` attribute when you use the proxy::\n\n    class OrderedPerson(Person):\n        class Meta:\n            ordering = [\"last_name\"]\n            proxy = True\n\nNow normal ``Person`` queries will be unordered\nand ``OrderedPerson`` queries will be ordered by ``last_name``.\n\nProxy models inherit ``Meta`` attributes :ref:`in the same way as regular\nmodels <meta-and-multi-table-inheritance>`.\n\n``QuerySet``\\s still return the model that was requested\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThere is no way to have Django return, say, a ``MyPerson`` object whenever you\nquery for ``Person`` objects. A queryset for ``Person`` objects will return\nthose types of objects. The whole point of proxy objects is that code relying\non the original ``Person`` will use those and your own code can use the\nextensions you included (that no other code is relying on anyway). It is not\na way to replace the ``Person`` (or any other) model everywhere with something\nof your own creation.\n\nBase class restrictions\n~~~~~~~~~~~~~~~~~~~~~~~\n\nA proxy model must inherit from exactly one non-abstract model class. You\ncan't inherit from multiple non-abstract models as the proxy model doesn't\nprovide any connection between the rows in the different database tables. A\nproxy model can inherit from any number of abstract model classes, providing\nthey do *not* define any model fields. A proxy model may also inherit from any\nnumber of proxy models that share a common non-abstract parent class.\n\nProxy model managers\n~~~~~~~~~~~~~~~~~~~~\n\nIf you don't specify any model managers on a proxy model, it inherits the\nmanagers from its model parents. If you define a manager on the proxy model,\nit will become the default, although any managers defined on the parent\nclasses will still be available.\n\nContinuing our example from above, you could change the default manager used\nwhen you query the ``Person`` model like this::\n\n    from django.db import models\n\n    class NewManager(models.Manager):\n        # ...\n        pass\n\n    class MyPerson(Person):\n        objects = NewManager()\n\n        class Meta:\n            proxy = True\n\nIf you wanted to add a new manager to the Proxy, without replacing the\nexisting default, you can use the techniques described in the :ref:`custom\nmanager <custom-managers-and-inheritance>` documentation: create a base class\ncontaining the new managers and inherit that after the primary base class::\n\n    # Create an abstract class for the new manager.\n    class ExtraManagers(models.Model):\n        secondary = NewManager()\n\n        class Meta:\n            abstract = True\n\n    class MyPerson(Person, ExtraManagers):\n        class Meta:\n            proxy = True\n\nYou probably won't need to do this very often, but, when you do, it's\npossible.\n\n.. _proxy-vs-unmanaged-models:\n\nDifferences between proxy inheritance and unmanaged models\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nProxy model inheritance might look fairly similar to creating an unmanaged\nmodel, using the :attr:`~django.db.models.Options.managed` attribute on a\nmodel's ``Meta`` class.\n\nWith careful setting of :attr:`Meta.db_table\n<django.db.models.Options.db_table>` you could create an unmanaged model that\nshadows an existing model and adds Python methods to it. However, that would be\nvery repetitive and fragile as you need to keep both copies synchronized if you\nmake any changes.\n\nOn the other hand, proxy models are intended to behave exactly like the model\nthey are proxying for. They are always in sync with the parent model since they\ndirectly inherit its fields and managers.\n\nThe general rules are:\n\n#. If you are mirroring an existing model or database table and don't want\n   all the original database table columns, use ``Meta.managed=False``.\n   That option is normally useful for modeling database views and tables\n   not under the control of Django.\n#. If you are wanting to change the Python-only behavior of a model, but\n   keep all the same fields as in the original, use ``Meta.proxy=True``.\n   This sets things up so that the proxy model is an exact copy of the\n   storage structure of the original model when data is saved.\n\n.. _model-multiple-inheritance-topic:\n\nMultiple inheritance\n--------------------\n\nJust as with Python's subclassing, it's possible for a Django model to inherit\nfrom multiple parent models. Keep in mind that normal Python name resolution\nrules apply. The first base class that a particular name (e.g. :ref:`Meta\n<meta-options>`) appears in will be the one that is used; for example, this\nmeans that if multiple parents contain a :ref:`Meta <meta-options>` class,\nonly the first one is going to be used, and all others will be ignored.\n\nGenerally, you won't need to inherit from multiple parents. The main use-case\nwhere this is useful is for \"mix-in\" classes: adding a particular extra\nfield or method to every class that inherits the mix-in. Try to keep your\ninheritance hierarchies as simple and straightforward as possible so that you\nwon't have to struggle to work out where a particular piece of information is\ncoming from.\n\nNote that inheriting from multiple models that have a common ``id`` primary\nkey field will raise an error. To properly use multiple inheritance, you can\nuse an explicit :class:`~django.db.models.AutoField` in the base models::\n\n    class Article(models.Model):\n        article_id = models.AutoField(primary_key=True)\n        ...\n\n    class Book(models.Model):\n        book_id = models.AutoField(primary_key=True)\n        ...\n\n    class BookReview(Book, Article):\n        pass\n\nOr use a common ancestor to hold the :class:`~django.db.models.AutoField`. This\nrequires using an explicit :class:`~django.db.models.OneToOneField` from each\nparent model to the common ancestor to avoid a clash between the fields that\nare automatically generated and inherited by the child::\n\n    class Piece(models.Model):\n        pass\n\n    class Article(Piece):\n        article_piece = models.OneToOneField(Piece, on_delete=models.CASCADE, parent_link=True)\n        ...\n\n    class Book(Piece):\n        book_piece = models.OneToOneField(Piece, on_delete=models.CASCADE, parent_link=True)\n        ...\n\n    class BookReview(Book, Article):\n        pass\n\nField name \"hiding\" is not permitted\n------------------------------------\n\nIn normal Python class inheritance, it is permissible for a child class to\noverride any attribute from the parent class. In Django, this isn't usually\npermitted for model fields. If a non-abstract model base class has a field\ncalled ``author``, you can't create another model field or define\nan attribute called ``author`` in any class that inherits from that base class.\n\nThis restriction doesn't apply to model fields inherited from an abstract\nmodel. Such fields may be overridden with another field or value, or be removed\nby setting ``field_name = None``.\n\n.. warning::\n\n    Model managers are inherited from abstract base classes. Overriding an\n    inherited field which is referenced by an inherited\n    :class:`~django.db.models.Manager` may cause subtle bugs. See :ref:`custom\n    managers and model inheritance <custom-managers-and-inheritance>`.\n\n.. note::\n\n    Some fields define extra attributes on the model, e.g. a\n    :class:`~django.db.models.ForeignKey` defines an extra attribute with\n    ``_id`` appended to the field name, as well as ``related_name`` and\n    ``related_query_name`` on the foreign model.\n\n    These extra attributes cannot be overridden unless the field that defines\n    it is changed or removed so that it no longer defines the extra attribute.\n\nOverriding fields in a parent model leads to difficulties in areas such as\ninitializing new instances (specifying which field is being initialized in\n``Model.__init__``) and serialization. These are features which normal Python\nclass inheritance doesn't have to deal with in quite the same way, so the\ndifference between Django model inheritance and Python class inheritance isn't\narbitrary.\n\nThis restriction only applies to attributes which are\n:class:`~django.db.models.Field` instances. Normal Python attributes\ncan be overridden if you wish. It also only applies to the name of the\nattribute as Python sees it: if you are manually specifying the database\ncolumn name, you can have the same column name appearing in both a child and\nan ancestor model for multi-table inheritance (they are columns in two\ndifferent database tables).\n\nDjango will raise a :exc:`~django.core.exceptions.FieldError` if you override\nany model field in any ancestor model.\n\nOrganizing models in a package\n==============================\n\nThe :djadmin:`manage.py startapp <startapp>` command creates an application\nstructure that includes a ``models.py`` file. If you have many models,\norganizing them in separate files may be useful.\n\nTo do so, create a ``models`` package. Remove ``models.py`` and create a\n``myapp/models/`` directory with an ``__init__.py`` file and the files to\nstore your models. You must import the models in the ``__init__.py`` file.\n\nFor example, if you had ``organic.py`` and ``synthetic.py`` in the ``models``\ndirectory:\n\n.. code-block:: python\n    :caption: myapp/models/__init__.py\n\n    from .organic import Person\n    from .synthetic import Robot\n\nExplicitly importing each model rather than using ``from .models import *``\nhas the advantages of not cluttering the namespace, making code more readable,\nand keeping code analysis tools useful.\n\n.. seealso::\n\n    :doc:`The Models Reference </ref/models/index>`\n        Covers all the model related APIs including model fields, related\n        objects, and ``QuerySet``.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":320,"nodeType":"TextFile","repoName":null,"name":"queries.txt","path":"docs/topics/db","text":"==============\nMaking queries\n==============\n\n.. currentmodule:: django.db.models\n\nOnce you've created your :doc:`data models </topics/db/models>`, Django\nautomatically gives you a database-abstraction API that lets you create,\nretrieve, update and delete objects. This document explains how to use this\nAPI. Refer to the :doc:`data model reference </ref/models/index>` for full\ndetails of all the various model lookup options.\n\nThroughout this guide (and in the reference), we'll refer to the following\nmodels, which comprise a Weblog application:\n\n.. _queryset-model-example:\n\n.. code-block:: python\n\n    from django.db import models\n\n    class Blog(models.Model):\n        name = models.CharField(max_length=100)\n        tagline = models.TextField()\n\n        def __str__(self):\n            return self.name\n\n    class Author(models.Model):\n        name = models.CharField(max_length=200)\n        email = models.EmailField()\n\n        def __str__(self):\n            return self.name\n\n    class Entry(models.Model):\n        blog = models.ForeignKey(Blog, on_delete=models.CASCADE)\n        headline = models.CharField(max_length=255)\n        body_text = models.TextField()\n        pub_date = models.DateField()\n        mod_date = models.DateField()\n        authors = models.ManyToManyField(Author)\n        number_of_comments = models.IntegerField()\n        number_of_pingbacks = models.IntegerField()\n        rating = models.IntegerField()\n\n        def __str__(self):\n            return self.headline\n\nCreating objects\n================\n\nTo represent database-table data in Python objects, Django uses an intuitive\nsystem: A model class represents a database table, and an instance of that\nclass represents a particular record in the database table.\n\nTo create an object, instantiate it using keyword arguments to the model class,\nthen call :meth:`~django.db.models.Model.save` to save it to the database.\n\nAssuming models live in a file ``mysite/blog/models.py``, here's an example::\n\n    >>> from blog.models import Blog\n    >>> b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')\n    >>> b.save()\n\nThis performs an ``INSERT`` SQL statement behind the scenes. Django doesn't hit\nthe database until you explicitly call :meth:`~django.db.models.Model.save`.\n\nThe :meth:`~django.db.models.Model.save` method has no return value.\n\n.. seealso::\n\n    :meth:`~django.db.models.Model.save` takes a number of advanced options not\n    described here. See the documentation for\n    :meth:`~django.db.models.Model.save` for complete details.\n\n    To create and save an object in a single step, use the\n    :meth:`~django.db.models.query.QuerySet.create()` method.\n\nSaving changes to objects\n=========================\n\nTo save changes to an object that's already in the database, use\n:meth:`~django.db.models.Model.save`.\n\nGiven a ``Blog`` instance ``b5`` that has already been saved to the database,\nthis example changes its name and updates its record in the database::\n\n    >>> b5.name = 'New name'\n    >>> b5.save()\n\nThis performs an ``UPDATE`` SQL statement behind the scenes. Django doesn't hit\nthe database until you explicitly call :meth:`~django.db.models.Model.save`.\n\nSaving ``ForeignKey`` and ``ManyToManyField`` fields\n----------------------------------------------------\n\nUpdating a :class:`~django.db.models.ForeignKey` field works exactly the same\nway as saving a normal field -- assign an object of the right type to the field\nin question. This example updates the ``blog`` attribute of an ``Entry``\ninstance ``entry``, assuming appropriate instances of ``Entry`` and ``Blog``\nare already saved to the database (so we can retrieve them below)::\n\n    >>> from blog.models import Blog, Entry\n    >>> entry = Entry.objects.get(pk=1)\n    >>> cheese_blog = Blog.objects.get(name=\"Cheddar Talk\")\n    >>> entry.blog = cheese_blog\n    >>> entry.save()\n\nUpdating a :class:`~django.db.models.ManyToManyField` works a little\ndifferently -- use the\n:meth:`~django.db.models.fields.related.RelatedManager.add` method on the field\nto add a record to the relation. This example adds the ``Author`` instance\n``joe`` to the ``entry`` object::\n\n    >>> from blog.models import Author\n    >>> joe = Author.objects.create(name=\"Joe\")\n    >>> entry.authors.add(joe)\n\nTo add multiple records to a :class:`~django.db.models.ManyToManyField` in one\ngo, include multiple arguments in the call to\n:meth:`~django.db.models.fields.related.RelatedManager.add`, like this::\n\n    >>> john = Author.objects.create(name=\"John\")\n    >>> paul = Author.objects.create(name=\"Paul\")\n    >>> george = Author.objects.create(name=\"George\")\n    >>> ringo = Author.objects.create(name=\"Ringo\")\n    >>> entry.authors.add(john, paul, george, ringo)\n\nDjango will complain if you try to assign or add an object of the wrong type.\n\n.. _retrieving-objects:\n\nRetrieving objects\n==================\n\nTo retrieve objects from your database, construct a\n:class:`~django.db.models.query.QuerySet` via a\n:class:`~django.db.models.Manager` on your model class.\n\nA :class:`~django.db.models.query.QuerySet` represents a collection of objects\nfrom your database. It can have zero, one or many *filters*. Filters narrow\ndown the query results based on the given parameters. In SQL terms, a\n:class:`~django.db.models.query.QuerySet` equates to a ``SELECT`` statement,\nand a filter is a limiting clause such as ``WHERE`` or ``LIMIT``.\n\nYou get a :class:`~django.db.models.query.QuerySet` by using your model's\n:class:`~django.db.models.Manager`. Each model has at least one\n:class:`~django.db.models.Manager`, and it's called\n:attr:`~django.db.models.Model.objects` by default. Access it directly via the\nmodel class, like so::\n\n    >>> Blog.objects\n    <django.db.models.manager.Manager object at ...>\n    >>> b = Blog(name='Foo', tagline='Bar')\n    >>> b.objects\n    Traceback:\n        ...\n    AttributeError: \"Manager isn't accessible via Blog instances.\"\n\n.. note::\n\n    ``Managers`` are accessible only via model classes, rather than from model\n    instances, to enforce a separation between \"table-level\" operations and\n    \"record-level\" operations.\n\nThe :class:`~django.db.models.Manager` is the main source of ``QuerySets`` for\na model. For example, ``Blog.objects.all()`` returns a\n:class:`~django.db.models.query.QuerySet` that contains all ``Blog`` objects in\nthe database.\n\nRetrieving all objects\n----------------------\n\nThe simplest way to retrieve objects from a table is to get all of them. To do\nthis, use the :meth:`~django.db.models.query.QuerySet.all` method on a\n:class:`~django.db.models.Manager`::\n\n    >>> all_entries = Entry.objects.all()\n\nThe :meth:`~django.db.models.query.QuerySet.all` method returns a\n:class:`~django.db.models.query.QuerySet` of all the objects in the database.\n\nRetrieving specific objects with filters\n----------------------------------------\n\nThe :class:`~django.db.models.query.QuerySet` returned by\n:meth:`~django.db.models.query.QuerySet.all` describes all objects in the\ndatabase table. Usually, though, you'll need to select only a subset of the\ncomplete set of objects.\n\nTo create such a subset, you refine the initial\n:class:`~django.db.models.query.QuerySet`, adding filter conditions. The two\nmost common ways to refine a :class:`~django.db.models.query.QuerySet` are:\n\n``filter(**kwargs)``\n    Returns a new :class:`~django.db.models.query.QuerySet` containing objects\n    that match the given lookup parameters.\n\n``exclude(**kwargs)``\n    Returns a new :class:`~django.db.models.query.QuerySet` containing objects\n    that do *not* match the given lookup parameters.\n\nThe lookup parameters (``**kwargs`` in the above function definitions) should\nbe in the format described in `Field lookups`_ below.\n\nFor example, to get a :class:`~django.db.models.query.QuerySet` of blog entries\nfrom the year 2006, use :meth:`~django.db.models.query.QuerySet.filter` like\nso::\n\n    Entry.objects.filter(pub_date__year=2006)\n\nWith the default manager class, it is the same as::\n\n    Entry.objects.all().filter(pub_date__year=2006)\n\n.. _chaining-filters:\n\nChaining filters\n~~~~~~~~~~~~~~~~\n\nThe result of refining a :class:`~django.db.models.query.QuerySet` is itself a\n:class:`~django.db.models.query.QuerySet`, so it's possible to chain\nrefinements together. For example::\n\n    >>> Entry.objects.filter(\n    ...     headline__startswith='What'\n    ... ).exclude(\n    ...     pub_date__gte=datetime.date.today()\n    ... ).filter(\n    ...     pub_date__gte=datetime.date(2005, 1, 30)\n    ... )\n\nThis takes the initial :class:`~django.db.models.query.QuerySet` of all entries\nin the database, adds a filter, then an exclusion, then another filter. The\nfinal result is a :class:`~django.db.models.query.QuerySet` containing all\nentries with a headline that starts with \"What\", that were published between\nJanuary 30, 2005, and the current day.\n\n.. _filtered-querysets-are-unique:\n\nFiltered ``QuerySet``\\s are unique\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nEach time you refine a :class:`~django.db.models.query.QuerySet`, you get a\nbrand-new :class:`~django.db.models.query.QuerySet` that is in no way bound to\nthe previous :class:`~django.db.models.query.QuerySet`. Each refinement creates\na separate and distinct :class:`~django.db.models.query.QuerySet` that can be\nstored, used and reused.\n\nExample::\n\n    >>> q1 = Entry.objects.filter(headline__startswith=\"What\")\n    >>> q2 = q1.exclude(pub_date__gte=datetime.date.today())\n    >>> q3 = q1.filter(pub_date__gte=datetime.date.today())\n\nThese three ``QuerySets`` are separate. The first is a base\n:class:`~django.db.models.query.QuerySet` containing all entries that contain a\nheadline starting with \"What\". The second is a subset of the first, with an\nadditional criteria that excludes records whose ``pub_date`` is today or in the\nfuture. The third is a subset of the first, with an additional criteria that\nselects only the records whose ``pub_date`` is today or in the future. The\ninitial :class:`~django.db.models.query.QuerySet` (``q1``) is unaffected by the\nrefinement process.\n\n.. _querysets-are-lazy:\n\n``QuerySet``\\s are lazy\n~~~~~~~~~~~~~~~~~~~~~~~\n\n``QuerySets`` are lazy -- the act of creating a\n:class:`~django.db.models.query.QuerySet` doesn't involve any database\nactivity. You can stack filters together all day long, and Django won't\nactually run the query until the :class:`~django.db.models.query.QuerySet` is\n*evaluated*. Take a look at this example::\n\n    >>> q = Entry.objects.filter(headline__startswith=\"What\")\n    >>> q = q.filter(pub_date__lte=datetime.date.today())\n    >>> q = q.exclude(body_text__icontains=\"food\")\n    >>> print(q)\n\nThough this looks like three database hits, in fact it hits the database only\nonce, at the last line (``print(q)``). In general, the results of a\n:class:`~django.db.models.query.QuerySet` aren't fetched from the database\nuntil you \"ask\" for them. When you do, the\n:class:`~django.db.models.query.QuerySet` is *evaluated* by accessing the\ndatabase. For more details on exactly when evaluation takes place, see\n:ref:`when-querysets-are-evaluated`.\n\n.. _retrieving-single-object-with-get:\n\nRetrieving a single object with ``get()``\n-----------------------------------------\n\n:meth:`~django.db.models.query.QuerySet.filter` will always give you a\n:class:`~django.db.models.query.QuerySet`, even if only a single object matches\nthe query - in this case, it will be a\n:class:`~django.db.models.query.QuerySet` containing a single element.\n\nIf you know there is only one object that matches your query, you can use the\n:meth:`~django.db.models.query.QuerySet.get` method on a\n:class:`~django.db.models.Manager` which returns the object directly::\n\n    >>> one_entry = Entry.objects.get(pk=1)\n\nYou can use any query expression with\n:meth:`~django.db.models.query.QuerySet.get`, just like with\n:meth:`~django.db.models.query.QuerySet.filter` - again, see `Field lookups`_\nbelow.\n\nNote that there is a difference between using\n:meth:`~django.db.models.query.QuerySet.get`, and using\n:meth:`~django.db.models.query.QuerySet.filter` with a slice of ``[0]``. If\nthere are no results that match the query,\n:meth:`~django.db.models.query.QuerySet.get` will raise a ``DoesNotExist``\nexception. This exception is an attribute of the model class that the query is\nbeing performed on - so in the code above, if there is no ``Entry`` object with\na primary key of 1, Django will raise ``Entry.DoesNotExist``.\n\nSimilarly, Django will complain if more than one item matches the\n:meth:`~django.db.models.query.QuerySet.get` query. In this case, it will raise\n:exc:`~django.core.exceptions.MultipleObjectsReturned`, which again is an\nattribute of the model class itself.\n\n\nOther ``QuerySet`` methods\n--------------------------\n\nMost of the time you'll use :meth:`~django.db.models.query.QuerySet.all`,\n:meth:`~django.db.models.query.QuerySet.get`,\n:meth:`~django.db.models.query.QuerySet.filter` and\n:meth:`~django.db.models.query.QuerySet.exclude` when you need to look up\nobjects from the database. However, that's far from all there is; see the\n:ref:`QuerySet API Reference <queryset-api>` for a complete list of all the\nvarious :class:`~django.db.models.query.QuerySet` methods.\n\n.. _limiting-querysets:\n\nLimiting ``QuerySet``\\s\n-----------------------\n\nUse a subset of Python's array-slicing syntax to limit your\n:class:`~django.db.models.query.QuerySet` to a certain number of results. This\nis the equivalent of SQL's ``LIMIT`` and ``OFFSET`` clauses.\n\nFor example, this returns the first 5 objects (``LIMIT 5``)::\n\n    >>> Entry.objects.all()[:5]\n\nThis returns the sixth through tenth objects (``OFFSET 5 LIMIT 5``)::\n\n    >>> Entry.objects.all()[5:10]\n\nNegative indexing (i.e. ``Entry.objects.all()[-1]``) is not supported.\n\nGenerally, slicing a :class:`~django.db.models.query.QuerySet` returns a new\n:class:`~django.db.models.query.QuerySet` -- it doesn't evaluate the query. An\nexception is if you use the \"step\" parameter of Python slice syntax. For\nexample, this would actually execute the query in order to return a list of\nevery *second* object of the first 10::\n\n    >>> Entry.objects.all()[:10:2]\n\nFurther filtering or ordering of a sliced queryset is prohibited due to the\nambiguous nature of how that might work.\n\nTo retrieve a *single* object rather than a list\n(e.g. ``SELECT foo FROM bar LIMIT 1``), use an index instead of a slice. For\nexample, this returns the first ``Entry`` in the database, after ordering\nentries alphabetically by headline::\n\n    >>> Entry.objects.order_by('headline')[0]\n\nThis is roughly equivalent to::\n\n    >>> Entry.objects.order_by('headline')[0:1].get()\n\nNote, however, that the first of these will raise ``IndexError`` while the\nsecond will raise ``DoesNotExist`` if no objects match the given criteria. See\n:meth:`~django.db.models.query.QuerySet.get` for more details.\n\n.. _field-lookups-intro:\n\nField lookups\n-------------\n\nField lookups are how you specify the meat of an SQL ``WHERE`` clause. They're\nspecified as keyword arguments to the :class:`~django.db.models.query.QuerySet`\nmethods :meth:`~django.db.models.query.QuerySet.filter`,\n:meth:`~django.db.models.query.QuerySet.exclude` and\n:meth:`~django.db.models.query.QuerySet.get`.\n\nBasic lookups keyword arguments take the form ``field__lookuptype=value``.\n(That's a double-underscore). For example::\n\n    >>> Entry.objects.filter(pub_date__lte='2006-01-01')\n\ntranslates (roughly) into the following SQL:\n\n.. code-block:: sql\n\n    SELECT * FROM blog_entry WHERE pub_date <= '2006-01-01';\n\n.. admonition:: How this is possible\n\n   Python has the ability to define functions that accept arbitrary name-value\n   arguments whose names and values are evaluated at runtime. For more\n   information, see :ref:`tut-keywordargs` in the official Python tutorial.\n\nThe field specified in a lookup has to be the name of a model field. There's\none exception though, in case of a :class:`~django.db.models.ForeignKey` you\ncan specify the field name suffixed with ``_id``. In this case, the value\nparameter is expected to contain the raw value of the foreign model's primary\nkey. For example:\n\n    >>> Entry.objects.filter(blog_id=4)\n\nIf you pass an invalid keyword argument, a lookup function will raise\n``TypeError``.\n\nThe database API supports about two dozen lookup types; a complete reference\ncan be found in the :ref:`field lookup reference <field-lookups>`. To give you\na taste of what's available, here's some of the more common lookups you'll\nprobably use:\n\n:lookup:`exact`\n    An \"exact\" match. For example::\n\n        >>> Entry.objects.get(headline__exact=\"Cat bites dog\")\n\n    Would generate SQL along these lines:\n\n    .. code-block:: sql\n\n        SELECT ... WHERE headline = 'Cat bites dog';\n\n    If you don't provide a lookup type -- that is, if your keyword argument\n    doesn't contain a double underscore -- the lookup type is assumed to be\n    ``exact``.\n\n    For example, the following two statements are equivalent::\n\n        >>> Blog.objects.get(id__exact=14)  # Explicit form\n        >>> Blog.objects.get(id=14)         # __exact is implied\n\n    This is for convenience, because ``exact`` lookups are the common case.\n\n:lookup:`iexact`\n    A case-insensitive match. So, the query::\n\n        >>> Blog.objects.get(name__iexact=\"beatles blog\")\n\n    Would match a ``Blog`` titled ``\"Beatles Blog\"``, ``\"beatles blog\"``, or\n    even ``\"BeAtlES blOG\"``.\n\n:lookup:`contains`\n    Case-sensitive containment test. For example::\n\n        Entry.objects.get(headline__contains='Lennon')\n\n    Roughly translates to this SQL:\n\n    .. code-block:: sql\n\n        SELECT ... WHERE headline LIKE '%Lennon%';\n\n    Note this will match the headline ``'Today Lennon honored'`` but not\n    ``'today lennon honored'``.\n\n    There's also a case-insensitive version, :lookup:`icontains`.\n\n:lookup:`startswith`, :lookup:`endswith`\n    Starts-with and ends-with search, respectively. There are also\n    case-insensitive versions called :lookup:`istartswith` and\n    :lookup:`iendswith`.\n\nAgain, this only scratches the surface. A complete reference can be found in the\n:ref:`field lookup reference <field-lookups>`.\n\n.. _lookups-that-span-relationships:\n\nLookups that span relationships\n-------------------------------\n\nDjango offers a powerful and intuitive way to \"follow\" relationships in\nlookups, taking care of the SQL ``JOIN``\\s for you automatically, behind the\nscenes. To span a relationship, use the field name of related fields\nacross models, separated by double underscores, until you get to the field you\nwant.\n\nThis example retrieves all ``Entry`` objects with a ``Blog`` whose ``name``\nis ``'Beatles Blog'``::\n\n    >>> Entry.objects.filter(blog__name='Beatles Blog')\n\nThis spanning can be as deep as you'd like.\n\nIt works backwards, too. Whilst it :attr:`can be customized\n<.ForeignKey.related_query_name>`, by default you refer to a \"reverse\"\nrelationship in a lookup using the lowercase name of the model.\n\nThis example retrieves all ``Blog`` objects which have at least one ``Entry``\nwhose ``headline`` contains ``'Lennon'``::\n\n    >>> Blog.objects.filter(entry__headline__contains='Lennon')\n\nIf you are filtering across multiple relationships and one of the intermediate\nmodels doesn't have a value that meets the filter condition, Django will treat\nit as if there is an empty (all values are ``NULL``), but valid, object there.\nAll this means is that no error will be raised. For example, in this filter::\n\n    Blog.objects.filter(entry__authors__name='Lennon')\n\n(if there was a related ``Author`` model), if there was no ``author``\nassociated with an entry, it would be treated as if there was also no ``name``\nattached, rather than raising an error because of the missing ``author``.\nUsually this is exactly what you want to have happen. The only case where it\nmight be confusing is if you are using :lookup:`isnull`. Thus::\n\n    Blog.objects.filter(entry__authors__name__isnull=True)\n\nwill return ``Blog`` objects that have an empty ``name`` on the ``author`` and\nalso those which have an empty ``author`` on the ``entry``. If you don't want\nthose latter objects, you could write::\n\n    Blog.objects.filter(entry__authors__isnull=False, entry__authors__name__isnull=True)\n\nSpanning multi-valued relationships\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nWhen you are filtering an object based on a\n:class:`~django.db.models.ManyToManyField` or a reverse\n:class:`~django.db.models.ForeignKey`, there are two different sorts of filter\nyou may be interested in. Consider the ``Blog``/``Entry`` relationship\n(``Blog`` to ``Entry`` is a one-to-many relation). We might be interested in\nfinding blogs that have an entry which has both *\"Lennon\"* in the headline and\nwas published in 2008. Or we might want to find blogs that have an entry with\n*\"Lennon\"* in the headline as well as an entry that was published\nin 2008. Since there are multiple entries associated with a single ``Blog``,\nboth of these queries are possible and make sense in some situations.\n\nThe same type of situation arises with a\n:class:`~django.db.models.ManyToManyField`. For example, if an ``Entry`` has a\n:class:`~django.db.models.ManyToManyField` called ``tags``, we might want to\nfind entries linked to tags called *\"music\"* and *\"bands\"* or we might want an\nentry that contains a tag with a name of *\"music\"* and a status of *\"public\"*.\n\nTo handle both of these situations, Django has a consistent way of processing\n:meth:`~django.db.models.query.QuerySet.filter` calls. Everything inside a\nsingle :meth:`~django.db.models.query.QuerySet.filter` call is applied\nsimultaneously to filter out items matching all those requirements. Successive\n:meth:`~django.db.models.query.QuerySet.filter` calls further restrict the set\nof objects, but for multi-valued relations, they apply to any object linked to\nthe primary model, not necessarily those objects that were selected by an\nearlier :meth:`~django.db.models.query.QuerySet.filter` call.\n\nThat may sound a bit confusing, so hopefully an example will clarify. To\nselect all blogs that contain entries with both *\"Lennon\"* in the headline\nand that were published in 2008 (the same entry satisfying both conditions),\nwe would write::\n\n    Blog.objects.filter(entry__headline__contains='Lennon', entry__pub_date__year=2008)\n\nTo select all blogs that contain an entry with *\"Lennon\"* in the headline\n**as well as** an entry that was published in 2008, we would write::\n\n    Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008)\n\nSuppose there is only one blog that had both entries containing *\"Lennon\"* and\nentries from 2008, but that none of the entries from 2008 contained *\"Lennon\"*.\nThe first query would not return any blogs, but the second query would return\nthat one blog.\n\nIn the second example, the first filter restricts the queryset to all those\nblogs linked to entries with *\"Lennon\"* in the headline. The second filter\nrestricts the set of blogs *further* to those that are also linked to entries\nthat were published in 2008. The entries selected by the second filter may or\nmay not be the same as the entries in the first filter. We are filtering the\n``Blog`` items with each filter statement, not the ``Entry`` items.\n\n.. note::\n\n    The behavior of :meth:`~django.db.models.query.QuerySet.filter` for queries\n    that span multi-value relationships, as described above, is not implemented\n    equivalently for :meth:`~django.db.models.query.QuerySet.exclude`. Instead,\n    the conditions in a single :meth:`~django.db.models.query.QuerySet.exclude`\n    call will not necessarily refer to the same item.\n\n    For example, the following query would exclude blogs that contain *both*\n    entries with *\"Lennon\"* in the headline *and* entries published in 2008::\n\n        Blog.objects.exclude(\n            entry__headline__contains='Lennon',\n            entry__pub_date__year=2008,\n        )\n\n    However, unlike the behavior when using\n    :meth:`~django.db.models.query.QuerySet.filter`, this will not limit blogs\n    based on entries that satisfy both conditions. In order to do that, i.e.\n    to select all blogs that do not contain entries published with *\"Lennon\"*\n    that were published in 2008, you need to make two queries::\n\n        Blog.objects.exclude(\n            entry__in=Entry.objects.filter(\n                headline__contains='Lennon',\n                pub_date__year=2008,\n            ),\n        )\n\n.. _using-f-expressions-in-filters:\n\nFilters can reference fields on the model\n-----------------------------------------\n\nIn the examples given so far, we have constructed filters that compare\nthe value of a model field with a constant. But what if you want to compare\nthe value of a model field with another field on the same model?\n\nDjango provides :class:`F expressions <django.db.models.F>` to allow such\ncomparisons. Instances of ``F()`` act as a reference to a model field within a\nquery. These references can then be used in query filters to compare the values\nof two different fields on the same model instance.\n\nFor example, to find a list of all blog entries that have had more comments\nthan pingbacks, we construct an ``F()`` object to reference the pingback count,\nand use that ``F()`` object in the query::\n\n    >>> from django.db.models import F\n    >>> Entry.objects.filter(number_of_comments__gt=F('number_of_pingbacks'))\n\nDjango supports the use of addition, subtraction, multiplication,\ndivision, modulo, and power arithmetic with ``F()`` objects, both with constants\nand with other ``F()`` objects. To find all the blog entries with more than\n*twice* as many comments as pingbacks, we modify the query::\n\n    >>> Entry.objects.filter(number_of_comments__gt=F('number_of_pingbacks') * 2)\n\nTo find all the entries where the rating of the entry is less than the\nsum of the pingback count and comment count, we would issue the\nquery::\n\n    >>> Entry.objects.filter(rating__lt=F('number_of_comments') + F('number_of_pingbacks'))\n\nYou can also use the double underscore notation to span relationships in\nan ``F()`` object. An ``F()`` object with a double underscore will introduce\nany joins needed to access the related object. For example, to retrieve all\nthe entries where the author's name is the same as the blog name, we could\nissue the query::\n\n    >>> Entry.objects.filter(authors__name=F('blog__name'))\n\nFor date and date/time fields, you can add or subtract a\n:class:`~datetime.timedelta` object. The following would return all entries\nthat were modified more than 3 days after they were published::\n\n    >>> from datetime import timedelta\n    >>> Entry.objects.filter(mod_date__gt=F('pub_date') + timedelta(days=3))\n\nThe ``F()`` objects support bitwise operations by ``.bitand()``, ``.bitor()``,\n``.bitxor()``, ``.bitrightshift()``, and ``.bitleftshift()``. For example::\n\n    >>> F('somefield').bitand(16)\n\n.. admonition:: Oracle\n\n    Oracle doesn't support bitwise XOR operation.\n\n.. versionchanged:: 3.1\n\n    Support for ``.bitxor()`` was added.\n\nThe ``pk`` lookup shortcut\n--------------------------\n\nFor convenience, Django provides a ``pk`` lookup shortcut, which stands for\n\"primary key\".\n\nIn the example ``Blog`` model, the primary key is the ``id`` field, so these\nthree statements are equivalent::\n\n    >>> Blog.objects.get(id__exact=14) # Explicit form\n    >>> Blog.objects.get(id=14) # __exact is implied\n    >>> Blog.objects.get(pk=14) # pk implies id__exact\n\nThe use of ``pk`` isn't limited to ``__exact`` queries -- any query term\ncan be combined with ``pk`` to perform a query on the primary key of a model::\n\n    # Get blogs entries with id 1, 4 and 7\n    >>> Blog.objects.filter(pk__in=[1,4,7])\n\n    # Get all blog entries with id > 14\n    >>> Blog.objects.filter(pk__gt=14)\n\n``pk`` lookups also work across joins. For example, these three statements are\nequivalent::\n\n    >>> Entry.objects.filter(blog__id__exact=3) # Explicit form\n    >>> Entry.objects.filter(blog__id=3)        # __exact is implied\n    >>> Entry.objects.filter(blog__pk=3)        # __pk implies __id__exact\n\nEscaping percent signs and underscores in ``LIKE`` statements\n-------------------------------------------------------------\n\nThe field lookups that equate to ``LIKE`` SQL statements (``iexact``,\n``contains``, ``icontains``, ``startswith``, ``istartswith``, ``endswith``\nand ``iendswith``) will automatically escape the two special characters used in\n``LIKE`` statements -- the percent sign and the underscore. (In a ``LIKE``\nstatement, the percent sign signifies a multiple-character wildcard and the\nunderscore signifies a single-character wildcard.)\n\nThis means things should work intuitively, so the abstraction doesn't leak.\nFor example, to retrieve all the entries that contain a percent sign, use the\npercent sign as any other character::\n\n    >>> Entry.objects.filter(headline__contains='%')\n\nDjango takes care of the quoting for you; the resulting SQL will look something\nlike this:\n\n.. code-block:: sql\n\n    SELECT ... WHERE headline LIKE '%\\%%';\n\nSame goes for underscores. Both percentage signs and underscores are handled\nfor you transparently.\n\n.. _caching-and-querysets:\n\nCaching and ``QuerySet``\\s\n--------------------------\n\nEach :class:`~django.db.models.query.QuerySet` contains a cache to minimize\ndatabase access. Understanding how it works will allow you to write the most\nefficient code.\n\nIn a newly created :class:`~django.db.models.query.QuerySet`, the cache is\nempty. The first time a :class:`~django.db.models.query.QuerySet` is evaluated\n-- and, hence, a database query happens -- Django saves the query results in\nthe :class:`~django.db.models.query.QuerySet`’s cache and returns the results\nthat have been explicitly requested (e.g., the next element, if the\n:class:`~django.db.models.query.QuerySet` is being iterated over). Subsequent\nevaluations of the :class:`~django.db.models.query.QuerySet` reuse the cached\nresults.\n\nKeep this caching behavior in mind, because it may bite you if you don't use\nyour :class:`~django.db.models.query.QuerySet`\\s correctly. For example, the\nfollowing will create two :class:`~django.db.models.query.QuerySet`\\s, evaluate\nthem, and throw them away::\n\n    >>> print([e.headline for e in Entry.objects.all()])\n    >>> print([e.pub_date for e in Entry.objects.all()])\n\nThat means the same database query will be executed twice, effectively doubling\nyour database load. Also, there's a possibility the two lists may not include\nthe same database records, because an ``Entry`` may have been added or deleted\nin the split second between the two requests.\n\nTo avoid this problem, save the :class:`~django.db.models.query.QuerySet` and\nreuse it::\n\n    >>> queryset = Entry.objects.all()\n    >>> print([p.headline for p in queryset]) # Evaluate the query set.\n    >>> print([p.pub_date for p in queryset]) # Re-use the cache from the evaluation.\n\nWhen ``QuerySet``\\s are not cached\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nQuerysets do not always cache their results.  When evaluating only *part* of\nthe queryset, the cache is checked, but if it is not populated then the items\nreturned by the subsequent query are not cached. Specifically, this means that\n:ref:`limiting the queryset <limiting-querysets>` using an array slice or an\nindex will not populate the cache.\n\nFor example, repeatedly getting a certain index in a queryset object will query\nthe database each time::\n\n    >>> queryset = Entry.objects.all()\n    >>> print(queryset[5]) # Queries the database\n    >>> print(queryset[5]) # Queries the database again\n\nHowever, if the entire queryset has already been evaluated, the cache will be\nchecked instead::\n\n    >>> queryset = Entry.objects.all()\n    >>> [entry for entry in queryset] # Queries the database\n    >>> print(queryset[5]) # Uses cache\n    >>> print(queryset[5]) # Uses cache\n\nHere are some examples of other actions that will result in the entire queryset\nbeing evaluated and therefore populate the cache::\n\n    >>> [entry for entry in queryset]\n    >>> bool(queryset)\n    >>> entry in queryset\n    >>> list(queryset)\n\n.. note::\n\n    Simply printing the queryset will not populate the cache. This is because\n    the call to ``__repr__()`` only returns a slice of the entire queryset.\n\n.. _querying-jsonfield:\n\nQuerying ``JSONField``\n======================\n\nLookups implementation is different in :class:`~django.db.models.JSONField`,\nmainly due to the existence of key transformations. To demonstrate, we will use\nthe following example model::\n\n    from django.db import models\n\n    class Dog(models.Model):\n        name = models.CharField(max_length=200)\n        data = models.JSONField(null=True)\n\n        def __str__(self):\n            return self.name\n\nStoring and querying for ``None``\n---------------------------------\n\nAs with other fields, storing ``None`` as the field's value will store it as\nSQL ``NULL``. While not recommended, it is possible to store JSON scalar\n``null`` instead of SQL ``NULL`` by using :class:`Value('null')\n<django.db.models.Value>`.\n\nWhichever of the values is stored, when retrieved from the database, the Python\nrepresentation of the JSON scalar ``null`` is the same as SQL ``NULL``, i.e.\n``None``. Therefore, it can be hard to distinguish between them.\n\nThis only applies to ``None`` as the top-level value of the field. If ``None``\nis inside a :py:class:`list` or :py:class:`dict`, it will always be interpreted\nas JSON ``null``.\n\nWhen querying, ``None`` value will always be interpreted as JSON ``null``. To\nquery for SQL ``NULL``, use :lookup:`isnull`::\n\n    >>> Dog.objects.create(name='Max', data=None)  # SQL NULL.\n    <Dog: Max>\n    >>> Dog.objects.create(name='Archie', data=Value('null'))  # JSON null.\n    <Dog: Archie>\n    >>> Dog.objects.filter(data=None)\n    <QuerySet [<Dog: Archie>]>\n    >>> Dog.objects.filter(data=Value('null'))\n    <QuerySet [<Dog: Archie>]>\n    >>> Dog.objects.filter(data__isnull=True)\n    <QuerySet [<Dog: Max>]>\n    >>> Dog.objects.filter(data__isnull=False)\n    <QuerySet [<Dog: Archie>]>\n\nUnless you are sure you wish to work with SQL ``NULL`` values, consider setting\n``null=False`` and providing a suitable default for empty values, such as\n``default=dict``.\n\n.. note::\n\n    Storing JSON scalar ``null`` does not violate :attr:`null=False\n    <django.db.models.Field.null>`.\n\n.. fieldlookup:: jsonfield.key\n\nKey, index, and path transforms\n-------------------------------\n\nTo query based on a given dictionary key, use that key as the lookup name::\n\n    >>> Dog.objects.create(name='Rufus', data={\n    ...     'breed': 'labrador',\n    ...     'owner': {\n    ...         'name': 'Bob',\n    ...         'other_pets': [{\n    ...             'name': 'Fishy',\n    ...         }],\n    ...     },\n    ... })\n    <Dog: Rufus>\n    >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': None})\n    <Dog: Meg>\n    >>> Dog.objects.filter(data__breed='collie')\n    <QuerySet [<Dog: Meg>]>\n\nMultiple keys can be chained together to form a path lookup::\n\n    >>> Dog.objects.filter(data__owner__name='Bob')\n    <QuerySet [<Dog: Rufus>]>\n\nIf the key is an integer, it will be interpreted as an index transform in an\narray::\n\n    >>> Dog.objects.filter(data__owner__other_pets__0__name='Fishy')\n    <QuerySet [<Dog: Rufus>]>\n\nIf the key you wish to query by clashes with the name of another lookup, use\nthe :lookup:`contains <jsonfield.contains>` lookup instead.\n\nTo query for missing keys, use the ``isnull`` lookup::\n\n    >>> Dog.objects.create(name='Shep', data={'breed': 'collie'})\n    <Dog: Shep>\n    >>> Dog.objects.filter(data__owner__isnull=True)\n    <QuerySet [<Dog: Shep>]>\n\n.. note::\n\n    The lookup examples given above implicitly use the :lookup:`exact` lookup.\n    Key, index, and path transforms can also be chained with:\n    :lookup:`contains`, :lookup:`icontains`, :lookup:`endswith`,\n    :lookup:`iendswith`, :lookup:`iexact`, :lookup:`regex`, :lookup:`iregex`,\n    :lookup:`startswith`, :lookup:`istartswith`, :lookup:`lt`, :lookup:`lte`,\n    :lookup:`gt`, and :lookup:`gte` lookups.\n\n.. warning::\n\n    Since any string could be a key in a JSON object, any lookup other than\n    those listed below will be interpreted as a key lookup. No errors are\n    raised. Be extra careful for typing mistakes, and always check your queries\n    work as you intend.\n\n.. admonition:: MariaDB and Oracle users\n\n    Using :meth:`~django.db.models.query.QuerySet.order_by` on key, index, or\n    path transforms will sort the objects using the string representation of\n    the values. This is because MariaDB and Oracle Database do not provide a\n    function that converts JSON values into their equivalent SQL values.\n\n.. admonition:: Oracle users\n\n    On Oracle Database, using ``None`` as the lookup value in an\n    :meth:`~django.db.models.query.QuerySet.exclude` query will return objects\n    that do not have ``null`` as the value at the given path, including objects\n    that do not have the path. On other database backends, the query will\n    return objects that have the path and the value is not ``null``.\n\n.. admonition:: PostgreSQL users\n\n    On PostgreSQL, if only one key or index is used, the SQL operator ``->`` is\n    used. If multiple operators are used then the ``#>`` operator is used.\n\nContainment and key operations\n------------------------------\n\n.. fieldlookup:: jsonfield.contains\n\n``contains``\n~~~~~~~~~~~~\n\nThe :lookup:`contains` lookup is overridden on ``JSONField``. The returned\nobjects are those where the given ``dict`` of key-value pairs are all\ncontained in the top-level of the field. For example::\n\n    >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador', 'owner': 'Bob'})\n    <Dog: Rufus>\n    >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})\n    <Dog: Meg>\n    >>> Dog.objects.create(name='Fred', data={})\n    <Dog: Fred>\n    >>> Dog.objects.filter(data__contains={'owner': 'Bob'})\n    <QuerySet [<Dog: Rufus>, <Dog: Meg>]>\n    >>> Dog.objects.filter(data__contains={'breed': 'collie'})\n    <QuerySet [<Dog: Meg>]>\n\n.. fieldlookup:: jsonfield.contained_by\n\n``contained_by``\n~~~~~~~~~~~~~~~~\n\nThis is the inverse of the :lookup:`contains <jsonfield.contains>` lookup - the\nobjects returned will be those where the key-value pairs on the object are a\nsubset of those in the value passed. For example::\n\n    >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador', 'owner': 'Bob'})\n    <Dog: Rufus>\n    >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})\n    <Dog: Meg>\n    >>> Dog.objects.create(name='Fred', data={})\n    <Dog: Fred>\n    >>> Dog.objects.filter(data__contained_by={'breed': 'collie', 'owner': 'Bob'})\n    <QuerySet [<Dog: Meg>, <Dog: Fred>]>\n    >>> Dog.objects.filter(data__contained_by={'breed': 'collie'})\n    <QuerySet [<Dog: Fred>]>\n\n.. admonition:: Oracle\n\n    ``contained_by`` is not supported on Oracle.\n\n.. fieldlookup:: jsonfield.has_key\n\n``has_key``\n~~~~~~~~~~~\n\nReturns objects where the given key is in the top-level of the data. For\nexample::\n\n    >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})\n    <Dog: Rufus>\n    >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})\n    <Dog: Meg>\n    >>> Dog.objects.filter(data__has_key='owner')\n    <QuerySet [<Dog: Meg>]>\n\n.. fieldlookup:: jsonfield.has_any_keys\n\n``has_keys``\n~~~~~~~~~~~~\n\nReturns objects where all of the given keys are in the top-level of the data.\nFor example::\n\n    >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})\n    <Dog: Rufus>\n    >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})\n    <Dog: Meg>\n    >>> Dog.objects.filter(data__has_keys=['breed', 'owner'])\n    <QuerySet [<Dog: Meg>]>\n\n.. fieldlookup:: jsonfield.has_keys\n\n``has_any_keys``\n~~~~~~~~~~~~~~~~\n\nReturns objects where any of the given keys are in the top-level of the data.\nFor example::\n\n    >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})\n    <Dog: Rufus>\n    >>> Dog.objects.create(name='Meg', data={'owner': 'Bob'})\n    <Dog: Meg>\n    >>> Dog.objects.filter(data__has_any_keys=['owner', 'breed'])\n    <QuerySet [<Dog: Rufus>, <Dog: Meg>]>\n\n.. _complex-lookups-with-q:\n\nComplex lookups with ``Q`` objects\n==================================\n\nKeyword argument queries -- in :meth:`~django.db.models.query.QuerySet.filter`,\netc. -- are \"AND\"ed together. If you need to execute more complex queries (for\nexample, queries with ``OR`` statements), you can use :class:`Q objects <django.db.models.Q>`.\n\nA :class:`Q object <django.db.models.Q>` (``django.db.models.Q``) is an object\nused to encapsulate a collection of keyword arguments. These keyword arguments\nare specified as in \"Field lookups\" above.\n\nFor example, this ``Q`` object encapsulates a single ``LIKE`` query::\n\n    from django.db.models import Q\n    Q(question__startswith='What')\n\n``Q`` objects can be combined using the ``&`` and ``|`` operators. When an\noperator is used on two ``Q`` objects, it yields a new ``Q`` object.\n\nFor example, this statement yields a single ``Q`` object that represents the\n\"OR\" of two ``\"question__startswith\"`` queries::\n\n    Q(question__startswith='Who') | Q(question__startswith='What')\n\nThis is equivalent to the following SQL ``WHERE`` clause::\n\n    WHERE question LIKE 'Who%' OR question LIKE 'What%'\n\nYou can compose statements of arbitrary complexity by combining ``Q`` objects\nwith the ``&`` and ``|`` operators and use parenthetical grouping. Also, ``Q``\nobjects can be negated using the ``~`` operator, allowing for combined lookups\nthat combine both a normal query and a negated (``NOT``) query::\n\n    Q(question__startswith='Who') | ~Q(pub_date__year=2005)\n\nEach lookup function that takes keyword-arguments\n(e.g. :meth:`~django.db.models.query.QuerySet.filter`,\n:meth:`~django.db.models.query.QuerySet.exclude`,\n:meth:`~django.db.models.query.QuerySet.get`) can also be passed one or more\n``Q`` objects as positional (not-named) arguments. If you provide multiple\n``Q`` object arguments to a lookup function, the arguments will be \"AND\"ed\ntogether. For example::\n\n    Poll.objects.get(\n        Q(question__startswith='Who'),\n        Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))\n    )\n\n... roughly translates into the SQL:\n\n.. code-block:: sql\n\n    SELECT * from polls WHERE question LIKE 'Who%'\n        AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')\n\nLookup functions can mix the use of ``Q`` objects and keyword arguments. All\narguments provided to a lookup function (be they keyword arguments or ``Q``\nobjects) are \"AND\"ed together. However, if a ``Q`` object is provided, it must\nprecede the definition of any keyword arguments. For example::\n\n    Poll.objects.get(\n        Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),\n        question__startswith='Who',\n    )\n\n... would be a valid query, equivalent to the previous example; but::\n\n    # INVALID QUERY\n    Poll.objects.get(\n        question__startswith='Who',\n        Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))\n    )\n\n... would not be valid.\n\n.. seealso::\n\n    The :source:`OR lookups examples <tests/or_lookups/tests.py>` in Django's\n    unit tests show some possible uses of ``Q``.\n\nComparing objects\n=================\n\nTo compare two model instances, use the standard Python comparison operator,\nthe double equals sign: ``==``. Behind the scenes, that compares the primary\nkey values of two models.\n\nUsing the ``Entry`` example above, the following two statements are equivalent::\n\n    >>> some_entry == other_entry\n    >>> some_entry.id == other_entry.id\n\nIf a model's primary key isn't called ``id``, no problem. Comparisons will\nalways use the primary key, whatever it's called. For example, if a model's\nprimary key field is called ``name``, these two statements are equivalent::\n\n    >>> some_obj == other_obj\n    >>> some_obj.name == other_obj.name\n\n.. _topics-db-queries-delete:\n\nDeleting objects\n================\n\nThe delete method, conveniently, is named\n:meth:`~django.db.models.Model.delete`. This method immediately deletes the\nobject and returns the number of objects deleted and a dictionary with\nthe number of deletions per object type. Example::\n\n    >>> e.delete()\n    (1, {'weblog.Entry': 1})\n\nYou can also delete objects in bulk. Every\n:class:`~django.db.models.query.QuerySet` has a\n:meth:`~django.db.models.query.QuerySet.delete` method, which deletes all\nmembers of that :class:`~django.db.models.query.QuerySet`.\n\nFor example, this deletes all ``Entry`` objects with a ``pub_date`` year of\n2005::\n\n    >>> Entry.objects.filter(pub_date__year=2005).delete()\n    (5, {'webapp.Entry': 5})\n\nKeep in mind that this will, whenever possible, be executed purely in SQL, and\nso the ``delete()`` methods of individual object instances will not necessarily\nbe called during the process. If you've provided a custom ``delete()`` method\non a model class and want to ensure that it is called, you will need to\n\"manually\" delete instances of that model (e.g., by iterating over a\n:class:`~django.db.models.query.QuerySet` and calling ``delete()`` on each\nobject individually) rather than using the bulk\n:meth:`~django.db.models.query.QuerySet.delete` method of a\n:class:`~django.db.models.query.QuerySet`.\n\nWhen Django deletes an object, by default it emulates the behavior of the SQL\nconstraint ``ON DELETE CASCADE`` -- in other words, any objects which had\nforeign keys pointing at the object to be deleted will be deleted along with\nit. For example::\n\n    b = Blog.objects.get(pk=1)\n    # This will delete the Blog and all of its Entry objects.\n    b.delete()\n\nThis cascade behavior is customizable via the\n:attr:`~django.db.models.ForeignKey.on_delete` argument to the\n:class:`~django.db.models.ForeignKey`.\n\nNote that :meth:`~django.db.models.query.QuerySet.delete` is the only\n:class:`~django.db.models.query.QuerySet` method that is not exposed on a\n:class:`~django.db.models.Manager` itself. This is a safety mechanism to\nprevent you from accidentally requesting ``Entry.objects.delete()``, and\ndeleting *all* the entries. If you *do* want to delete all the objects, then\nyou have to explicitly request a complete query set::\n\n    Entry.objects.all().delete()\n\n.. _topics-db-queries-copy:\n\nCopying model instances\n=======================\n\nAlthough there is no built-in method for copying model instances, it is\npossible to easily create new instance with all fields' values copied. In the\nsimplest case, you can set ``pk`` to ``None``. Using our blog example::\n\n    blog = Blog(name='My blog', tagline='Blogging is easy')\n    blog.save() # blog.pk == 1\n\n    blog.pk = None\n    blog.save() # blog.pk == 2\n\nThings get more complicated if you use inheritance. Consider a subclass of\n``Blog``::\n\n    class ThemeBlog(Blog):\n        theme = models.CharField(max_length=200)\n\n    django_blog = ThemeBlog(name='Django', tagline='Django is easy', theme='python')\n    django_blog.save() # django_blog.pk == 3\n\nDue to how inheritance works, you have to set both ``pk`` and ``id`` to None::\n\n    django_blog.pk = None\n    django_blog.id = None\n    django_blog.save() # django_blog.pk == 4\n\nThis process doesn't copy relations that aren't part of the model's database\ntable. For example, ``Entry`` has a ``ManyToManyField`` to ``Author``. After\nduplicating an entry, you must set the many-to-many relations for the new\nentry::\n\n    entry = Entry.objects.all()[0] # some previous entry\n    old_authors = entry.authors.all()\n    entry.pk = None\n    entry.save()\n    entry.authors.set(old_authors)\n\nFor a ``OneToOneField``, you must duplicate the related object and assign it\nto the new object's field to avoid violating the one-to-one unique constraint.\nFor example, assuming ``entry`` is already duplicated as above::\n\n    detail = EntryDetail.objects.all()[0]\n    detail.pk = None\n    detail.entry = entry\n    detail.save()\n\n.. _topics-db-queries-update:\n\nUpdating multiple objects at once\n=================================\n\nSometimes you want to set a field to a particular value for all the objects in\na :class:`~django.db.models.query.QuerySet`. You can do this with the\n:meth:`~django.db.models.query.QuerySet.update` method. For example::\n\n    # Update all the headlines with pub_date in 2007.\n    Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same')\n\nYou can only set non-relation fields and :class:`~django.db.models.ForeignKey`\nfields using this method. To update a non-relation field, provide the new value\nas a constant. To update :class:`~django.db.models.ForeignKey` fields, set the\nnew value to be the new model instance you want to point to. For example::\n\n    >>> b = Blog.objects.get(pk=1)\n\n    # Change every Entry so that it belongs to this Blog.\n    >>> Entry.objects.all().update(blog=b)\n\nThe ``update()`` method is applied instantly and returns the number of rows\nmatched by the query (which may not be equal to the number of rows updated if\nsome rows already have the new value). The only restriction on the\n:class:`~django.db.models.query.QuerySet` being updated is that it can only\naccess one database table: the model's main table. You can filter based on\nrelated fields, but you can only update columns in the model's main\ntable. Example::\n\n    >>> b = Blog.objects.get(pk=1)\n\n    # Update all the headlines belonging to this Blog.\n    >>> Entry.objects.select_related().filter(blog=b).update(headline='Everything is the same')\n\nBe aware that the ``update()`` method is converted directly to an SQL\nstatement. It is a bulk operation for direct updates. It doesn't run any\n:meth:`~django.db.models.Model.save` methods on your models, or emit the\n``pre_save`` or ``post_save`` signals (which are a consequence of calling\n:meth:`~django.db.models.Model.save`), or honor the\n:attr:`~django.db.models.DateField.auto_now` field option.\nIf you want to save every item in a :class:`~django.db.models.query.QuerySet`\nand make sure that the :meth:`~django.db.models.Model.save` method is called on\neach instance, you don't need any special function to handle that. Loop over\nthem and call :meth:`~django.db.models.Model.save`::\n\n    for item in my_queryset:\n        item.save()\n\nCalls to update can also use :class:`F expressions <django.db.models.F>` to\nupdate one field based on the value of another field in the model. This is\nespecially useful for incrementing counters based upon their current value. For\nexample, to increment the pingback count for every entry in the blog::\n\n    >>> Entry.objects.all().update(number_of_pingbacks=F('number_of_pingbacks') + 1)\n\nHowever, unlike ``F()`` objects in filter and exclude clauses, you can't\nintroduce joins when you use ``F()`` objects in an update -- you can only\nreference fields local to the model being updated. If you attempt to introduce\na join with an ``F()`` object, a ``FieldError`` will be raised::\n\n    # This will raise a FieldError\n    >>> Entry.objects.update(headline=F('blog__name'))\n\n.. _topics-db-queries-related:\n\nRelated objects\n===============\n\nWhen you define a relationship in a model (i.e., a\n:class:`~django.db.models.ForeignKey`,\n:class:`~django.db.models.OneToOneField`, or\n:class:`~django.db.models.ManyToManyField`), instances of that model will have\na convenient API to access the related object(s).\n\nUsing the models at the top of this page, for example, an ``Entry`` object ``e``\ncan get its associated ``Blog`` object by accessing the ``blog`` attribute:\n``e.blog``.\n\n(Behind the scenes, this functionality is implemented by Python descriptors_.\nThis shouldn't really matter to you, but we point it out here for the curious.)\n\nDjango also creates API accessors for the \"other\" side of the relationship --\nthe link from the related model to the model that defines the relationship.\nFor example, a ``Blog`` object ``b`` has access to a list of all related\n``Entry`` objects via the ``entry_set`` attribute: ``b.entry_set.all()``.\n\nAll examples in this section use the sample ``Blog``, ``Author`` and ``Entry``\nmodels defined at the top of this page.\n\n.. _descriptors: https://docs.python.org/howto/descriptor.html\n\nOne-to-many relationships\n-------------------------\n\nForward\n~~~~~~~\n\nIf a model has a :class:`~django.db.models.ForeignKey`, instances of that model\nwill have access to the related (foreign) object via an attribute of the model.\n\nExample::\n\n    >>> e = Entry.objects.get(id=2)\n    >>> e.blog # Returns the related Blog object.\n\nYou can get and set via a foreign-key attribute. As you may expect, changes to\nthe foreign key aren't saved to the database until you call\n:meth:`~django.db.models.Model.save`. Example::\n\n    >>> e = Entry.objects.get(id=2)\n    >>> e.blog = some_blog\n    >>> e.save()\n\nIf a :class:`~django.db.models.ForeignKey` field has ``null=True`` set (i.e.,\nit allows ``NULL`` values), you can assign ``None`` to remove the relation.\nExample::\n\n    >>> e = Entry.objects.get(id=2)\n    >>> e.blog = None\n    >>> e.save() # \"UPDATE blog_entry SET blog_id = NULL ...;\"\n\nForward access to one-to-many relationships is cached the first time the\nrelated object is accessed. Subsequent accesses to the foreign key on the same\nobject instance are cached. Example::\n\n    >>> e = Entry.objects.get(id=2)\n    >>> print(e.blog)  # Hits the database to retrieve the associated Blog.\n    >>> print(e.blog)  # Doesn't hit the database; uses cached version.\n\nNote that the :meth:`~django.db.models.query.QuerySet.select_related`\n:class:`~django.db.models.query.QuerySet` method recursively prepopulates the\ncache of all one-to-many relationships ahead of time. Example::\n\n    >>> e = Entry.objects.select_related().get(id=2)\n    >>> print(e.blog)  # Doesn't hit the database; uses cached version.\n    >>> print(e.blog)  # Doesn't hit the database; uses cached version.\n\n.. _backwards-related-objects:\n\nFollowing relationships \"backward\"\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf a model has a :class:`~django.db.models.ForeignKey`, instances of the\nforeign-key model will have access to a :class:`~django.db.models.Manager` that\nreturns all instances of the first model. By default, this\n:class:`~django.db.models.Manager` is named ``FOO_set``, where ``FOO`` is the\nsource model name, lowercased. This :class:`~django.db.models.Manager` returns\n``QuerySets``, which can be filtered and manipulated as described in the\n\"Retrieving objects\" section above.\n\nExample::\n\n    >>> b = Blog.objects.get(id=1)\n    >>> b.entry_set.all() # Returns all Entry objects related to Blog.\n\n    # b.entry_set is a Manager that returns QuerySets.\n    >>> b.entry_set.filter(headline__contains='Lennon')\n    >>> b.entry_set.count()\n\nYou can override the ``FOO_set`` name by setting the\n:attr:`~django.db.models.ForeignKey.related_name` parameter in the\n:class:`~django.db.models.ForeignKey` definition. For example, if the ``Entry``\nmodel was altered to ``blog = ForeignKey(Blog, on_delete=models.CASCADE,\nrelated_name='entries')``, the above example code would look like this::\n\n    >>> b = Blog.objects.get(id=1)\n    >>> b.entries.all() # Returns all Entry objects related to Blog.\n\n    # b.entries is a Manager that returns QuerySets.\n    >>> b.entries.filter(headline__contains='Lennon')\n    >>> b.entries.count()\n\n.. _using-custom-reverse-manager:\n\nUsing a custom reverse manager\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nBy default the :class:`~django.db.models.fields.related.RelatedManager` used\nfor reverse relations is a subclass of the :ref:`default manager <manager-names>`\nfor that model. If you would like to specify a different manager for a given\nquery you can use the following syntax::\n\n    from django.db import models\n\n    class Entry(models.Model):\n        #...\n        objects = models.Manager()  # Default Manager\n        entries = EntryManager()    # Custom Manager\n\n    b = Blog.objects.get(id=1)\n    b.entry_set(manager='entries').all()\n\nIf ``EntryManager`` performed default filtering in its ``get_queryset()``\nmethod, that filtering would apply to the ``all()`` call.\n\nSpecifying a custom reverse manager also enables you to call its custom\nmethods::\n\n    b.entry_set(manager='entries').is_published()\n\nAdditional methods to handle related objects\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIn addition to the :class:`~django.db.models.query.QuerySet` methods defined in\n\"Retrieving objects\" above, the :class:`~django.db.models.ForeignKey`\n:class:`~django.db.models.Manager` has additional methods used to handle the\nset of related objects. A synopsis of each is below, and complete details can\nbe found in the :doc:`related objects reference </ref/models/relations>`.\n\n``add(obj1, obj2, ...)``\n    Adds the specified model objects to the related object set.\n\n``create(**kwargs)``\n    Creates a new object, saves it and puts it in the related object set.\n    Returns the newly created object.\n\n``remove(obj1, obj2, ...)``\n    Removes the specified model objects from the related object set.\n\n``clear()``\n    Removes all objects from the related object set.\n\n``set(objs)``\n    Replace the set of related objects.\n\nTo assign the members of a related set, use the ``set()`` method with an\niterable of object instances. For example, if ``e1`` and ``e2`` are ``Entry``\ninstances::\n\n    b = Blog.objects.get(id=1)\n    b.entry_set.set([e1, e2])\n\nIf the ``clear()`` method is available, any pre-existing objects will be\nremoved from the ``entry_set`` before all objects in the iterable (in this\ncase, a list) are added to the set. If the ``clear()`` method is *not*\navailable, all objects in the iterable will be added without removing any\nexisting elements.\n\nEach \"reverse\" operation described in this section has an immediate effect on\nthe database. Every addition, creation and deletion is immediately and\nautomatically saved to the database.\n\n.. _m2m-reverse-relationships:\n\nMany-to-many relationships\n--------------------------\n\nBoth ends of a many-to-many relationship get automatic API access to the other\nend. The API works similar to a \"backward\" one-to-many relationship, above.\n\nOne difference is in the attribute naming: The model that defines the\n:class:`~django.db.models.ManyToManyField` uses the attribute name of that\nfield itself, whereas the \"reverse\" model uses the lowercased model name of the\noriginal model, plus ``'_set'`` (just like reverse one-to-many relationships).\n\nAn example makes this easier to understand::\n\n    e = Entry.objects.get(id=3)\n    e.authors.all() # Returns all Author objects for this Entry.\n    e.authors.count()\n    e.authors.filter(name__contains='John')\n\n    a = Author.objects.get(id=5)\n    a.entry_set.all() # Returns all Entry objects for this Author.\n\nLike :class:`~django.db.models.ForeignKey`,\n:class:`~django.db.models.ManyToManyField` can specify\n:attr:`~django.db.models.ManyToManyField.related_name`. In the above example,\nif the :class:`~django.db.models.ManyToManyField` in ``Entry`` had specified\n``related_name='entries'``, then each ``Author`` instance would have an\n``entries`` attribute instead of ``entry_set``.\n\nAnother difference from one-to-many relationships is that in addition to model\ninstances,  the ``add()``, ``set()``, and ``remove()`` methods on many-to-many\nrelationships accept primary key values. For example, if ``e1`` and ``e2`` are\n``Entry`` instances, then these ``set()`` calls work identically::\n\n    a = Author.objects.get(id=5)\n    a.entry_set.set([e1, e2])\n    a.entry_set.set([e1.pk, e2.pk])\n\nOne-to-one relationships\n------------------------\n\nOne-to-one relationships are very similar to many-to-one relationships. If you\ndefine a :class:`~django.db.models.OneToOneField` on your model, instances of\nthat model will have access to the related object via an attribute of the\nmodel.\n\nFor example::\n\n    class EntryDetail(models.Model):\n        entry = models.OneToOneField(Entry, on_delete=models.CASCADE)\n        details = models.TextField()\n\n    ed = EntryDetail.objects.get(id=2)\n    ed.entry # Returns the related Entry object.\n\nThe difference comes in \"reverse\" queries. The related model in a one-to-one\nrelationship also has access to a :class:`~django.db.models.Manager` object, but\nthat :class:`~django.db.models.Manager` represents a single object, rather than\na collection of objects::\n\n    e = Entry.objects.get(id=2)\n    e.entrydetail # returns the related EntryDetail object\n\nIf no object has been assigned to this relationship, Django will raise\na ``DoesNotExist`` exception.\n\nInstances can be assigned to the reverse relationship in the same way as\nyou would assign the forward relationship::\n\n    e.entrydetail = ed\n\nHow are the backward relationships possible?\n--------------------------------------------\n\nOther object-relational mappers require you to define relationships on both\nsides. The Django developers believe this is a violation of the DRY (Don't\nRepeat Yourself) principle, so Django only requires you to define the\nrelationship on one end.\n\nBut how is this possible, given that a model class doesn't know which other\nmodel classes are related to it until those other model classes are loaded?\n\nThe answer lies in the :data:`app registry <django.apps.apps>`. When Django\nstarts, it imports each application listed in :setting:`INSTALLED_APPS`, and\nthen the ``models`` module inside each application. Whenever a new model class\nis created, Django adds backward-relationships to any related models. If the\nrelated models haven't been imported yet, Django keeps tracks of the\nrelationships and adds them when the related models eventually are imported.\n\nFor this reason, it's particularly important that all the models you're using\nbe defined in applications listed in :setting:`INSTALLED_APPS`. Otherwise,\nbackwards relations may not work properly.\n\nQueries over related objects\n----------------------------\n\nQueries involving related objects follow the same rules as queries involving\nnormal value fields. When specifying the value for a query to match, you may\nuse either an object instance itself, or the primary key value for the object.\n\nFor example, if you have a Blog object ``b`` with ``id=5``, the following\nthree queries would be identical::\n\n    Entry.objects.filter(blog=b) # Query using object instance\n    Entry.objects.filter(blog=b.id) # Query using id from instance\n    Entry.objects.filter(blog=5) # Query using id directly\n\nFalling back to raw SQL\n=======================\n\nIf you find yourself needing to write an SQL query that is too complex for\nDjango's database-mapper to handle, you can fall back on writing SQL by hand.\nDjango has a couple of options for writing raw SQL queries; see\n:doc:`/topics/db/sql`.\n\nFinally, it's important to note that the Django database layer is merely an\ninterface to your database. You can access your database via other tools,\nprogramming languages or database frameworks; there's nothing Django-specific\nabout your database.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":321,"nodeType":"TextFile","repoName":null,"name":"modelforms.txt","path":"docs/topics/forms","text":"==========================\nCreating forms from models\n==========================\n\n.. currentmodule:: django.forms\n\n``ModelForm``\n=============\n.. class:: ModelForm\n\nIf you're building a database-driven app, chances are you'll have forms that\nmap closely to Django models. For instance, you might have a ``BlogComment``\nmodel, and you want to create a form that lets people submit comments. In this\ncase, it would be redundant to define the field types in your form, because\nyou've already defined the fields in your model.\n\nFor this reason, Django provides a helper class that lets you create a ``Form``\nclass from a Django model.\n\nFor example::\n\n    >>> from django.forms import ModelForm\n    >>> from myapp.models import Article\n\n    # Create the form class.\n    >>> class ArticleForm(ModelForm):\n    ...     class Meta:\n    ...         model = Article\n    ...         fields = ['pub_date', 'headline', 'content', 'reporter']\n\n    # Creating a form to add an article.\n    >>> form = ArticleForm()\n\n    # Creating a form to change an existing article.\n    >>> article = Article.objects.get(pk=1)\n    >>> form = ArticleForm(instance=article)\n\nField types\n-----------\n\nThe generated ``Form`` class will have a form field for every model field\nspecified, in the order specified in the ``fields`` attribute.\n\nEach model field has a corresponding default form field. For example, a\n``CharField`` on a model is represented as a ``CharField`` on a form. A model\n``ManyToManyField`` is represented as a ``MultipleChoiceField``. Here is the\nfull list of conversions:\n\n.. currentmodule:: django.db.models\n\n=================================== ==================================================\nModel field                         Form field\n=================================== ==================================================\n:class:`AutoField`                  Not represented in the form\n\n:class:`BigAutoField`               Not represented in the form\n\n:class:`BigIntegerField`            :class:`~django.forms.IntegerField` with\n                                    ``min_value`` set to -9223372036854775808\n                                    and ``max_value`` set to 9223372036854775807.\n\n:class:`BinaryField`                :class:`~django.forms.CharField`, if\n                                    :attr:`~.Field.editable` is set to\n                                    ``True`` on the model field, otherwise not\n                                    represented in the form.\n\n:class:`BooleanField`               :class:`~django.forms.BooleanField`, or\n                                    :class:`~django.forms.NullBooleanField` if\n                                    ``null=True``.\n\n:class:`CharField`                  :class:`~django.forms.CharField` with\n                                    ``max_length`` set to the model field's\n                                    ``max_length`` and\n                                    :attr:`~django.forms.CharField.empty_value`\n                                    set to ``None`` if ``null=True``.\n\n:class:`DateField`                  :class:`~django.forms.DateField`\n\n:class:`DateTimeField`              :class:`~django.forms.DateTimeField`\n\n:class:`DecimalField`               :class:`~django.forms.DecimalField`\n\n:class:`DurationField`              :class:`~django.forms.DurationField`\n\n:class:`EmailField`                 :class:`~django.forms.EmailField`\n\n:class:`FileField`                  :class:`~django.forms.FileField`\n\n:class:`FilePathField`              :class:`~django.forms.FilePathField`\n\n:class:`FloatField`                 :class:`~django.forms.FloatField`\n\n:class:`ForeignKey`                 :class:`~django.forms.ModelChoiceField`\n                                    (see below)\n\n:class:`ImageField`                 :class:`~django.forms.ImageField`\n\n:class:`IntegerField`               :class:`~django.forms.IntegerField`\n\n``IPAddressField``                  ``IPAddressField``\n\n:class:`GenericIPAddressField`      :class:`~django.forms.GenericIPAddressField`\n\n:class:`ManyToManyField`            :class:`~django.forms.ModelMultipleChoiceField`\n                                    (see below)\n\n:class:`NullBooleanField`           :class:`~django.forms.NullBooleanField`\n\n:class:`PositiveBigIntegerField`    :class:`~django.forms.IntegerField`\n\n:class:`PositiveIntegerField`       :class:`~django.forms.IntegerField`\n\n:class:`PositiveSmallIntegerField`  :class:`~django.forms.IntegerField`\n\n:class:`SlugField`                  :class:`~django.forms.SlugField`\n\n:class:`SmallAutoField`             Not represented in the form\n\n:class:`SmallIntegerField`          :class:`~django.forms.IntegerField`\n\n:class:`TextField`                  :class:`~django.forms.CharField` with\n                                    ``widget=forms.Textarea``\n\n:class:`TimeField`                  :class:`~django.forms.TimeField`\n\n:class:`URLField`                   :class:`~django.forms.URLField`\n\n:class:`UUIDField`                  :class:`~django.forms.UUIDField`\n=================================== ==================================================\n\n.. currentmodule:: django.forms\n\nAs you might expect, the ``ForeignKey`` and ``ManyToManyField`` model field\ntypes are special cases:\n\n* ``ForeignKey`` is represented by ``django.forms.ModelChoiceField``,\n  which is a ``ChoiceField`` whose choices are a model ``QuerySet``.\n\n* ``ManyToManyField`` is represented by\n  ``django.forms.ModelMultipleChoiceField``, which is a\n  ``MultipleChoiceField`` whose choices are a model ``QuerySet``.\n\nIn addition, each generated form field has attributes set as follows:\n\n* If the model field has ``blank=True``, then ``required`` is set to\n  ``False`` on the form field. Otherwise, ``required=True``.\n\n* The form field's ``label`` is set to the ``verbose_name`` of the model\n  field, with the first character capitalized.\n\n* The form field's ``help_text`` is set to the ``help_text`` of the model\n  field.\n\n* If the model field has ``choices`` set, then the form field's ``widget``\n  will be set to ``Select``, with choices coming from the model field's\n  ``choices``. The choices will normally include the blank choice which is\n  selected by default. If the field is required, this forces the user to\n  make a selection. The blank choice will not be included if the model\n  field has ``blank=False`` and an explicit ``default`` value (the\n  ``default`` value will be initially selected instead).\n\nFinally, note that you can override the form field used for a given model\nfield. See `Overriding the default fields`_ below.\n\nA full example\n--------------\n\nConsider this set of models::\n\n    from django.db import models\n    from django.forms import ModelForm\n\n    TITLE_CHOICES = [\n        ('MR', 'Mr.'),\n        ('MRS', 'Mrs.'),\n        ('MS', 'Ms.'),\n    ]\n\n    class Author(models.Model):\n        name = models.CharField(max_length=100)\n        title = models.CharField(max_length=3, choices=TITLE_CHOICES)\n        birth_date = models.DateField(blank=True, null=True)\n\n        def __str__(self):\n            return self.name\n\n    class Book(models.Model):\n        name = models.CharField(max_length=100)\n        authors = models.ManyToManyField(Author)\n\n    class AuthorForm(ModelForm):\n        class Meta:\n            model = Author\n            fields = ['name', 'title', 'birth_date']\n\n    class BookForm(ModelForm):\n        class Meta:\n            model = Book\n            fields = ['name', 'authors']\n\n\nWith these models, the ``ModelForm`` subclasses above would be roughly\nequivalent to this (the only difference being the ``save()`` method, which\nwe'll discuss in a moment.)::\n\n    from django import forms\n\n    class AuthorForm(forms.Form):\n        name = forms.CharField(max_length=100)\n        title = forms.CharField(\n            max_length=3,\n            widget=forms.Select(choices=TITLE_CHOICES),\n        )\n        birth_date = forms.DateField(required=False)\n\n    class BookForm(forms.Form):\n        name = forms.CharField(max_length=100)\n        authors = forms.ModelMultipleChoiceField(queryset=Author.objects.all())\n\n.. _validation-on-modelform:\n\nValidation on a ``ModelForm``\n-----------------------------\n\nThere are two main steps involved in validating a ``ModelForm``:\n\n1. :doc:`Validating the form </ref/forms/validation>`\n2. :ref:`Validating the model instance <validating-objects>`\n\nJust like normal form validation, model form validation is triggered implicitly\nwhen calling :meth:`~django.forms.Form.is_valid()` or accessing the\n:attr:`~django.forms.Form.errors` attribute and explicitly when calling\n``full_clean()``, although you will typically not use the latter method in\npractice.\n\n``Model`` validation (:meth:`Model.full_clean()\n<django.db.models.Model.full_clean()>`) is triggered from within the form\nvalidation step, right after the form's ``clean()`` method is called.\n\n.. warning::\n\n    The cleaning process modifies the model instance passed to the\n    ``ModelForm`` constructor in various ways. For instance, any date fields on\n    the model are converted into actual date objects. Failed validation may\n    leave the underlying model instance in an inconsistent state and therefore\n    it's not recommended to reuse it.\n\n.. _overriding-modelform-clean-method:\n\nOverriding the clean() method\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nYou can override the ``clean()`` method on a model form to provide additional\nvalidation in the same way you can on a normal form.\n\nA model form instance attached to a model object will contain an ``instance``\nattribute that gives its methods access to that specific model instance.\n\n.. warning::\n\n    The ``ModelForm.clean()`` method sets a flag that makes the :ref:`model\n    validation <validating-objects>` step validate the uniqueness of model\n    fields that are marked as ``unique``, ``unique_together`` or\n    ``unique_for_date|month|year``.\n\n    If you would like to override the ``clean()`` method and maintain this\n    validation, you must call the parent class's ``clean()`` method.\n\nInteraction with model validation\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nAs part of the validation process, ``ModelForm`` will call the ``clean()``\nmethod of each field on your model that has a corresponding field on your form.\nIf you have excluded any model fields, validation will not be run on those\nfields. See the :doc:`form validation </ref/forms/validation>` documentation\nfor more on how field cleaning and validation work.\n\nThe model's ``clean()`` method will be called before any uniqueness checks are\nmade. See :ref:`Validating objects <validating-objects>` for more information\non the model's ``clean()`` hook.\n\n.. _considerations-regarding-model-errormessages:\n\nConsiderations regarding model's ``error_messages``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nError messages defined at the\n:attr:`form field <django.forms.Field.error_messages>` level or at the\n:ref:`form Meta <modelforms-overriding-default-fields>` level always take\nprecedence over the error messages defined at the\n:attr:`model field <django.db.models.Field.error_messages>` level.\n\nError messages  defined on :attr:`model fields\n<django.db.models.Field.error_messages>` are only used when the\n``ValidationError`` is raised during the :ref:`model validation\n<validating-objects>` step and no corresponding error messages are defined at\nthe form level.\n\nYou can override the error messages from ``NON_FIELD_ERRORS`` raised by model\nvalidation by adding the :data:`~django.core.exceptions.NON_FIELD_ERRORS` key\nto the ``error_messages`` dictionary of the ``ModelForm``’s inner ``Meta`` class::\n\n    from django.core.exceptions import NON_FIELD_ERRORS\n    from django.forms import ModelForm\n\n    class ArticleForm(ModelForm):\n        class Meta:\n            error_messages = {\n                NON_FIELD_ERRORS: {\n                    'unique_together': \"%(model_name)s's %(field_labels)s are not unique.\",\n                }\n            }\n\n.. _topics-modelform-save:\n\nThe ``save()`` method\n---------------------\n\nEvery ``ModelForm`` also has a ``save()`` method. This method creates and saves\na database object from the data bound to the form. A subclass of ``ModelForm``\ncan accept an existing model instance as the keyword argument ``instance``; if\nthis is supplied, ``save()`` will update that instance. If it's not supplied,\n``save()`` will create a new instance of the specified model::\n\n    >>> from myapp.models import Article\n    >>> from myapp.forms import ArticleForm\n\n    # Create a form instance from POST data.\n    >>> f = ArticleForm(request.POST)\n\n    # Save a new Article object from the form's data.\n    >>> new_article = f.save()\n\n    # Create a form to edit an existing Article, but use\n    # POST data to populate the form.\n    >>> a = Article.objects.get(pk=1)\n    >>> f = ArticleForm(request.POST, instance=a)\n    >>> f.save()\n\nNote that if the form :ref:`hasn't been validated\n<validation-on-modelform>`, calling ``save()`` will do so by checking\n``form.errors``. A ``ValueError`` will be raised if the data in the form\ndoesn't validate -- i.e., if ``form.errors`` evaluates to ``True``.\n\nIf an optional field doesn't appear in the form's data, the resulting model\ninstance uses the model field :attr:`~django.db.models.Field.default`, if\nthere is one, for that field. This behavior doesn't apply to fields that use\n:class:`~django.forms.CheckboxInput`,\n:class:`~django.forms.CheckboxSelectMultiple`, or\n:class:`~django.forms.SelectMultiple` (or any custom widget whose\n:meth:`~django.forms.Widget.value_omitted_from_data` method always returns\n``False``) since an unchecked checkbox and unselected ``<select multiple>``\ndon't appear in the data of an HTML form submission. Use a custom form field or\nwidget if you're designing an API and want the default fallback behavior for a\nfield that uses one of these widgets.\n\nThis ``save()`` method accepts an optional ``commit`` keyword argument, which\naccepts either ``True`` or ``False``. If you call ``save()`` with\n``commit=False``, then it will return an object that hasn't yet been saved to\nthe database. In this case, it's up to you to call ``save()`` on the resulting\nmodel instance. This is useful if you want to do custom processing on the\nobject before saving it, or if you want to use one of the specialized\n:ref:`model saving options <ref-models-force-insert>`. ``commit`` is ``True``\nby default.\n\nAnother side effect of using ``commit=False`` is seen when your model has\na many-to-many relation with another model. If your model has a many-to-many\nrelation and you specify ``commit=False`` when you save a form, Django cannot\nimmediately save the form data for the many-to-many relation. This is because\nit isn't possible to save many-to-many data for an instance until the instance\nexists in the database.\n\nTo work around this problem, every time you save a form using ``commit=False``,\nDjango adds a ``save_m2m()`` method to your ``ModelForm`` subclass. After\nyou've manually saved the instance produced by the form, you can invoke\n``save_m2m()`` to save the many-to-many form data. For example::\n\n    # Create a form instance with POST data.\n    >>> f = AuthorForm(request.POST)\n\n    # Create, but don't save the new author instance.\n    >>> new_author = f.save(commit=False)\n\n    # Modify the author in some way.\n    >>> new_author.some_field = 'some_value'\n\n    # Save the new instance.\n    >>> new_author.save()\n\n    # Now, save the many-to-many data for the form.\n    >>> f.save_m2m()\n\nCalling ``save_m2m()`` is only required if you use ``save(commit=False)``.\nWhen you use a ``save()`` on a form, all data -- including many-to-many data --\nis saved without the need for any additional method calls.  For example::\n\n    # Create a form instance with POST data.\n    >>> a = Author()\n    >>> f = AuthorForm(request.POST, instance=a)\n\n    # Create and save the new author instance. There's no need to do anything else.\n    >>> new_author = f.save()\n\nOther than the ``save()`` and ``save_m2m()`` methods, a ``ModelForm`` works\nexactly the same way as any other ``forms`` form. For example, the\n``is_valid()`` method is used to check for validity, the ``is_multipart()``\nmethod is used to determine whether a form requires multipart file upload (and\nhence whether ``request.FILES`` must be passed to the form), etc. See\n:ref:`binding-uploaded-files` for more information.\n\n.. _modelforms-selecting-fields:\n\nSelecting the fields to use\n---------------------------\n\nIt is strongly recommended that you explicitly set all fields that should be\nedited in the form using the ``fields`` attribute. Failure to do so can easily\nlead to security problems when a form unexpectedly allows a user to set certain\nfields, especially when new fields are added to a model. Depending on how the\nform is rendered, the problem may not even be visible on the web page.\n\nThe alternative approach would be to include all fields automatically, or\nblacklist only some. This fundamental approach is known to be much less secure\nand has led to serious exploits on major websites (e.g. `GitHub\n<https://github.com/blog/1068-public-key-security-vulnerability-and-mitigation>`_).\n\nThere are, however, two shortcuts available for cases where you can guarantee\nthese security concerns do not apply to you:\n\n1. Set the ``fields`` attribute to the special value ``'__all__'`` to indicate\n   that all fields in the model should be used. For example::\n\n       from django.forms import ModelForm\n\n       class AuthorForm(ModelForm):\n           class Meta:\n               model = Author\n               fields = '__all__'\n\n2. Set the ``exclude`` attribute of the ``ModelForm``’s inner ``Meta`` class to\n   a list of fields to be excluded from the form.\n\n   For example::\n\n       class PartialAuthorForm(ModelForm):\n           class Meta:\n               model = Author\n               exclude = ['title']\n\n   Since the ``Author`` model has the 3 fields ``name``, ``title`` and\n   ``birth_date``, this will result in the fields ``name`` and ``birth_date``\n   being present on the form.\n\nIf either of these are used, the order the fields appear in the form will be the\norder the fields are defined in the model, with ``ManyToManyField`` instances\nappearing last.\n\nIn addition, Django applies the following rule: if you set ``editable=False`` on\nthe model field, *any* form created from the model via ``ModelForm`` will not\ninclude that field.\n\n.. note::\n\n    Any fields not included in a form by the above logic\n    will not be set by the form's ``save()`` method. Also, if you\n    manually add the excluded fields back to the form, they will not\n    be initialized from the model instance.\n\n    Django will prevent any attempt to save an incomplete model, so if\n    the model does not allow the missing fields to be empty, and does\n    not provide a default value for the missing fields, any attempt to\n    ``save()`` a ``ModelForm`` with missing fields will fail.  To\n    avoid this failure, you must instantiate your model with initial\n    values for the missing, but required fields::\n\n        author = Author(title='Mr')\n        form = PartialAuthorForm(request.POST, instance=author)\n        form.save()\n\n    Alternatively, you can use ``save(commit=False)`` and manually set\n    any extra required fields::\n\n        form = PartialAuthorForm(request.POST)\n        author = form.save(commit=False)\n        author.title = 'Mr'\n        author.save()\n\n    See the `section on saving forms`_ for more details on using\n    ``save(commit=False)``.\n\n.. _section on saving forms: `The save() method`_\n\n.. _modelforms-overriding-default-fields:\n\nOverriding the default fields\n-----------------------------\n\nThe default field types, as described in the `Field types`_ table above, are\nsensible defaults. If you have a ``DateField`` in your model, chances are you'd\nwant that to be represented as a ``DateField`` in your form. But ``ModelForm``\ngives you the flexibility of changing the form field for a given model.\n\nTo specify a custom widget for a field, use the ``widgets`` attribute of the\ninner ``Meta`` class. This should be a dictionary mapping field names to widget\nclasses or instances.\n\nFor example, if you want the ``CharField`` for the ``name`` attribute of\n``Author`` to be represented by a ``<textarea>`` instead of its default\n``<input type=\"text\">``, you can override the field's widget::\n\n    from django.forms import ModelForm, Textarea\n    from myapp.models import Author\n\n    class AuthorForm(ModelForm):\n        class Meta:\n            model = Author\n            fields = ('name', 'title', 'birth_date')\n            widgets = {\n                'name': Textarea(attrs={'cols': 80, 'rows': 20}),\n            }\n\nThe ``widgets`` dictionary accepts either widget instances (e.g.,\n``Textarea(...)``) or classes (e.g., ``Textarea``). Note that the ``widgets``\ndictionary is ignored for a model field with a non-empty ``choices`` attribute.\nIn this case, you must override the form field to use a different widget.\n\nSimilarly, you can specify the ``labels``, ``help_texts`` and ``error_messages``\nattributes of the inner ``Meta`` class if you want to further customize a field.\n\nFor example if you wanted to customize the wording of all user facing strings for\nthe ``name`` field::\n\n    from django.utils.translation import gettext_lazy as _\n\n    class AuthorForm(ModelForm):\n        class Meta:\n            model = Author\n            fields = ('name', 'title', 'birth_date')\n            labels = {\n                'name': _('Writer'),\n            }\n            help_texts = {\n                'name': _('Some useful help text.'),\n            }\n            error_messages = {\n                'name': {\n                    'max_length': _(\"This writer's name is too long.\"),\n                },\n            }\n\nYou can also specify ``field_classes`` to customize the type of fields\ninstantiated by the form.\n\nFor example, if you wanted to use ``MySlugFormField`` for the ``slug``\nfield, you could do the following::\n\n    from django.forms import ModelForm\n    from myapp.models import Article\n\n    class ArticleForm(ModelForm):\n        class Meta:\n            model = Article\n            fields = ['pub_date', 'headline', 'content', 'reporter', 'slug']\n            field_classes = {\n                'slug': MySlugFormField,\n            }\n\n\nFinally, if you want complete control over of a field -- including its type,\nvalidators, required, etc. -- you can do this by declaratively specifying\nfields like you would in a regular ``Form``.\n\nIf you want to specify a field's validators, you can do so by defining\nthe field declaratively and setting its ``validators`` parameter::\n\n    from django.forms import CharField, ModelForm\n    from myapp.models import Article\n\n    class ArticleForm(ModelForm):\n        slug = CharField(validators=[validate_slug])\n\n        class Meta:\n            model = Article\n            fields = ['pub_date', 'headline', 'content', 'reporter', 'slug']\n\n.. note::\n\n    When you explicitly instantiate a form field like this, it is important to\n    understand how ``ModelForm`` and regular ``Form`` are related.\n\n    ``ModelForm`` is a regular ``Form`` which can automatically generate\n    certain fields. The fields that are automatically generated depend on\n    the content of the ``Meta`` class and on which fields have already been\n    defined declaratively. Basically, ``ModelForm`` will **only** generate fields\n    that are **missing** from the form, or in other words, fields that weren't\n    defined declaratively.\n\n    Fields defined declaratively are left as-is, therefore any customizations\n    made to ``Meta`` attributes such as ``widgets``, ``labels``, ``help_texts``,\n    or ``error_messages`` are ignored; these only apply to fields that are\n    generated automatically.\n\n    Similarly, fields defined declaratively do not draw their attributes like\n    ``max_length`` or ``required`` from the corresponding model. If you want to\n    maintain the behavior specified in the model, you must set the relevant\n    arguments explicitly when declaring the form field.\n\n    For example, if the ``Article`` model looks like this::\n\n        class Article(models.Model):\n            headline = models.CharField(\n                max_length=200,\n                null=True,\n                blank=True,\n                help_text='Use puns liberally',\n            )\n            content = models.TextField()\n\n    and you want to do some custom validation for ``headline``, while keeping\n    the ``blank`` and ``help_text`` values as specified, you might define\n    ``ArticleForm`` like this::\n\n        class ArticleForm(ModelForm):\n            headline = MyFormField(\n                max_length=200,\n                required=False,\n                help_text='Use puns liberally',\n            )\n\n            class Meta:\n                model = Article\n                fields = ['headline', 'content']\n\n    You must ensure that the type of the form field can be used to set the\n    contents of the corresponding model field. When they are not compatible,\n    you will get a ``ValueError`` as no implicit conversion takes place.\n\n    See the :doc:`form field documentation </ref/forms/fields>` for more information\n    on fields and their arguments.\n\n\nEnabling localization of fields\n-------------------------------\n\nBy default, the fields in a ``ModelForm`` will not localize their data. To\nenable localization for fields, you can use the ``localized_fields``\nattribute on the ``Meta`` class.\n\n    >>> from django.forms import ModelForm\n    >>> from myapp.models import Author\n    >>> class AuthorForm(ModelForm):\n    ...     class Meta:\n    ...         model = Author\n    ...         localized_fields = ('birth_date',)\n\nIf ``localized_fields`` is set to the special value ``'__all__'``, all fields\nwill be localized.\n\nForm inheritance\n----------------\n\nAs with basic forms, you can extend and reuse ``ModelForms`` by inheriting\nthem. This is useful if you need to declare extra fields or extra methods on a\nparent class for use in a number of forms derived from models. For example,\nusing the previous ``ArticleForm`` class::\n\n    >>> class EnhancedArticleForm(ArticleForm):\n    ...     def clean_pub_date(self):\n    ...         ...\n\nThis creates a form that behaves identically to ``ArticleForm``, except there's\nsome extra validation and cleaning for the ``pub_date`` field.\n\nYou can also subclass the parent's ``Meta`` inner class if you want to change\nthe ``Meta.fields`` or ``Meta.exclude`` lists::\n\n    >>> class RestrictedArticleForm(EnhancedArticleForm):\n    ...     class Meta(ArticleForm.Meta):\n    ...         exclude = ('body',)\n\nThis adds the extra method from the ``EnhancedArticleForm`` and modifies\nthe original ``ArticleForm.Meta`` to remove one field.\n\nThere are a couple of things to note, however.\n\n* Normal Python name resolution rules apply. If you have multiple base\n  classes that declare a ``Meta`` inner class, only the first one will be\n  used. This means the child's ``Meta``, if it exists, otherwise the\n  ``Meta`` of the first parent, etc.\n\n* It's possible to inherit from both ``Form`` and ``ModelForm`` simultaneously,\n  however, you must ensure that ``ModelForm`` appears first in the MRO. This is\n  because these classes rely on different metaclasses and a class can only have\n  one metaclass.\n\n* It's possible to declaratively remove a ``Field`` inherited from a parent class by\n  setting the name to be ``None`` on the subclass.\n\n  You can only use this technique to opt out from a field defined declaratively\n  by a parent class; it won't prevent the ``ModelForm`` metaclass from generating\n  a default field. To opt-out from default fields, see\n  :ref:`modelforms-selecting-fields`.\n\nProviding initial values\n------------------------\n\nAs with regular forms, it's possible to specify initial data for forms by\nspecifying an ``initial`` parameter when instantiating the form. Initial\nvalues provided this way will override both initial values from the form field\nand values from an attached model instance. For example::\n\n    >>> article = Article.objects.get(pk=1)\n    >>> article.headline\n    'My headline'\n    >>> form = ArticleForm(initial={'headline': 'Initial headline'}, instance=article)\n    >>> form['headline'].value()\n    'Initial headline'\n\n.. _modelforms-factory:\n\nModelForm factory function\n--------------------------\n\nYou can create forms from a given model using the standalone function\n:func:`~django.forms.models.modelform_factory`, instead of using a class\ndefinition. This may be more convenient if you do not have many customizations\nto make::\n\n    >>> from django.forms import modelform_factory\n    >>> from myapp.models import Book\n    >>> BookForm = modelform_factory(Book, fields=(\"author\", \"title\"))\n\nThis can also be used to make modifications to existing forms, for example by\nspecifying the widgets to be used for a given field::\n\n    >>> from django.forms import Textarea\n    >>> Form = modelform_factory(Book, form=BookForm,\n    ...                          widgets={\"title\": Textarea()})\n\nThe fields to include can be specified using the ``fields`` and ``exclude``\nkeyword arguments, or the corresponding attributes on the ``ModelForm`` inner\n``Meta`` class. Please see the ``ModelForm`` :ref:`modelforms-selecting-fields`\ndocumentation.\n\n... or enable localization for specific fields::\n\n    >>> Form = modelform_factory(Author, form=AuthorForm, localized_fields=(\"birth_date\",))\n\n.. _model-formsets:\n\nModel formsets\n==============\n\n.. class:: models.BaseModelFormSet\n\nLike :doc:`regular formsets </topics/forms/formsets>`, Django provides a couple\nof enhanced formset classes to make working with Django models more\nconvenient. Let's reuse the ``Author`` model from above::\n\n    >>> from django.forms import modelformset_factory\n    >>> from myapp.models import Author\n    >>> AuthorFormSet = modelformset_factory(Author, fields=('name', 'title'))\n\nUsing ``fields`` restricts the formset to use only the given fields.\nAlternatively, you can take an \"opt-out\" approach, specifying which fields to\nexclude::\n\n    >>> AuthorFormSet = modelformset_factory(Author, exclude=('birth_date',))\n\nThis will create a formset that is capable of working with the data associated\nwith the ``Author`` model. It works just like a regular formset::\n\n    >>> formset = AuthorFormSet()\n    >>> print(formset)\n    <input type=\"hidden\" name=\"form-TOTAL_FORMS\" value=\"1\" id=\"id_form-TOTAL_FORMS\"><input type=\"hidden\" name=\"form-INITIAL_FORMS\" value=\"0\" id=\"id_form-INITIAL_FORMS\"><input type=\"hidden\" name=\"form-MAX_NUM_FORMS\" id=\"id_form-MAX_NUM_FORMS\">\n    <tr><th><label for=\"id_form-0-name\">Name:</label></th><td><input id=\"id_form-0-name\" type=\"text\" name=\"form-0-name\" maxlength=\"100\"></td></tr>\n    <tr><th><label for=\"id_form-0-title\">Title:</label></th><td><select name=\"form-0-title\" id=\"id_form-0-title\">\n    <option value=\"\" selected>---------</option>\n    <option value=\"MR\">Mr.</option>\n    <option value=\"MRS\">Mrs.</option>\n    <option value=\"MS\">Ms.</option>\n    </select><input type=\"hidden\" name=\"form-0-id\" id=\"id_form-0-id\"></td></tr>\n\n.. note::\n\n    :func:`~django.forms.models.modelformset_factory` uses\n    :func:`~django.forms.formsets.formset_factory` to generate formsets. This\n    means that a model formset is an extension of a basic formset that knows\n    how to interact with a particular model.\n\n.. note::\n\n    When using :ref:`multi-table inheritance <multi-table-inheritance>`, forms\n    generated by a formset factory will contain a parent link field (by default\n    ``<parent_model_name>_ptr``) instead of an ``id`` field.\n\nChanging the queryset\n---------------------\n\nBy default, when you create a formset from a model, the formset will use a\nqueryset that includes all objects in the model (e.g.,\n``Author.objects.all()``). You can override this behavior by using the\n``queryset`` argument::\n\n    >>> formset = AuthorFormSet(queryset=Author.objects.filter(name__startswith='O'))\n\nAlternatively, you can create a subclass that sets ``self.queryset`` in\n``__init__``::\n\n    from django.forms import BaseModelFormSet\n    from myapp.models import Author\n\n    class BaseAuthorFormSet(BaseModelFormSet):\n        def __init__(self, *args, **kwargs):\n            super().__init__(*args, **kwargs)\n            self.queryset = Author.objects.filter(name__startswith='O')\n\nThen, pass your ``BaseAuthorFormSet`` class to the factory function::\n\n    >>> AuthorFormSet = modelformset_factory(\n    ...     Author, fields=('name', 'title'), formset=BaseAuthorFormSet)\n\nIf you want to return a formset that doesn't include *any* pre-existing\ninstances of the model, you can specify an empty QuerySet::\n\n   >>> AuthorFormSet(queryset=Author.objects.none())\n\nChanging the form\n-----------------\n\nBy default, when you use ``modelformset_factory``, a model form will\nbe created using :func:`~django.forms.models.modelform_factory`.\nOften, it can be useful to specify a custom model form. For example,\nyou can create a custom model form that has custom validation::\n\n    class AuthorForm(forms.ModelForm):\n        class Meta:\n            model = Author\n            fields = ('name', 'title')\n\n        def clean_name(self):\n            # custom validation for the name field\n            ...\n\nThen, pass your model form to the factory function::\n\n    AuthorFormSet = modelformset_factory(Author, form=AuthorForm)\n\nIt is not always necessary to define a custom model form. The\n``modelformset_factory`` function has several arguments which are\npassed through to ``modelform_factory``, which are described below.\n\nSpecifying widgets to use in the form with ``widgets``\n------------------------------------------------------\n\nUsing the ``widgets`` parameter, you can specify a dictionary of values to\ncustomize the ``ModelForm``’s widget class for a particular field. This\nworks the same way as the ``widgets`` dictionary on the inner ``Meta``\nclass of a ``ModelForm`` works::\n\n    >>> AuthorFormSet = modelformset_factory(\n    ...     Author, fields=('name', 'title'),\n    ...     widgets={'name': Textarea(attrs={'cols': 80, 'rows': 20})})\n\nEnabling localization for fields with ``localized_fields``\n----------------------------------------------------------\n\nUsing the ``localized_fields`` parameter, you can enable localization for\nfields in the form.\n\n    >>> AuthorFormSet = modelformset_factory(\n    ...     Author, fields=('name', 'title', 'birth_date'),\n    ...     localized_fields=('birth_date',))\n\nIf ``localized_fields`` is set to the special value ``'__all__'``, all fields\nwill be localized.\n\nProviding initial values\n------------------------\n\nAs with regular formsets, it's possible to :ref:`specify initial data\n<formsets-initial-data>` for forms in the formset by specifying an ``initial``\nparameter when instantiating the model formset class returned by\n:func:`~django.forms.models.modelformset_factory`. However, with model\nformsets, the initial values only apply to extra forms, those that aren't\nattached to an existing model instance. If the length of ``initial`` exceeds\nthe number of extra forms, the excess initial data is ignored. If the extra\nforms with initial data aren't changed by the user, they won't be validated or\nsaved.\n\n.. _saving-objects-in-the-formset:\n\nSaving objects in the formset\n-----------------------------\n\nAs with a ``ModelForm``, you can save the data as a model object. This is done\nwith the formset's ``save()`` method::\n\n    # Create a formset instance with POST data.\n    >>> formset = AuthorFormSet(request.POST)\n\n    # Assuming all is valid, save the data.\n    >>> instances = formset.save()\n\nThe ``save()`` method returns the instances that have been saved to the\ndatabase. If a given instance's data didn't change in the bound data, the\ninstance won't be saved to the database and won't be included in the return\nvalue (``instances``, in the above example).\n\nWhen fields are missing from the form (for example because they have been\nexcluded), these fields will not be set by the ``save()`` method. You can find\nmore information about this restriction, which also holds for regular\n``ModelForms``, in `Selecting the fields to use`_.\n\nPass ``commit=False`` to return the unsaved model instances::\n\n    # don't save to the database\n    >>> instances = formset.save(commit=False)\n    >>> for instance in instances:\n    ...     # do something with instance\n    ...     instance.save()\n\nThis gives you the ability to attach data to the instances before saving them\nto the database. If your formset contains a ``ManyToManyField``, you'll also\nneed to call ``formset.save_m2m()`` to ensure the many-to-many relationships\nare saved properly.\n\nAfter calling ``save()``, your model formset will have three new attributes\ncontaining the formset's changes:\n\n.. attribute:: models.BaseModelFormSet.changed_objects\n.. attribute:: models.BaseModelFormSet.deleted_objects\n.. attribute:: models.BaseModelFormSet.new_objects\n\n.. _model-formsets-max-num:\n\nLimiting the number of editable objects\n---------------------------------------\n\nAs with regular formsets, you can use the ``max_num`` and ``extra`` parameters\nto :func:`~django.forms.models.modelformset_factory` to limit the number of\nextra forms displayed.\n\n``max_num`` does not prevent existing objects from being displayed::\n\n    >>> Author.objects.order_by('name')\n    <QuerySet [<Author: Charles Baudelaire>, <Author: Paul Verlaine>, <Author: Walt Whitman>]>\n\n    >>> AuthorFormSet = modelformset_factory(Author, fields=('name',), max_num=1)\n    >>> formset = AuthorFormSet(queryset=Author.objects.order_by('name'))\n    >>> [x.name for x in formset.get_queryset()]\n    ['Charles Baudelaire', 'Paul Verlaine', 'Walt Whitman']\n\nAlso, ``extra=0`` doesn't prevent creation of new model instances as you can\n:ref:`add additional forms with JavaScript <understanding-the-managementform>`\nor send additional POST data. Formsets :ticket:`don't yet provide functionality\n<26142>` for an \"edit only\" view that prevents creation of new instances.\n\nIf the value of ``max_num`` is greater than the number of existing related\nobjects, up to ``extra`` additional blank forms will be added to the formset,\nso long as the total number of forms does not exceed ``max_num``::\n\n    >>> AuthorFormSet = modelformset_factory(Author, fields=('name',), max_num=4, extra=2)\n    >>> formset = AuthorFormSet(queryset=Author.objects.order_by('name'))\n    >>> for form in formset:\n    ...     print(form.as_table())\n    <tr><th><label for=\"id_form-0-name\">Name:</label></th><td><input id=\"id_form-0-name\" type=\"text\" name=\"form-0-name\" value=\"Charles Baudelaire\" maxlength=\"100\"><input type=\"hidden\" name=\"form-0-id\" value=\"1\" id=\"id_form-0-id\"></td></tr>\n    <tr><th><label for=\"id_form-1-name\">Name:</label></th><td><input id=\"id_form-1-name\" type=\"text\" name=\"form-1-name\" value=\"Paul Verlaine\" maxlength=\"100\"><input type=\"hidden\" name=\"form-1-id\" value=\"3\" id=\"id_form-1-id\"></td></tr>\n    <tr><th><label for=\"id_form-2-name\">Name:</label></th><td><input id=\"id_form-2-name\" type=\"text\" name=\"form-2-name\" value=\"Walt Whitman\" maxlength=\"100\"><input type=\"hidden\" name=\"form-2-id\" value=\"2\" id=\"id_form-2-id\"></td></tr>\n    <tr><th><label for=\"id_form-3-name\">Name:</label></th><td><input id=\"id_form-3-name\" type=\"text\" name=\"form-3-name\" maxlength=\"100\"><input type=\"hidden\" name=\"form-3-id\" id=\"id_form-3-id\"></td></tr>\n\nA ``max_num`` value of ``None`` (the default) puts a high limit on the number\nof forms displayed (1000). In practice this is equivalent to no limit.\n\nUsing a model formset in a view\n-------------------------------\n\nModel formsets are very similar to formsets. Let's say we want to present a\nformset to edit ``Author`` model instances::\n\n    from django.forms import modelformset_factory\n    from django.shortcuts import render\n    from myapp.models import Author\n\n    def manage_authors(request):\n        AuthorFormSet = modelformset_factory(Author, fields=('name', 'title'))\n        if request.method == 'POST':\n            formset = AuthorFormSet(request.POST, request.FILES)\n            if formset.is_valid():\n                formset.save()\n                # do something.\n        else:\n            formset = AuthorFormSet()\n        return render(request, 'manage_authors.html', {'formset': formset})\n\nAs you can see, the view logic of a model formset isn't drastically different\nthan that of a \"normal\" formset. The only difference is that we call\n``formset.save()`` to save the data into the database. (This was described\nabove, in :ref:`saving-objects-in-the-formset`.)\n\n.. _model-formsets-overriding-clean:\n\nOverriding ``clean()`` on a ``ModelFormSet``\n--------------------------------------------\n\nJust like with ``ModelForms``, by default the ``clean()`` method of a\n``ModelFormSet`` will validate that none of the items in the formset violate\nthe unique constraints on your model (either ``unique``, ``unique_together`` or\n``unique_for_date|month|year``).  If you want to override the ``clean()`` method\non a ``ModelFormSet`` and maintain this validation, you must call the parent\nclass's ``clean`` method::\n\n    from django.forms import BaseModelFormSet\n\n    class MyModelFormSet(BaseModelFormSet):\n        def clean(self):\n            super().clean()\n            # example custom validation across forms in the formset\n            for form in self.forms:\n                # your custom formset validation\n                ...\n\nAlso note that by the time you reach this step, individual model instances\nhave already been created for each ``Form``. Modifying a value in\n``form.cleaned_data`` is not sufficient to affect the saved value. If you wish\nto modify a value in ``ModelFormSet.clean()`` you must modify\n``form.instance``::\n\n    from django.forms import BaseModelFormSet\n\n    class MyModelFormSet(BaseModelFormSet):\n        def clean(self):\n            super().clean()\n\n            for form in self.forms:\n                name = form.cleaned_data['name'].upper()\n                form.cleaned_data['name'] = name\n                # update the instance value.\n                form.instance.name = name\n\nUsing a custom queryset\n-----------------------\n\nAs stated earlier, you can override the default queryset used by the model\nformset::\n\n    from django.forms import modelformset_factory\n    from django.shortcuts import render\n    from myapp.models import Author\n\n    def manage_authors(request):\n        AuthorFormSet = modelformset_factory(Author, fields=('name', 'title'))\n        if request.method == \"POST\":\n            formset = AuthorFormSet(\n                request.POST, request.FILES,\n                queryset=Author.objects.filter(name__startswith='O'),\n            )\n            if formset.is_valid():\n                formset.save()\n                # Do something.\n        else:\n            formset = AuthorFormSet(queryset=Author.objects.filter(name__startswith='O'))\n        return render(request, 'manage_authors.html', {'formset': formset})\n\nNote that we pass the ``queryset`` argument in both the ``POST`` and ``GET``\ncases in this example.\n\nUsing the formset in the template\n---------------------------------\n\n.. highlight:: html+django\n\nThere are three ways to render a formset in a Django template.\n\nFirst, you can let the formset do most of the work::\n\n    <form method=\"post\">\n        {{ formset }}\n    </form>\n\nSecond, you can manually render the formset, but let the form deal with\nitself::\n\n    <form method=\"post\">\n        {{ formset.management_form }}\n        {% for form in formset %}\n            {{ form }}\n        {% endfor %}\n    </form>\n\nWhen you manually render the forms yourself, be sure to render the management\nform as shown above. See the :ref:`management form documentation\n<understanding-the-managementform>`.\n\nThird, you can manually render each field::\n\n    <form method=\"post\">\n        {{ formset.management_form }}\n        {% for form in formset %}\n            {% for field in form %}\n                {{ field.label_tag }} {{ field }}\n            {% endfor %}\n        {% endfor %}\n    </form>\n\nIf you opt to use this third method and you don't iterate over the fields with\na ``{% for %}`` loop, you'll need to render the primary key field. For example,\nif you were rendering the ``name`` and ``age`` fields of a model::\n\n    <form method=\"post\">\n        {{ formset.management_form }}\n        {% for form in formset %}\n            {{ form.id }}\n            <ul>\n                <li>{{ form.name }}</li>\n                <li>{{ form.age }}</li>\n            </ul>\n        {% endfor %}\n    </form>\n\nNotice how we need to explicitly render ``{{ form.id }}``. This ensures that\nthe model formset, in the ``POST`` case, will work correctly. (This example\nassumes a primary key named ``id``. If you've explicitly defined your own\nprimary key that isn't called ``id``, make sure it gets rendered.)\n\n.. highlight:: python\n\n.. _inline-formsets:\n\nInline formsets\n===============\n\n.. class:: models.BaseInlineFormSet\n\nInline formsets is a small abstraction layer on top of model formsets. These\nsimplify the case of working with related objects via a foreign key. Suppose\nyou have these two models::\n\n    from django.db import models\n\n    class Author(models.Model):\n        name = models.CharField(max_length=100)\n\n    class Book(models.Model):\n        author = models.ForeignKey(Author, on_delete=models.CASCADE)\n        title = models.CharField(max_length=100)\n\nIf you want to create a formset that allows you to edit books belonging to\na particular author, you could do this::\n\n    >>> from django.forms import inlineformset_factory\n    >>> BookFormSet = inlineformset_factory(Author, Book, fields=('title',))\n    >>> author = Author.objects.get(name='Mike Royko')\n    >>> formset = BookFormSet(instance=author)\n\n``BookFormSet``'s :ref:`prefix <formset-prefix>` is ``'book_set'``\n(``<model name>_set`` ). If ``Book``'s ``ForeignKey`` to ``Author`` has a\n:attr:`~django.db.models.ForeignKey.related_name`, that's used instead.\n\n.. note::\n\n    :func:`~django.forms.models.inlineformset_factory` uses\n    :func:`~django.forms.models.modelformset_factory` and marks\n    ``can_delete=True``.\n\n.. seealso::\n\n    :ref:`Manually rendered can_delete and can_order <manually-rendered-can-delete-and-can-order>`.\n\nOverriding methods on an ``InlineFormSet``\n------------------------------------------\n\nWhen overriding methods on ``InlineFormSet``, you should subclass\n:class:`~models.BaseInlineFormSet` rather than\n:class:`~models.BaseModelFormSet`.\n\nFor example, if you want to override ``clean()``::\n\n    from django.forms import BaseInlineFormSet\n\n    class CustomInlineFormSet(BaseInlineFormSet):\n        def clean(self):\n            super().clean()\n            # example custom validation across forms in the formset\n            for form in self.forms:\n                # your custom formset validation\n                ...\n\nSee also :ref:`model-formsets-overriding-clean`.\n\nThen when you create your inline formset, pass in the optional argument\n``formset``::\n\n    >>> from django.forms import inlineformset_factory\n    >>> BookFormSet = inlineformset_factory(Author, Book, fields=('title',),\n    ...     formset=CustomInlineFormSet)\n    >>> author = Author.objects.get(name='Mike Royko')\n    >>> formset = BookFormSet(instance=author)\n\nMore than one foreign key to the same model\n-------------------------------------------\n\nIf your model contains more than one foreign key to the same model, you'll\nneed to resolve the ambiguity manually using ``fk_name``. For example, consider\nthe following model::\n\n    class Friendship(models.Model):\n        from_friend = models.ForeignKey(\n            Friend,\n            on_delete=models.CASCADE,\n            related_name='from_friends',\n        )\n        to_friend = models.ForeignKey(\n            Friend,\n            on_delete=models.CASCADE,\n            related_name='friends',\n        )\n        length_in_months = models.IntegerField()\n\nTo resolve this, you can use ``fk_name`` to\n:func:`~django.forms.models.inlineformset_factory`::\n\n    >>> FriendshipFormSet = inlineformset_factory(Friend, Friendship, fk_name='from_friend',\n    ...     fields=('to_friend', 'length_in_months'))\n\nUsing an inline formset in a view\n---------------------------------\n\nYou may want to provide a view that allows a user to edit the related objects\nof a model. Here's how you can do that::\n\n    def manage_books(request, author_id):\n        author = Author.objects.get(pk=author_id)\n        BookInlineFormSet = inlineformset_factory(Author, Book, fields=('title',))\n        if request.method == \"POST\":\n            formset = BookInlineFormSet(request.POST, request.FILES, instance=author)\n            if formset.is_valid():\n                formset.save()\n                # Do something. Should generally end with a redirect. For example:\n                return HttpResponseRedirect(author.get_absolute_url())\n        else:\n            formset = BookInlineFormSet(instance=author)\n        return render(request, 'manage_books.html', {'formset': formset})\n\nNotice how we pass ``instance`` in both the ``POST`` and ``GET`` cases.\n\nSpecifying widgets to use in the inline form\n--------------------------------------------\n\n\n``inlineformset_factory`` uses ``modelformset_factory`` and passes most\nof its arguments to ``modelformset_factory``. This means you can use\nthe ``widgets`` parameter in much the same way as passing it to\n``modelformset_factory``. See `Specifying widgets to use in the form with\nwidgets`_ above.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":322,"nodeType":"TextFile","repoName":null,"name":"index.txt","path":"docs/topics/class-based-views","text":"=================\nClass-based views\n=================\n\nA view is a callable which takes a request and returns a\nresponse. This can be more than just a function, and Django provides\nan example of some classes which can be used as views. These allow you\nto structure your views and reuse code by harnessing inheritance and\nmixins. There are also some generic views for tasks which we'll get to later,\nbut you may want to design your own structure of reusable views which suits\nyour use case. For full details, see the :doc:`class-based views reference\ndocumentation</ref/class-based-views/index>`.\n\n.. toctree::\n   :maxdepth: 1\n\n   intro\n   generic-display\n   generic-editing\n   mixins\n\nBasic examples\n==============\n\nDjango provides base view classes which will suit a wide range of applications.\nAll views inherit from the :class:`~django.views.generic.base.View` class, which\nhandles linking the view into the URLs, HTTP method dispatching and other\ncommon features. :class:`~django.views.generic.base.RedirectView` provides a\nHTTP redirect, and :class:`~django.views.generic.base.TemplateView` extends the\nbase class to make it also render a template.\n\n\nUsage in your URLconf\n=====================\n\nThe most direct way to use generic views is to create them directly in your\nURLconf. If you're only changing a few attributes on a class-based view, you\ncan pass them into the :meth:`~django.views.generic.base.View.as_view` method\ncall itself::\n\n    from django.urls import path\n    from django.views.generic import TemplateView\n\n    urlpatterns = [\n        path('about/', TemplateView.as_view(template_name=\"about.html\")),\n    ]\n\nAny arguments passed to :meth:`~django.views.generic.base.View.as_view` will\noverride attributes set on the class. In this example, we set ``template_name``\non the ``TemplateView``. A similar overriding pattern can be used for the\n``url`` attribute on :class:`~django.views.generic.base.RedirectView`.\n\n\nSubclassing generic views\n=========================\n\nThe second, more powerful way to use generic views is to inherit from an\nexisting view and override attributes (such as the ``template_name``) or\nmethods (such as ``get_context_data``) in your subclass to provide new values\nor methods. Consider, for example, a view that just displays one template,\n``about.html``. Django has a generic view to do this -\n:class:`~django.views.generic.base.TemplateView` - so we can subclass it, and\noverride the template name::\n\n    # some_app/views.py\n    from django.views.generic import TemplateView\n\n    class AboutView(TemplateView):\n        template_name = \"about.html\"\n\nThen we need to add this new view into our URLconf.\n:class:`~django.views.generic.base.TemplateView` is a class, not a function, so\nwe point the URL to the :meth:`~django.views.generic.base.View.as_view` class\nmethod instead, which provides a function-like entry to class-based views::\n\n    # urls.py\n    from django.urls import path\n    from some_app.views import AboutView\n\n    urlpatterns = [\n        path('about/', AboutView.as_view()),\n    ]\n\n\nFor more information on how to use the built in generic views, consult the next\ntopic on :doc:`generic class-based views</topics/class-based-views/generic-display>`.\n\n.. _supporting-other-http-methods:\n\nSupporting other HTTP methods\n-----------------------------\n\nSuppose somebody wants to access our book library over HTTP using the views\nas an API. The API client would connect every now and then and download book\ndata for the books published since last visit. But if no new books appeared\nsince then, it is a waste of CPU time and bandwidth to fetch the books from the\ndatabase, render a full response and send it to the client. It might be\npreferable to ask the API when the most recent book was published.\n\nWe map the URL to book list view in the URLconf::\n\n    from django.urls import path\n    from books.views import BookListView\n\n    urlpatterns = [\n        path('books/', BookListView.as_view()),\n    ]\n\nAnd the view::\n\n    from django.http import HttpResponse\n    from django.views.generic import ListView\n    from books.models import Book\n\n    class BookListView(ListView):\n        model = Book\n\n        def head(self, *args, **kwargs):\n            last_book = self.get_queryset().latest('publication_date')\n            response = HttpResponse()\n            # RFC 1123 date format\n            response['Last-Modified'] = last_book.publication_date.strftime('%a, %d %b %Y %H:%M:%S GMT')\n            return response\n\nIf the view is accessed from a ``GET`` request, an object list is returned in\nthe response (using the ``book_list.html`` template). But if the client issues\na ``HEAD`` request, the response has an empty body and the ``Last-Modified``\nheader indicates when the most recent book was published.  Based on this\ninformation, the client may or may not download the full object list.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":323,"nodeType":"Package","repoName":null,"name":"docs/releases","path":null,"text":null,"fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":324,"nodeType":"TextFile","repoName":null,"name":"3.2.txt","path":"docs/releases","text":"============================================\nDjango 3.2 release notes - UNDER DEVELOPMENT\n============================================\n\n*Expected April 2021*\n\nWelcome to Django 3.2!\n\nThese release notes cover the :ref:`new features <whats-new-3.2>`, as well as\nsome :ref:`backwards incompatible changes <backwards-incompatible-3.2>` you'll\nwant to be aware of when upgrading from Django 3.1 or earlier. We've\n:ref:`begun the deprecation process for some features\n<deprecated-features-3.2>`.\n\nSee the :doc:`/howto/upgrade-version` guide if you're updating an existing\nproject.\n\nDjango 3.2 is designated as a :term:`long-term support release\n<Long-term support release>`. It will receive security updates for at least\nthree years after its release. Support for the previous LTS, Django 2.2, will\nend in April 2022.\n\nPython compatibility\n====================\n\nDjango 3.2 supports Python 3.6, 3.7, and 3.8. We **highly recommend** and only\nofficially support the latest release of each series.\n\n.. _whats-new-3.2:\n\nWhat's new in Django 3.2\n========================\n\nMinor features\n--------------\n\n:mod:`django.contrib.admin`\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n* ...\n\n:mod:`django.contrib.admindocs`\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n* ...\n\n:mod:`django.contrib.auth`\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n* The default iteration count for the PBKDF2 password hasher is increased from\n  216,000 to 260,000.\n\n:mod:`django.contrib.contenttypes`\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n* ...\n\n:mod:`django.contrib.gis`\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\n* ...\n\n:mod:`django.contrib.messages`\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n* ...\n\n:mod:`django.contrib.postgres`\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n* ...\n\n:mod:`django.contrib.redirects`\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n* ...\n\n:mod:`django.contrib.sessions`\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n* ...\n\n:mod:`django.contrib.sitemaps`\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n* ...\n\n:mod:`django.contrib.sites`\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n* ...\n\n:mod:`django.contrib.staticfiles`\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n* ...\n\n:mod:`django.contrib.syndication`\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n* ...\n\nCache\n~~~~~\n\n* ...\n\nCSRF\n~~~~\n\n* ...\n\nEmail\n~~~~~\n\n* ...\n\nError Reporting\n~~~~~~~~~~~~~~~\n\n* ...\n\nFile Storage\n~~~~~~~~~~~~\n\n* ...\n\nFile Uploads\n~~~~~~~~~~~~\n\n* ...\n\n\nForms\n~~~~~\n\n* ...\n\nGeneric Views\n~~~~~~~~~~~~~\n\n* ...\n\nInternationalization\n~~~~~~~~~~~~~~~~~~~~\n\n* ...\n\nLogging\n~~~~~~~\n\n* ...\n\nManagement Commands\n~~~~~~~~~~~~~~~~~~~\n\n* :djadmin:`loaddata` now supports fixtures stored in XZ archives (``.xz``) and\n  LZMA archives (``.lzma``).\n\n* :djadmin:`makemigrations` can now be called without an active database\n  connection. In that case, check for a consistent migration history is\n  skipped.\n\nMigrations\n~~~~~~~~~~\n\n* ...\n\nModels\n~~~~~~\n\n* ...\n\nRequests and Responses\n~~~~~~~~~~~~~~~~~~~~~~\n\n* ...\n\nSecurity\n~~~~~~~~\n\n* ...\n\nSerialization\n~~~~~~~~~~~~~\n\n* ...\n\nSignals\n~~~~~~~\n\n* ...\n\nTemplates\n~~~~~~~~~\n\n* ...\n\nTests\n~~~~~\n\n* Objects assigned to class attributes in :meth:`.TestCase.setUpTestData` are\n  now isolated for each test method. Such objects are now required to support\n  creating deep copies with :py:func:`copy.deepcopy`. Assigning objects which\n  don't support ``deepcopy()`` is deprecated and will be removed in Django 4.1.\n\nURLs\n~~~~\n\n* ...\n\nUtilities\n~~~~~~~~~\n\n* ...\n\nValidators\n~~~~~~~~~~\n\n* ...\n\n.. _backwards-incompatible-3.2:\n\nBackwards incompatible changes in 3.2\n=====================================\n\nDatabase backend API\n--------------------\n\nThis section describes changes that may be needed in third-party database\nbackends.\n\n* ...\n\n:mod:`django.contrib.gis`\n-------------------------\n\n* Support for PostGIS 2.2 is removed.\n\nDropped support for PostgreSQL 9.5\n----------------------------------\n\nUpstream support for PostgreSQL 9.5 ends in February 2021. Django 3.2 supports\nPostgreSQL 9.6 and higher.\n\nDropped support for MySQL 5.6\n-----------------------------\n\nThe end of upstream support for MySQL 5.6 is April 2021. Django 3.2 supports\nMySQL 5.7 and higher.\n\nMiscellaneous\n-------------\n\n* The undocumented ``SpatiaLiteOperations.proj4_version()`` method is renamed\n  to ``proj_version()``.\n\n* Minified JavaScript files are no longer included with the admin. If you\n  require these files to be minified, consider using a third party app or\n  external build tool. The minified vendored JavaScript files packaged with the\n  admin (e.g. :ref:`jquery.min.js <contrib-admin-jquery>`) are still included.\n\n.. _deprecated-features-3.2:\n\nFeatures deprecated in 3.2\n==========================\n\nMiscellaneous\n-------------\n\n* Assigning objects which don't support creating deep copies with\n  :py:func:`copy.deepcopy` to class attributes in\n  :meth:`.TestCase.setUpTestData` is deprecated.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":325,"nodeType":"TextFile","repoName":null,"name":"3.0.2.txt","path":"docs/releases","text":"==========================\nDjango 3.0.2 release notes\n==========================\n\n*January 2, 2020*\n\nDjango 3.0.2 fixes several bugs in 3.0.1.\n\nBugfixes\n========\n\n* Fixed a regression in Django 3.0 that didn't include columns referenced by a\n  ``Subquery()`` in the ``GROUP BY`` clause (:ticket:`31094`).\n\n* Fixed a regression in Django 3.0 where ``QuerySet.exists()`` crashed if a\n  queryset contained an aggregation over a ``Subquery()`` (:ticket:`31109`).\n\n* Fixed a regression in Django 3.0 that caused a migration crash on PostgreSQL\n  10+ when adding a foreign key and changing data in the same migration\n  (:ticket:`31106`).\n\n* Fixed a regression in Django 3.0 where loading fixtures crashed for models\n  defining a :attr:`~django.db.models.Field.default` for the primary key\n  (:ticket:`31071`).\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":326,"nodeType":"TextFile","repoName":null,"name":"2.1.9.txt","path":"docs/releases","text":"============================\nDjango 2.1.9 release notes\n============================\n\n*June 3, 2019*\n\nDjango 2.1.9 fixes security issues in 2.1.8.\n\nCVE-2019-12308: AdminURLFieldWidget XSS\n---------------------------------------\n\nThe clickable \"Current URL\" link generated by ``AdminURLFieldWidget`` displayed\nthe provided value without validating it as a safe URL. Thus, an unvalidated\nvalue stored in the database, or a value provided as a URL query parameter\npayload, could result in an clickable JavaScript link.\n\n``AdminURLFieldWidget`` now validates the provided value using\n:class:`~django.core.validators.URLValidator` before displaying the clickable\nlink. You may customize the validator by passing a ``validator_class`` kwarg to\n``AdminURLFieldWidget.__init__()``, e.g. when using\n:attr:`~django.contrib.admin.ModelAdmin.formfield_overrides`.\n\nPatched bundled jQuery for CVE-2019-11358: Prototype pollution\n--------------------------------------------------------------\n\njQuery before 3.4.0, mishandles ``jQuery.extend(true, {}, ...)`` because of\n``Object.prototype`` pollution. If an unsanitized source object contained an\nenumerable ``__proto__`` property, it could extend the native\n``Object.prototype``.\n\nThe bundled version of jQuery used by the Django admin has been patched to\nallow for the ``select2`` library's use of ``jQuery.extend()``.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":327,"nodeType":"TextFile","repoName":null,"name":"1.4.2.txt","path":"docs/releases","text":"==========================\nDjango 1.4.2 release notes\n==========================\n\n*October 17, 2012*\n\nThis is the second security release in the Django 1.4 series.\n\nHost header poisoning\n=====================\n\nSome parts of Django -- independent of end-user-written applications -- make\nuse of full URLs, including domain name, which are generated from the HTTP Host\nheader. Some attacks against this are beyond Django's ability to control, and\nrequire the web server to be properly configured; Django's documentation has\nfor some time contained notes advising users on such configuration.\n\nDjango's own built-in parsing of the Host header is, however, still vulnerable,\nas was reported to us recently. The Host header parsing in Django 1.3.3 and\nDjango 1.4.1 -- specifically, ``django.http.HttpRequest.get_host()`` -- was\nincorrectly handling username/password information in the header. Thus, for\nexample, the following Host header would be accepted by Django when running on\n\"validsite.com\"::\n\n    Host: validsite.com:random@evilsite.com\n\nUsing this, an attacker can cause parts of Django -- particularly the\npassword-reset mechanism -- to generate and display arbitrary URLs to users.\n\nTo remedy this, the parsing in ``HttpRequest.get_host()`` is being modified;\nHost headers which contain potentially dangerous content (such as\nusername/password pairs) now raise the exception\n:exc:`django.core.exceptions.SuspiciousOperation`.\n\nDetails of this issue were initially posted online as a `security advisory`_.\n\n.. _security advisory: https://www.djangoproject.com/weblog/2012/oct/17/security/\n\nBackwards incompatible changes\n==============================\n\n* The newly introduced :class:`~django.db.models.GenericIPAddressField`\n  constructor arguments have been adapted to match those of all other model\n  fields. The first two keyword arguments are now verbose_name and name.\n\nOther bugfixes and changes\n==========================\n\n* Subclass HTMLParser only for appropriate Python versions (#18239).\n* Added batch_size argument to qs.bulk_create() (#17788).\n* Fixed a small regression in the admin filters where wrongly formatted dates passed as url parameters caused an unhandled ValidationError (#18530).\n* Fixed an endless loop bug when accessing permissions in templates (#18979)\n* Fixed some Python 2.5 compatibility issues\n* Fixed an issue with quoted filenames in Content-Disposition header (#19006)\n* Made the context option in ``trans`` and ``blocktrans`` tags accept literals wrapped in single quotes (#18881).\n* Numerous documentation improvements and fixes.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":328,"nodeType":"TextFile","repoName":null,"name":"2.1.14.txt","path":"docs/releases","text":"===========================\nDjango 2.1.14 release notes\n===========================\n\n*November 4, 2019*\n\nDjango 2.1.14 fixes a regression in 2.1.13.\n\nBugfixes\n========\n\n* Fixed a crash when using a ``contains``, ``contained_by``, ``has_key``,\n  ``has_keys``, or ``has_any_keys`` lookup on\n  :class:`~django.contrib.postgres.fields.JSONField`, if the right or left hand\n  side of an expression is a key transform (:ticket:`30826`).\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":329,"nodeType":"TextFile","repoName":null,"name":"1.3.5.txt","path":"docs/releases","text":"==========================\nDjango 1.3.5 release notes\n==========================\n\n*December 10, 2012*\n\nDjango 1.3.5 addresses two security issues present in previous Django releases\nin the 1.3 series.\n\nPlease be aware that this security release is slightly different from previous\nones. Both issues addressed here have been dealt with in prior security updates\nto Django. In one case, we have received ongoing reports of problems, and in\nthe other we've chosen to take further steps to tighten up Django's code in\nresponse to independent discovery of potential problems from multiple sources.\n\nHost header poisoning\n=====================\n\nSeveral earlier Django security releases focused on the issue of poisoning the\nHTTP Host header, causing Django to generate URLs pointing to arbitrary,\npotentially-malicious domains.\n\nIn response to further input received and reports of continuing issues\nfollowing the previous release, we're taking additional steps to tighten Host\nheader validation. Rather than attempt to accommodate all features HTTP\nsupports here, Django's Host header validation attempts to support a smaller,\nbut far more common, subset:\n\n* Hostnames must consist of characters ``[A-Za-z0-9]`` plus hyphen ('-') or dot\n  ('.').\n* IP addresses -- both IPv4 and IPv6 -- are permitted.\n* Port, if specified, is numeric.\n\nAny deviation from this will now be rejected, raising the exception\n:exc:`django.core.exceptions.SuspiciousOperation`.\n\nRedirect poisoning\n==================\n\nAlso following up on a previous issue: in July of this year, we made changes to\nDjango's HTTP redirect classes, performing additional validation of the scheme\nof the URL to redirect to (since, both within Django's own supplied\napplications and many third-party applications, accepting a user-supplied\nredirect target is a common pattern).\n\nSince then, two independent audits of the code turned up further potential\nproblems. So, similar to the Host-header issue, we are taking steps to provide\ntighter validation in response to reported problems (primarily with third-party\napplications, but to a certain extent also within Django itself). This comes in\ntwo parts:\n\n1. A new utility function, ``django.utils.http.is_safe_url``, is added; this\nfunction takes a URL and a hostname, and checks that the URL is either\nrelative, or if absolute matches the supplied hostname. This function is\nintended for use whenever user-supplied redirect targets are accepted, to\nensure that such redirects cannot lead to arbitrary third-party sites.\n\n2. All of Django's own built-in views -- primarily in the authentication system\n-- which allow user-supplied redirect targets now use ``is_safe_url`` to\nvalidate the supplied URL.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":330,"nodeType":"TextFile","repoName":null,"name":"2.2.6.txt","path":"docs/releases","text":"==========================\nDjango 2.2.6 release notes\n==========================\n\n*October 1, 2019*\n\nDjango 2.2.6 fixes several bugs in 2.2.5.\n\nBugfixes\n========\n\n* Fixed migrations crash on SQLite when altering a model containing partial\n  indexes (:ticket:`30754`).\n\n* Fixed a regression in Django 2.2.4 that caused a crash when filtering with a\n  ``Subquery()`` annotation of a queryset containing\n  :class:`~django.contrib.postgres.fields.JSONField` or\n  :class:`~django.contrib.postgres.fields.HStoreField` (:ticket:`30769`).\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":331,"nodeType":"TextFile","repoName":null,"name":"2.2.2.txt","path":"docs/releases","text":"==========================\nDjango 2.2.2 release notes\n==========================\n\n*June 3, 2019*\n\nDjango 2.2.2 fixes security issues and several bugs in 2.2.1.\n\nCVE-2019-12308: AdminURLFieldWidget XSS\n---------------------------------------\n\nThe clickable \"Current URL\" link generated by ``AdminURLFieldWidget`` displayed\nthe provided value without validating it as a safe URL. Thus, an unvalidated\nvalue stored in the database, or a value provided as a URL query parameter\npayload, could result in an clickable JavaScript link.\n\n``AdminURLFieldWidget`` now validates the provided value using\n:class:`~django.core.validators.URLValidator` before displaying the clickable\nlink. You may customize the validator by passing a ``validator_class`` kwarg to\n``AdminURLFieldWidget.__init__()``, e.g. when using\n:attr:`~django.contrib.admin.ModelAdmin.formfield_overrides`.\n\nPatched bundled jQuery for CVE-2019-11358: Prototype pollution\n--------------------------------------------------------------\n\njQuery before 3.4.0, mishandles ``jQuery.extend(true, {}, ...)`` because of\n``Object.prototype`` pollution. If an unsanitized source object contained an\nenumerable ``__proto__`` property, it could extend the native\n``Object.prototype``.\n\nThe bundled version of jQuery used by the Django admin has been patched to\nallow for the ``select2`` library's use of ``jQuery.extend()``.\n\nBugfixes\n========\n\n* Fixed a regression in Django 2.2 that stopped Show/Hide toggles working on\n  dynamically added admin inlines (:ticket:`30459`).\n\n* Fixed a regression in Django 2.2 where deprecation message crashes if\n  ``Meta.ordering`` contains an expression (:ticket:`30463`).\n\n* Fixed a regression in Django 2.2.1 where\n  :class:`~django.contrib.postgres.search.SearchVector` generates SQL with a\n  redundant ``Coalesce`` call (:ticket:`30488`).\n\n* Fixed a regression in Django 2.2 where auto-reloader doesn't detect changes\n  in ``manage.py`` file when using ``StatReloader`` (:ticket:`30479`).\n\n* Fixed crash of :class:`~django.contrib.postgres.aggregates.ArrayAgg` and\n  :class:`~django.contrib.postgres.aggregates.StringAgg` with ``ordering``\n  argument when used in a ``Subquery`` (:ticket:`30315`).\n\n* Fixed a regression in Django 2.2 that caused a crash of auto-reloader when\n  an exception with custom signature is raised (:ticket:`30516`).\n\n* Fixed a regression in Django 2.2.1 where auto-reloader unnecessarily reloads\n  translation files multiple times when using ``StatReloader``\n  (:ticket:`30523`).\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":332,"nodeType":"TextFile","repoName":null,"name":"2.1.5.txt","path":"docs/releases","text":"==========================\nDjango 2.1.5 release notes\n==========================\n\n*January 4, 2019*\n\nDjango 2.1.5 fixes a security issue and several bugs in 2.1.4.\n\nCVE-2019-3498: Content spoofing possibility in the default 404 page\n-------------------------------------------------------------------\n\nAn attacker could craft a malicious URL that could make spoofed content appear\non the default page generated by the ``django.views.defaults.page_not_found()``\nview.\n\nThe URL path is no longer displayed in the default 404 template and the\n``request_path`` context variable is now quoted to fix the issue for custom\ntemplates that use the path.\n\nBugfixes\n========\n\n* Fixed compatibility with mysqlclient 1.3.14 (:ticket:`30013`).\n\n* Fixed a schema corruption issue on SQLite 3.26+. You might have to drop and\n  rebuild your SQLite database if you applied a migration while using an older\n  version of Django with SQLite 3.26 or later (:ticket:`29182`).\n\n* Prevented SQLite schema alterations while foreign key checks are enabled to\n  avoid the possibility of schema corruption (:ticket:`30023`).\n\n* Fixed a regression in Django 2.1.4 (which enabled keep-alive connections)\n  where request body data isn't properly consumed for such connections\n  (:ticket:`30015`).\n\n* Fixed a regression in Django 2.1.4 where\n  ``InlineModelAdmin.has_change_permission()`` is incorrectly called with a\n  non-``None`` ``obj`` argument during an object add (:ticket:`30050`).\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":333,"nodeType":"TextFile","repoName":null,"name":"1.4.6.txt","path":"docs/releases","text":"==========================\nDjango 1.4.6 release notes\n==========================\n\n*August 13, 2013*\n\nDjango 1.4.6 fixes one security issue present in previous Django releases in\nthe 1.4 series, as well as one other bug.\n\nThis is the sixth bugfix/security release in the Django 1.4 series.\n\nMitigated possible XSS attack via user-supplied redirect URLs\n=============================================================\n\nDjango relies on user input in some cases (e.g.\n``django.contrib.auth.views.login()``, ``django.contrib.comments``, and\n:doc:`i18n </topics/i18n/index>`) to redirect the user to an \"on success\" URL.\nThe security checks for these redirects (namely\n``django.utils.http.is_safe_url()``) didn't check if the scheme is ``http(s)``\nand as such allowed ``javascript:...`` URLs to be entered. If a developer\nrelied on ``is_safe_url()`` to provide safe redirect targets and put such a\nURL into a link, they could suffer from a XSS attack. This bug doesn't affect\nDjango currently, since we only put this URL into the ``Location`` response\nheader and browsers seem to ignore JavaScript there.\n\nBugfixes\n========\n\n* Fixed an obscure bug with the :func:`~django.test.override_settings`\n  decorator. If you hit an ``AttributeError: 'Settings' object has no attribute\n  '_original_allowed_hosts'`` exception, it's probably fixed (#20636).\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":334,"nodeType":"TextFile","repoName":null,"name":"1.8.5.txt","path":"docs/releases","text":"==========================\nDjango 1.8.5 release notes\n==========================\n\n*October 3, 2015*\n\nDjango 1.8.5 fixes several bugs in 1.8.4.\n\nBugfixes\n========\n\n* Made the development server's autoreload more robust (:ticket:`24704`).\n\n* Fixed ``AssertionError`` in some delete queries with a model containing a\n  field that is both a foreign and primary key (:ticket:`24951`).\n\n* Fixed ``AssertionError`` in some complex queries (:ticket:`24525`).\n\n* Fixed a migrations crash with ``GenericForeignKey`` (:ticket:`25040`).\n\n* Made ``translation.override()`` clear the overridden language when a\n  translation isn't initially active (:ticket:`25295`).\n\n* Fixed crash when using a value in ``ModelAdmin.list_display`` that clashed\n  with a reverse field on the model (:ticket:`25299`).\n\n* Fixed autocompletion for options of non-``argparse`` management commands\n  (:ticket:`25372`).\n\n* Alphabetized ordering of imports in ``from django.db import migrations,\n  models`` statement in newly created migrations (:ticket:`25384`).\n\n* Fixed migrations crash on MySQL when adding a text or a blob field with an\n  unhashable default (:ticket:`25393`).\n\n* Changed ``Count`` queries to execute ``COUNT(*)`` instead of ``COUNT('*')``\n  as versions of Django before 1.8 did (:ticket:`25377`). This may fix a\n  performance regression on some databases.\n\n* Fixed custom queryset chaining with ``values()`` and ``values_list()``\n  (:ticket:`20625`).\n\n* Moved the :ref:`unsaved model instance assignment data loss check\n  <unsaved-model-instance-check-18>` on reverse relations to ``Model.save()``\n  (:ticket:`25160`).\n\n* Readded inline foreign keys to form instances when validating model formsets\n  (:ticket:`25431`).\n\n* Allowed using ORM write methods after disabling autocommit with\n  :func:`set_autocommit(False) <django.db.transaction.set_autocommit>`\n  (:ticket:`24921`).\n\n* Fixed the ``manage.py test --keepdb`` option on Oracle (:ticket:`25421`).\n\n* Fixed incorrect queries with multiple many-to-many fields on a model with the\n  same 'to' model and with ``related_name`` set to '+' (:ticket:`24505`,\n  :ticket:`25486`).\n\n* Fixed pickling a ``SimpleLazyObject`` wrapping a model (:ticket:`25389`).\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":335,"nodeType":"TextFile","repoName":null,"name":"1.11.7.txt","path":"docs/releases","text":"===========================\nDjango 1.11.7 release notes\n===========================\n\n*November 1, 2017*\n\nDjango 1.11.7 fixes several bugs in 1.11.6.\n\nBugfixes\n========\n\n* Prevented ``cache.get_or_set()`` from caching ``None`` if the ``default``\n  argument is a callable that returns ``None`` (:ticket:`28601`).\n\n* Fixed the Basque ``DATE_FORMAT`` string (:ticket:`28710`).\n\n* Made ``QuerySet.reverse()`` affect ``nulls_first`` and ``nulls_last``\n  (:ticket:`28722`).\n\n* Fixed unquoted table names in ``Subquery`` SQL when using ``OuterRef``\n  (:ticket:`28689`).\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":336,"nodeType":"TextFile","repoName":null,"name":"1.11.14.txt","path":"docs/releases","text":"============================\nDjango 1.11.14 release notes\n============================\n\n*July 2, 2018*\n\nDjango 1.11.14 fixes several bugs in 1.11.13.\n\nBugfixes\n========\n\n* Fixed ``WKBWriter.write()`` and ``write_hex()`` for empty polygons on\n  GEOS 3.6.1+ (:ticket:`29460`).\n\n* Fixed a regression in Django 1.10 that could result in large memory usage\n  when making edits using ``ModelAdmin.list_editable`` (:ticket:`28462`).\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":337,"nodeType":"TextFile","repoName":null,"name":"1.8.14.txt","path":"docs/releases","text":"===========================\nDjango 1.8.14 release notes\n===========================\n\n*July 18, 2016*\n\nDjango 1.8.14 fixes a security issue and a bug in 1.8.13.\n\nXSS in admin's add/change related popup\n=======================================\n\nUnsafe usage of JavaScript's ``Element.innerHTML`` could result in XSS in the\nadmin's add/change related popup. ``Element.textContent`` is now used to\nprevent execution of the data.\n\nThe debug view also used ``innerHTML``. Although a security issue wasn't\nidentified there, out of an abundance of caution it's also updated to use\n``textContent``.\n\nBugfixes\n========\n\n* Fixed missing ``varchar/text_pattern_ops`` index on ``CharField`` and\n  ``TextField`` respectively when using ``AddField`` on PostgreSQL\n  (:ticket:`26889`).\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":338,"nodeType":"TextFile","repoName":null,"name":"1.9.9.txt","path":"docs/releases","text":"==========================\nDjango 1.9.9 release notes\n==========================\n\n*August 1, 2016*\n\nDjango 1.9.9 fixes several bugs in 1.9.8.\n\nBugfixes\n========\n\n* Fixed invalid HTML in template postmortem on the debug page\n  (:ticket:`26938`).\n\n* Fixed some GIS database function crashes on MySQL 5.7 (:ticket:`26657`).\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":339,"nodeType":"TextFile","repoName":null,"name":"generic-display.txt","path":"docs/topics/class-based-views","text":"==================================\nBuilt-in class-based generic views\n==================================\n\nWriting Web applications can be monotonous, because we repeat certain patterns\nagain and again. Django tries to take away some of that monotony at the model\nand template layers, but Web developers also experience this boredom at the view\nlevel.\n\nDjango's *generic views* were developed to ease that pain. They take certain\ncommon idioms and patterns found in view development and abstract them so that\nyou can quickly write common views of data without having to write too much\ncode.\n\nWe can recognize certain common tasks, like displaying a list of objects, and\nwrite code that displays a list of *any* object. Then the model in question can\nbe passed as an extra argument to the URLconf.\n\nDjango ships with generic views to do the following:\n\n* Display list and detail pages for a single object. If we were creating an\n  application to manage conferences then a ``TalkListView`` and a\n  ``RegisteredUserListView`` would be examples of list views. A single\n  talk page is an example of what we call a \"detail\" view.\n\n* Present date-based objects in year/month/day archive pages,\n  associated detail, and \"latest\" pages.\n\n* Allow users to create, update, and delete objects -- with or\n  without authorization.\n\nTaken together, these views provide interfaces to perform the most common tasks\ndevelopers encounter.\n\n\nExtending generic views\n=======================\n\nThere's no question that using generic views can speed up development\nsubstantially. In most projects, however, there comes a moment when the\ngeneric views no longer suffice. Indeed, the most common question asked by new\nDjango developers is how to make generic views handle a wider array of\nsituations.\n\nThis is one of the reasons generic views were redesigned for the 1.3 release -\npreviously, they were view functions with a bewildering array of options; now,\nrather than passing in a large amount of configuration in the URLconf, the\nrecommended way to extend generic views is to subclass them, and override their\nattributes or methods.\n\nThat said, generic views will have a limit. If you find you're struggling to\nimplement your view as a subclass of a generic view, then you may find it more\neffective to write just the code you need, using your own class-based or\nfunctional views.\n\nMore examples of generic views are available in some third party applications,\nor you could write your own as needed.\n\n\nGeneric views of objects\n========================\n\n:class:`~django.views.generic.base.TemplateView` certainly is useful, but\nDjango's generic views really shine when it comes to presenting views of your\ndatabase content. Because it's such a common task, Django comes with a handful\nof built-in generic views to help generate list and detail views of objects.\n\nLet's start by looking at some examples of showing a list of objects or an\nindividual object.\n\n.. comment: link here to the other topic pages (form handling, date based, mixins)\n\nWe'll be using these models::\n\n    # models.py\n    from django.db import models\n\n    class Publisher(models.Model):\n        name = models.CharField(max_length=30)\n        address = models.CharField(max_length=50)\n        city = models.CharField(max_length=60)\n        state_province = models.CharField(max_length=30)\n        country = models.CharField(max_length=50)\n        website = models.URLField()\n\n        class Meta:\n            ordering = [\"-name\"]\n\n        def __str__(self):\n            return self.name\n\n    class Author(models.Model):\n        salutation = models.CharField(max_length=10)\n        name = models.CharField(max_length=200)\n        email = models.EmailField()\n        headshot = models.ImageField(upload_to='author_headshots')\n\n        def __str__(self):\n            return self.name\n\n    class Book(models.Model):\n        title = models.CharField(max_length=100)\n        authors = models.ManyToManyField('Author')\n        publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)\n        publication_date = models.DateField()\n\nNow we need to define a view::\n\n    # views.py\n    from django.views.generic import ListView\n    from books.models import Publisher\n\n    class PublisherList(ListView):\n        model = Publisher\n\nFinally hook that view into your urls::\n\n    # urls.py\n    from django.urls import path\n    from books.views import PublisherList\n\n    urlpatterns = [\n        path('publishers/', PublisherList.as_view()),\n    ]\n\nThat's all the Python code we need to write. We still need to write a template,\nhowever. We could explicitly tell the view which template to use by adding a\n``template_name`` attribute to the view, but in the absence of an explicit\ntemplate Django will infer one from the object's name. In this case, the\ninferred template will be ``\"books/publisher_list.html\"`` -- the \"books\" part\ncomes from the name of the app that defines the model, while the \"publisher\"\nbit is the lowercased version of the model's name.\n\n.. note::\n\n    Thus, when (for example) the ``APP_DIRS`` option of a ``DjangoTemplates``\n    backend is set to True in :setting:`TEMPLATES`, a template location could\n    be: /path/to/project/books/templates/books/publisher_list.html\n\nThis template will be rendered against a context containing a variable called\n``object_list`` that contains all the publisher objects. A template might look\nlike this:\n\n.. code-block:: html+django\n\n    {% extends \"base.html\" %}\n\n    {% block content %}\n        <h2>Publishers</h2>\n        <ul>\n            {% for publisher in object_list %}\n                <li>{{ publisher.name }}</li>\n            {% endfor %}\n        </ul>\n    {% endblock %}\n\nThat's really all there is to it. All the cool features of generic views come\nfrom changing the attributes set on the generic view. The\n:doc:`generic views reference</ref/class-based-views/index>` documents all the\ngeneric views and their options in detail; the rest of this document will\nconsider some of the common ways you might customize and extend generic views.\n\n\nMaking \"friendly\" template contexts\n-----------------------------------\n\nYou might have noticed that our sample publisher list template stores all the\npublishers in a variable named ``object_list``. While this works just fine, it\nisn't all that \"friendly\" to template authors: they have to \"just know\" that\nthey're dealing with publishers here.\n\nWell, if you're dealing with a model object, this is already done for you. When\nyou are dealing with an object or queryset, Django is able to populate the\ncontext using the lowercased version of the model class' name. This is provided\nin addition to the default ``object_list`` entry, but contains exactly the same\ndata, i.e. ``publisher_list``.\n\nIf this still isn't a good match, you can manually set the name of the\ncontext variable. The ``context_object_name`` attribute on a generic view\nspecifies the context variable to use::\n\n    # views.py\n    from django.views.generic import ListView\n    from books.models import Publisher\n\n    class PublisherList(ListView):\n        model = Publisher\n        context_object_name = 'my_favorite_publishers'\n\nProviding a useful ``context_object_name`` is always a good idea. Your\ncoworkers who design templates will thank you.\n\n\n.. _adding-extra-context:\n\nAdding extra context\n--------------------\n\nOften you need to present some extra information beyond that provided by the\ngeneric view. For example, think of showing a list of all the books on each\npublisher detail page. The :class:`~django.views.generic.detail.DetailView`\ngeneric view provides the publisher to the context, but how do we get\nadditional information in that template?\n\nThe answer is to subclass :class:`~django.views.generic.detail.DetailView`\nand provide your own implementation of the ``get_context_data`` method.\nThe default implementation adds the object being displayed to the template, but\nyou can override it to send more::\n\n    from django.views.generic import DetailView\n    from books.models import Book, Publisher\n\n    class PublisherDetail(DetailView):\n\n        model = Publisher\n\n        def get_context_data(self, **kwargs):\n            # Call the base implementation first to get a context\n            context = super().get_context_data(**kwargs)\n            # Add in a QuerySet of all the books\n            context['book_list'] = Book.objects.all()\n            return context\n\n.. note::\n\n    Generally, ``get_context_data`` will merge the context data of all parent\n    classes with those of the current class. To preserve this behavior in your\n    own classes where you want to alter the context, you should be sure to call\n    ``get_context_data`` on the super class. When no two classes try to define the\n    same key, this will give the expected results. However if any class\n    attempts to override a key after parent classes have set it (after the call\n    to super), any children of that class will also need to explicitly set it\n    after super if they want to be sure to override all parents. If you're\n    having trouble, review the method resolution order of your view.\n\n    Another consideration is that the context data from class-based generic\n    views will override data provided by context processors; see\n    :meth:`~django.views.generic.detail.SingleObjectMixin.get_context_data` for\n    an example.\n\n.. _generic-views-list-subsets:\n\nViewing subsets of objects\n--------------------------\n\nNow let's take a closer look at the ``model`` argument we've been\nusing all along. The ``model`` argument, which specifies the database\nmodel that the view will operate upon, is available on all the\ngeneric views that operate on a single object or a collection of\nobjects. However, the ``model`` argument is not the only way to\nspecify the objects that the view will operate upon -- you can also\nspecify the list of objects using the ``queryset`` argument::\n\n    from django.views.generic import DetailView\n    from books.models import Publisher\n\n    class PublisherDetail(DetailView):\n\n        context_object_name = 'publisher'\n        queryset = Publisher.objects.all()\n\nSpecifying ``model = Publisher`` is shorthand for saying ``queryset =\nPublisher.objects.all()``. However, by using ``queryset`` to define a filtered\nlist of objects you can be more specific about the objects that will be visible\nin the view (see :doc:`/topics/db/queries` for more information about\n:class:`~django.db.models.query.QuerySet` objects, and see the\n:doc:`class-based views reference </ref/class-based-views/index>` for the\ncomplete details).\n\nTo pick an example, we might want to order a list of books by publication date,\nwith the most recent first::\n\n    from django.views.generic import ListView\n    from books.models import Book\n\n    class BookList(ListView):\n        queryset = Book.objects.order_by('-publication_date')\n        context_object_name = 'book_list'\n\nThat's a pretty minimal example, but it illustrates the idea nicely. You'll\nusually want to do more than just reorder objects. If you want to present a\nlist of books by a particular publisher, you can use the same technique::\n\n    from django.views.generic import ListView\n    from books.models import Book\n\n    class AcmeBookList(ListView):\n\n        context_object_name = 'book_list'\n        queryset = Book.objects.filter(publisher__name='ACME Publishing')\n        template_name = 'books/acme_list.html'\n\nNotice that along with a filtered ``queryset``, we're also using a custom\ntemplate name. If we didn't, the generic view would use the same template as the\n\"vanilla\" object list, which might not be what we want.\n\nAlso notice that this isn't a very elegant way of doing publisher-specific\nbooks. If we want to add another publisher page, we'd need another handful of\nlines in the URLconf, and more than a few publishers would get unreasonable.\nWe'll deal with this problem in the next section.\n\n.. note::\n\n    If you get a 404 when requesting ``/books/acme/``, check to ensure you\n    actually have a Publisher with the name 'ACME Publishing'.  Generic\n    views have an ``allow_empty`` parameter for this case.  See the\n    :doc:`class-based-views reference</ref/class-based-views/index>` for more\n    details.\n\n\nDynamic filtering\n-----------------\n\nAnother common need is to filter down the objects given in a list page by some\nkey in the URL. Earlier we hard-coded the publisher's name in the URLconf, but\nwhat if we wanted to write a view that displayed all the books by some arbitrary\npublisher?\n\nHandily, the ``ListView`` has a\n:meth:`~django.views.generic.list.MultipleObjectMixin.get_queryset` method we\ncan override. By default, it returns the value of the ``queryset`` attribute,\nbut we can use it to add more logic.\n\nThe key part to making this work is that when class-based views are called,\nvarious useful things are stored on ``self``; as well as the request\n(``self.request``) this includes the positional (``self.args``) and name-based\n(``self.kwargs``) arguments captured according to the URLconf.\n\nHere, we have a URLconf with a single captured group::\n\n    # urls.py\n    from django.urls import path\n    from books.views import PublisherBookList\n\n    urlpatterns = [\n        path('books/<publisher>/', PublisherBookList.as_view()),\n    ]\n\nNext, we'll write the ``PublisherBookList`` view itself::\n\n    # views.py\n    from django.shortcuts import get_object_or_404\n    from django.views.generic import ListView\n    from books.models import Book, Publisher\n\n    class PublisherBookList(ListView):\n\n        template_name = 'books/books_by_publisher.html'\n\n        def get_queryset(self):\n            self.publisher = get_object_or_404(Publisher, name=self.kwargs['publisher'])\n            return Book.objects.filter(publisher=self.publisher)\n\nUsing ``get_queryset`` to add logic to the queryset selection is as convenient\nas it is powerful. For instance, if we wanted, we could use\n``self.request.user`` to filter using the current user, or other more complex\nlogic.\n\nWe can also add the publisher into the context at the same time, so we can\nuse it in the template::\n\n        # ...\n\n        def get_context_data(self, **kwargs):\n            # Call the base implementation first to get a context\n            context = super().get_context_data(**kwargs)\n            # Add in the publisher\n            context['publisher'] = self.publisher\n            return context\n\n.. _generic-views-extra-work:\n\nPerforming extra work\n---------------------\n\nThe last common pattern we'll look at involves doing some extra work before\nor after calling the generic view.\n\nImagine we had a ``last_accessed`` field on our ``Author`` model that we were\nusing to keep track of the last time anybody looked at that author::\n\n    # models.py\n    from django.db import models\n\n    class Author(models.Model):\n        salutation = models.CharField(max_length=10)\n        name = models.CharField(max_length=200)\n        email = models.EmailField()\n        headshot = models.ImageField(upload_to='author_headshots')\n        last_accessed = models.DateTimeField()\n\nThe generic ``DetailView`` class wouldn't know anything about this field, but\nonce again we could write a custom view to keep that field updated.\n\nFirst, we'd need to add an author detail bit in the URLconf to point to a\ncustom view::\n\n    from django.urls import path\n    from books.views import AuthorDetailView\n\n    urlpatterns = [\n        #...\n        path('authors/<int:pk>/', AuthorDetailView.as_view(), name='author-detail'),\n    ]\n\nThen we'd write our new view -- ``get_object`` is the method that retrieves the\nobject -- so we override it and wrap the call::\n\n    from django.utils import timezone\n    from django.views.generic import DetailView\n    from books.models import Author\n\n    class AuthorDetailView(DetailView):\n\n        queryset = Author.objects.all()\n\n        def get_object(self):\n            obj = super().get_object()\n            # Record the last accessed date\n            obj.last_accessed = timezone.now()\n            obj.save()\n            return obj\n\n.. note::\n\n    The URLconf here uses the named group ``pk`` - this name is the default\n    name that ``DetailView`` uses to find the value of the primary key used to\n    filter the queryset.\n\n    If you want to call the group something else, you can set ``pk_url_kwarg``\n    on the view. More details can be found in the reference for\n    :class:`~django.views.generic.detail.DetailView`\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":340,"nodeType":"TextFile","repoName":null,"name":"intro.txt","path":"docs/topics/class-based-views","text":"=================================\nIntroduction to class-based views\n=================================\n\nClass-based views provide an alternative way to implement views as Python\nobjects instead of functions. They do not replace function-based views, but\nhave certain differences and advantages when compared to function-based views:\n\n* Organization of code related to specific HTTP methods (``GET``, ``POST``,\n  etc.) can be addressed by separate methods instead of conditional branching.\n\n* Object oriented techniques such as mixins (multiple inheritance) can be\n  used to factor code into reusable components.\n\nThe relationship and history of generic views, class-based views, and class-based generic views\n===============================================================================================\n\nIn the beginning there was only the view function contract, Django passed your\nfunction an :class:`~django.http.HttpRequest` and expected back an\n:class:`~django.http.HttpResponse`. This was the extent of what Django provided.\n\nEarly on it was recognized that there were common idioms and patterns found in\nview development. Function-based generic views were introduced to abstract\nthese patterns and ease view development for the common cases.\n\nThe problem with function-based generic views is that while they covered the\nsimple cases well, there was no way to extend or customize them beyond some\nconfiguration options, limiting their usefulness in many real-world\napplications.\n\nClass-based generic views were created with the same objective as\nfunction-based generic views, to make view development easier. However, the way\nthe solution is implemented, through the use of mixins, provides a toolkit that\nresults in class-based generic views being more extensible and flexible than\ntheir function-based counterparts.\n\nIf you have tried function based generic views in the past and found them\nlacking, you should not think of class-based generic views as a class-based\nequivalent, but rather as a fresh approach to solving the original problems\nthat generic views were meant to solve.\n\nThe toolkit of base classes and mixins that Django uses to build class-based\ngeneric views are built for maximum flexibility, and as such have many hooks in\nthe form of default method implementations and attributes that you are unlikely\nto be concerned with in the simplest use cases. For example, instead of\nlimiting you to a class-based attribute for ``form_class``, the implementation\nuses a ``get_form`` method, which calls a ``get_form_class`` method, which in\nits default implementation returns the ``form_class`` attribute of the class.\nThis gives you several options for specifying what form to use, from an\nattribute, to a fully dynamic, callable hook. These options seem to add hollow\ncomplexity for simple situations, but without them, more advanced designs would\nbe limited.\n\nUsing class-based views\n=======================\n\nAt its core, a class-based view allows you to respond to different HTTP request\nmethods with different class instance methods, instead of with conditionally\nbranching code inside a single view function.\n\nSo where the code to handle HTTP ``GET`` in a view function would look\nsomething like::\n\n    from django.http import HttpResponse\n\n    def my_view(request):\n        if request.method == 'GET':\n            # <view logic>\n            return HttpResponse('result')\n\nIn a class-based view, this would become::\n\n    from django.http import HttpResponse\n    from django.views import View\n\n    class MyView(View):\n        def get(self, request):\n            # <view logic>\n            return HttpResponse('result')\n\nBecause Django's URL resolver expects to send the request and associated\narguments to a callable function, not a class, class-based views have an\n:meth:`~django.views.generic.base.View.as_view` class method which returns a\nfunction that can be called when a request arrives for a URL matching the\nassociated pattern. The function creates an instance of the class, calls\n:meth:`~django.views.generic.base.View.setup` to initialize its attributes, and\nthen calls its :meth:`~django.views.generic.base.View.dispatch` method.\n``dispatch`` looks at the request to determine whether it is a ``GET``,\n``POST``, etc, and relays the request to a matching method if one is defined,\nor raises :class:`~django.http.HttpResponseNotAllowed` if not::\n\n    # urls.py\n    from django.urls import path\n    from myapp.views import MyView\n\n    urlpatterns = [\n        path('about/', MyView.as_view()),\n    ]\n\n\nIt is worth noting that what your method returns is identical to what you\nreturn from a function-based view, namely some form of\n:class:`~django.http.HttpResponse`. This means that\n:doc:`http shortcuts </topics/http/shortcuts>` or\n:class:`~django.template.response.TemplateResponse` objects are valid to use\ninside a class-based view.\n\nWhile a minimal class-based view does not require any class attributes to\nperform its job, class attributes are useful in many class-based designs,\nand there are two ways to configure or set class attributes.\n\nThe first is the standard Python way of subclassing and overriding attributes\nand methods in the subclass. So that if your parent class had an attribute\n``greeting`` like this::\n\n    from django.http import HttpResponse\n    from django.views import View\n\n    class GreetingView(View):\n        greeting = \"Good Day\"\n\n        def get(self, request):\n            return HttpResponse(self.greeting)\n\nYou can override that in a subclass::\n\n    class MorningGreetingView(GreetingView):\n        greeting = \"Morning to ya\"\n\nAnother option is to configure class attributes as keyword arguments to the\n:meth:`~django.views.generic.base.View.as_view` call in the URLconf::\n\n    urlpatterns = [\n        path('about/', GreetingView.as_view(greeting=\"G'day\")),\n    ]\n\n.. note::\n\n    While your class is instantiated for each request dispatched to it, class\n    attributes set through the\n    :meth:`~django.views.generic.base.View.as_view` entry point are\n    configured only once at the time your URLs are imported.\n\nUsing mixins\n============\n\nMixins are a form of multiple inheritance where behaviors and attributes of\nmultiple parent classes can be combined.\n\nFor example, in the generic class-based views there is a mixin called\n:class:`~django.views.generic.base.TemplateResponseMixin` whose primary purpose\nis to define the method\n:meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`.\nWhen combined with the behavior of the :class:`~django.views.generic.base.View`\nbase class, the result is a :class:`~django.views.generic.base.TemplateView`\nclass that will dispatch requests to the appropriate matching methods (a\nbehavior defined in the ``View`` base class), and that has a\n:meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`\nmethod that uses a\n:attr:`~django.views.generic.base.TemplateResponseMixin.template_name`\nattribute to return a :class:`~django.template.response.TemplateResponse`\nobject (a behavior defined in the ``TemplateResponseMixin``).\n\nMixins are an excellent way of reusing code across multiple classes, but they\ncome with some cost. The more your code is scattered among mixins, the harder\nit will be to read a child class and know what exactly it is doing, and the\nharder it will be to know which methods from which mixins to override if you\nare subclassing something that has a deep inheritance tree.\n\nNote also that you can only inherit from one generic view - that is, only one\nparent class may inherit from :class:`~django.views.generic.base.View` and\nthe rest (if any) should be mixins. Trying to inherit from more than one class\nthat inherits from ``View`` - for example, trying to use a form at the top of a\nlist and combining :class:`~django.views.generic.edit.ProcessFormView` and\n:class:`~django.views.generic.list.ListView` - won't work as expected.\n\n\nHandling forms with class-based views\n=====================================\n\nA basic function-based view that handles forms may look something like this::\n\n    from django.http import HttpResponseRedirect\n    from django.shortcuts import render\n\n    from .forms import MyForm\n\n    def myview(request):\n        if request.method == \"POST\":\n            form = MyForm(request.POST)\n            if form.is_valid():\n                # <process form cleaned data>\n                return HttpResponseRedirect('/success/')\n        else:\n            form = MyForm(initial={'key': 'value'})\n\n        return render(request, 'form_template.html', {'form': form})\n\nA similar class-based view might look like::\n\n    from django.http import HttpResponseRedirect\n    from django.shortcuts import render\n    from django.views import View\n\n    from .forms import MyForm\n\n    class MyFormView(View):\n        form_class = MyForm\n        initial = {'key': 'value'}\n        template_name = 'form_template.html'\n\n        def get(self, request, *args, **kwargs):\n            form = self.form_class(initial=self.initial)\n            return render(request, self.template_name, {'form': form})\n\n        def post(self, request, *args, **kwargs):\n            form = self.form_class(request.POST)\n            if form.is_valid():\n                # <process form cleaned data>\n                return HttpResponseRedirect('/success/')\n\n            return render(request, self.template_name, {'form': form})\n\nThis is a minimal case, but you can see that you would then have the option\nof customizing this view by overriding any of the class attributes, e.g.\n``form_class``, via URLconf configuration, or subclassing and overriding one or\nmore of the methods (or both!).\n\nDecorating class-based views\n============================\n\nThe extension of class-based views isn't limited to using mixins. You can also\nuse decorators. Since class-based views aren't functions, decorating them works\ndifferently depending on if you're using ``as_view()`` or creating a subclass.\n\nDecorating in URLconf\n---------------------\n\nYou can adjust class-based views by decorating the result of the\n:meth:`~django.views.generic.base.View.as_view` method. The easiest place to do\nthis is in the URLconf where you deploy your view::\n\n    from django.contrib.auth.decorators import login_required, permission_required\n    from django.views.generic import TemplateView\n\n    from .views import VoteView\n\n    urlpatterns = [\n        path('about/', login_required(TemplateView.as_view(template_name=\"secret.html\"))),\n        path('vote/', permission_required('polls.can_vote')(VoteView.as_view())),\n    ]\n\nThis approach applies the decorator on a per-instance basis. If you\nwant every instance of a view to be decorated, you need to take a\ndifferent approach.\n\n.. _decorating-class-based-views:\n\nDecorating the class\n--------------------\n\nTo decorate every instance of a class-based view, you need to decorate\nthe class definition itself. To do this you apply the decorator to the\n:meth:`~django.views.generic.base.View.dispatch` method of the class.\n\nA method on a class isn't quite the same as a standalone function, so you can't\njust apply a function decorator to the method -- you need to transform it into\na method decorator first. The ``method_decorator`` decorator transforms a\nfunction decorator into a method decorator so that it can be used on an\ninstance method. For example::\n\n    from django.contrib.auth.decorators import login_required\n    from django.utils.decorators import method_decorator\n    from django.views.generic import TemplateView\n\n    class ProtectedView(TemplateView):\n        template_name = 'secret.html'\n\n        @method_decorator(login_required)\n        def dispatch(self, *args, **kwargs):\n            return super().dispatch(*args, **kwargs)\n\nOr, more succinctly, you can decorate the class instead and pass the name\nof the method to be decorated as the keyword argument ``name``::\n\n    @method_decorator(login_required, name='dispatch')\n    class ProtectedView(TemplateView):\n        template_name = 'secret.html'\n\nIf you have a set of common decorators used in several places, you can define\na list or tuple of decorators and use this instead of invoking\n``method_decorator()`` multiple times. These two classes are equivalent::\n\n    decorators = [never_cache, login_required]\n\n    @method_decorator(decorators, name='dispatch')\n    class ProtectedView(TemplateView):\n        template_name = 'secret.html'\n\n    @method_decorator(never_cache, name='dispatch')\n    @method_decorator(login_required, name='dispatch')\n    class ProtectedView(TemplateView):\n        template_name = 'secret.html'\n\nThe decorators will process a request in the order they are passed to the\ndecorator. In the example, ``never_cache()`` will process the request before\n``login_required()``.\n\nIn this example, every instance of ``ProtectedView`` will have login\nprotection. These examples use ``login_required``, however, the same behavior\ncan be obtained by using\n:class:`~django.contrib.auth.mixins.LoginRequiredMixin`.\n\n.. note::\n\n    ``method_decorator`` passes ``*args`` and ``**kwargs``\n    as parameters to the decorated method on the class. If your method\n    does not accept a compatible set of parameters it will raise a\n    ``TypeError`` exception.\n","fileName":null,"filePath":null,"col":null,"comment":null,"endLoc":null,"header":null,"startLoc":null,"attributeType":null,"className":null},{"groupName":null,"id":341,"nodeType":"TextFile","repoName":null,"name":"translation.txt","path":"docs/topics/i18n","text":"===========\nTranslation\n===========\n\n.. currentmodule:: django.utils.translation\n\nOverview\n========\n\nIn order to make a Django project translatable, you have to add a minimal\nnumber of hooks to your Python code and templates. These hooks are called\n:term:`translation strings <translation string>`. They tell Django: \"This text\nshould be translated into the end user's language, if a translation for this\ntext is available in that language.\" It's your responsibility to mark\ntranslatable strings; the system can only translate strings it knows about.\n\nDjango then provides utilities to extract the translation strings into a\n:term:`message file`. This file is a convenient way for translators to provide\nthe equivalent of the translation strings in the target language. Once the\ntranslators have filled in the message file, it must be compiled. This process\nrelies on the GNU gettext toolset.\n\nOnce this is done, Django takes care of translating Web apps on the fly in each\navailable language, according to users' language preferences.\n\nDjango's internationalization hooks are on by default, and that means there's a\nbit of i18n-related overhead in certain places of the framework. If you don't\nuse internationalization, you should take the two seconds to set\n:setting:`USE_I18N = False <USE_I18N>` in your settings file. Then Django will\nmake some optimizations so as not to load the internationalization machinery.\n\n.. note::\n\n    There is also an independent but related :setting:`USE_L10N` setting that\n    controls if Django should implement format localization. See\n    :doc:`/topics/i18n/formatting` for more details.\n\n.. note::\n\n    Make sure you've activated translation for your project (the fastest way is\n    to check if :setting:`MIDDLEWARE` includes\n    :mod:`django.middleware.locale.LocaleMiddleware`). If you haven't yet,\n    see :ref:`how-django-discovers-language-preference`.\n\nInternationalization: in Python code\n====================================\n\nStandard translation\n--------------------\n\nSpecify a translation string by using the function\n:func:`~django.utils.translation.gettext`. It's convention to import this\nas a shorter alias, ``_``, to save typing.\n\n.. note::\n    Python's standard library ``gettext`` module installs ``_()`` into the\n    global namespace, as an alias for ``gettext()``. In Django, we have chosen\n    not to follow this practice, for a couple of reasons:\n\n    #. Sometimes, you should use :func:`~django.utils.translation.gettext_lazy`\n       as the default translation method for a particular file. Without ``_()``\n       in the global namespace, the developer has to think about which is the\n       most appropriate translation function.\n\n    #. The underscore character (``_``) is used to represent \"the previous\n       result\" in Python's interactive shell and doctest tests. Installing a\n       global ``_()`` function causes interference. Explicitly importing\n       ``gettext()`` as ``_()`` avoids this problem.\n\n.. admonition:: What functions may be aliased as ``_``?\n\n    Because of how ``xgettext`` (used by :djadmin:`makemessages`) works, only\n    functions that take a single string argument can be imported as ``_``:\n\n    * :func:`~django.utils.translation.gettext`\n    * :func:`~django.utils.translation.gettext_lazy`\n\nIn this example, the text ``\"Welcome to my site.\"`` is marked as a translation\nstring::\n\n    from django.http import HttpResponse\n    from django.utils.translation import gettext as _\n\n    def my_view(request):\n        output = _(\"Welcome to my site.\")\n        return HttpResponse(output)\n\nYou could code this without using the alias. This example is identical to the\nprevious one::\n\n    from django.http import HttpResponse\n    from django.utils.translation import gettext\n\n    def my_view(request):\n        output = gettext(\"Welcome to my site.\")\n        return HttpResponse(output)\n\nTranslation works on computed values. This example is identical to the previous\ntwo::\n\n    def my_view(request):\n        words = ['Welcome', 'to', 'my', 'site.']\n        output = _(' '.join(words))\n        return HttpResponse(output)\n\nTranslation works on variables. Again, here's an identical example::\n\n    def my_view(request):\n        sentence = 'Welcome to my site.'\n        output = _(sentence)\n        return HttpResponse(output)\n\n(The caveat with using variables or computed values, as in the previous two\nexamples, is that Django's translation-string-detecting utility,\n:djadmin:`django-admin makemessages <makemessages>`, won't be able to find\nthese strings. More on :djadmin:`makemessages` later.)\n\nThe strings you pass to ``_()`` or ``gettext()`` can take placeholders,\nspecified with Python's standard named-string interpolation syntax. Example::\n\n    def my_view(request, m, d):\n        output = _('Today is %(month)s %(day)s.') % {'month': m, 'day': d}\n        return HttpResponse(output)\n\nThis technique lets language-specific translations reorder the placeholder\ntext. For example, an English translation may be ``\"Today is November 26.\"``,\nwhile a Spanish translation may be ``\"Hoy es 26 de noviembre.\"`` -- with the\nmonth and the day placeholders swapped.\n\nFor this reason, you should use named-string interpolation (e.g., ``%(day)s``)\ninstead of positional interpolation (e.g., ``%s`` or ``%d``) whenever you\nhave more than a single parameter. If you used positional interpolation,\ntranslations wouldn't be able to reorder placeholder text.\n\nSince string extraction is done by the ``xgettext`` command, only syntaxes\nsupported by ``gettext`` are supported by Django. In particular, Python\n:py:ref:`f-strings <f-strings>` are not yet supported by ``xgettext``, and\nJavaScript template strings need ``gettext`` 0.21+.\n\n.. _translator-comments:\n\nComments for translators\n------------------------\n\nIf you would like to give translators hints about a translatable string, you\ncan add a comment prefixed with the ``Translators`` keyword on the line\npreceding the string, e.g.::\n\n    def my_view(request):\n        # Translators: This message appears on the home page only\n        output = gettext(\"Welcome to my site.\")\n\nThe comment will then appear in the resulting ``.po`` file associated with the\ntranslatable construct located below it and should also be displayed by most\ntranslation tools.\n\n.. note:: Just for completeness, this is the corresponding fragment of the\n    resulting ``.po`` file:\n\n    .. code-block:: po\n\n        #. Translators: This message appears on the home page only\n        # path/to/python/file.py:123\n        msgid \"Welcome to my site.\"\n        msgstr \"\"\n\nThis also works in templates. See :ref:`translator-comments-in-templates` for\nmore details.\n\nMarking strings as no-op\n------------------------\n\nUse the function :func:`django.utils.translation.gettext_noop()` to mark a\nstring as a translation string without translating it. The string is later\ntranslated from a variable.\n\nUse this if you have constant strings that should be stored in the source\nlanguage because they are exchanged over systems or users -- such as strings\nin a database -- but should be translated at the last possible point in time,\nsuch as when the string is presented to the user.\n\nPluralization\n-------------\n\nUse the function :func:`django.utils.translation.ngettext()` to specify\npluralized messages.\n\n``ngettext()`` takes three arguments: the singular translation string, the\nplural translation string and the number of objects.\n\nThis function is useful when you need your Django application to be localizable\nto languages where the number and complexity of `plural forms\n<https://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms>`_ is\ngreater than the two forms used in English ('object' for the singular and\n'objects' for all the cases where ``count`` is different from one, irrespective\nof its value.)\n\nFor example::\n\n    from django.http import HttpResponse\n    from django.utils.translation import ngettext\n\n    def hello_world(request, count):\n        page = ngettext(\n            'there is %(count)d object',\n            'there are %(count)d objects',\n        count) % {\n            'count': count,\n        }\n        return HttpResponse(page)\n\nIn this example the number of objects is passed to the translation\nlanguages as the ``count`` variable.\n\nNote that pluralization is complicated and works differently in each language.\nComparing ``count`` to 1 isn't always the correct rule. This code looks\nsophisticated, but will produce incorrect results for some languages::\n\n    from django.utils.translation import ngettext\n    from myapp.models import Report\n\n    count = Report.objects.count()\n    if count == 1:\n        name = Report._meta.verbose_name\n    else:\n        name = Report._meta.verbose_name_plural\n\n    text = ngettext(\n        'There is %(count)d %(name)s available.',\n        'There are %(count)d %(name)s available.',\n        count\n    ) % {\n        'count': count,\n        'name': name\n    }\n\nDon't try to implement your own singular-or-plural logic; it won't be correct.\nIn a case like this, consider something like the following::\n\n    text = ngettext(\n        'There is %(count)d %(name)s object available.',\n        'There are %(count)d %(name)s objects available.',\n        count\n    ) % {\n        'count': count,\n        'name': Report._meta.verbose_name,\n    }\n\n.. _pluralization-var-notes:\n\n.. note::\n\n    When using ``ngettext()``, make sure you use a single name for every\n    extrapolated variable included in the literal. In the examples above, note\n    how we used the ``name`` Python variable in both translation strings. This\n    example, besides being incorrect in some languages as noted above, would\n    fail::\n\n        text = ngettext(\n            'There is %(count)d %(name)s available.',\n            'There are %(count)d %(plural_name)s available.',\n            count\n        ) % {\n            'count': Report.objects.count(),\n            'name': Report._meta.verbose_name,\n            'plural_name': Report._meta.verbose_name_plural\n        }\n\n    You would get an error when running :djadmin:`django-admin\n    compilemessages <compilemessages>`::\n\n        a format specification for argument 'name', as in 'msgstr[0]', doesn't exist in 'msgid'\n\n.. versionchanged: 2.2.12\n\n    Added support for different plural equations in ``.po`` files.\n\n.. _contextual-markers:\n\nContextual markers\n------------------\n\nSometimes words have several meanings, such as ``\"May\"`` in English, which\nrefers to a month name and to a verb. To enable translators to translate\nthese words correctly in different contexts, you can use the\n:func:`django.utils.translation.pgettext()` function, or the\n:func:`django.utils.translation.npgettext()` function if the string needs\npluralization. Both take a context string as the first variable.\n\nIn the resulting ``.po`` file, the string will then appear as often as there are\ndifferent contextual markers for the same string (the context will appear on the\n``msgctxt`` line), allowing the translator to give a different translation for\neach of them.\n\nFor example::\n\n    from django.utils.translation import pgettext\n\n    month = pgettext(\"month name\", \"May\")\n\nor::\n\n    from django.db import models\n    from django.utils.translation import pgettext_lazy\n\n    class MyThing(models.Model):\n        name = models.CharField(help_text=pgettext_lazy(\n            'help text for MyThing model', 'This is the help text'))\n\nwill appear in the ``.po`` file as:\n\n.. code-block:: po\n\n    msgctxt \"month name\"\n    msgid \"May\"\n    msgstr \"\"\n\nContextual markers are also supported by the :ttag:`translate` and\n:ttag:`blocktranslate` template tags.\n\n.. _lazy-translations:\n\nLazy translation\n----------------\n\nUse the lazy versions of translation functions in\n:mod:`django.utils.translation` (easily recognizable by the ``lazy`` suffix in\ntheir names) to translate strings lazily -- when the value is accessed rather\nthan when they're called.\n\nThese functions store a lazy reference to the string -- not the actual\ntranslation. The translation itself will be done when the string is used in a\nstring context, such as in template rendering.\n\nThis is essential when calls to these functions are located in code paths that\nare executed at module load time.\n\nThis is something that can easily happen when defining models, forms and\nmodel forms, because Django implements these such that their fields are\nactually class-level attributes. For that reason, make sure to use lazy\ntranslations in the following cases:\n\nModel fields and relationships ``verbose_name`` and ``help_text`` option values\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nFor example, to translate the help text of the *name* field in the following\nmodel, do the following::\n\n    from django.db import models\n    from django.utils.translation import gettext_lazy as _\n\n    class MyThing(models.Model):\n        name = models.CharField(help_text=_('This is the help text'))\n\nYou can mark names of :class:`~django.db.models.ForeignKey`,\n:class:`~django.db.models.ManyToManyField` or\n:class:`~django.db.models.OneToOneField` relationship as translatable by using\ntheir :attr:`~django.db.models.Options.verbose_name` options::\n\n    class MyThing(models.Model):\n        kind = models.ForeignKey(\n            ThingKind,\n            on_delete=models.CASCADE,\n            related_name='kinds',\n            verbose_name=_('kind'),\n        )\n\nJust like you would do in :attr:`~django.db.models.Options.verbose_name` you\nshould provide a lowercase verbose name text for the relation as Django will\nautomatically titlecase it when required.\n\nModel verbose names values\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIt is recommended to always provide explicit\n:attr:`~django.db.models.Options.verbose_name` and\n:attr:`~django.db.models.Options.verbose_name_plural` options rather than\nrelying on the fallback English-centric and somewhat naïve determination of\nverbose names Django performs by looking at the model's class name::\n\n    from django.db import models\n    from django.utils.translation import gettext_lazy as _\n\n    class MyThing(models.Model):\n        name = models.CharField(_('name'), help_text=_('This is the help text'))\n\n        class Meta:\n            verbose_name = _('my thing')\n            verbose_name_plural = _('my things')\n\nModel methods ``short_description`` attribute values\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nFor model methods, you can provide translations to Django and the admin site\nwith the ``short_description`` attribute::\n\n    from django.db import models\n    from django.utils.translation import gettext_lazy as _\n\n    class MyThing(models.Model):\n        kind = models.ForeignKey(\n            ThingKind,\n            on_delete=models.CASCADE,\n            related_name='kinds',\n            verbose_name=_('kind'),\n        )\n\n        def is_mouse(self):\n            return self.kind.type == MOUSE_TYPE\n        is_mouse.short_description = _('Is it a mouse?')\n\nWorking with lazy translation objects\n-------------------------------------\n\nThe result of a ``gettext_lazy()`` call can be used wherever you would use a\nstring (a :class:`str` object) in other Django code, but it may not work with\narbitrary Python code. For example, the following won't work because the\n`requests <https://pypi.org/project/requests/>`_ library doesn't handle\n``gettext_lazy`` objects::\n\n    body = gettext_lazy(\"I \\u2764 Django\")  # (Unicode :heart:)\n    requests.post('https://example.com/send', data={'body': body})\n\nYou can avoid such problems by casting ``gettext_lazy()`` objects to text\nstrings before passing them to non-Django code::\n\n    requests.post('https://example.com/send', data={'body': str(body)})\n\nIf you don't like the long ``gettext_lazy`` name, you can alias it as ``_``\n(underscore), like so::\n\n    from django.db import models\n    from django.utils.translation import gettext_lazy as _\n\n    class MyThing(models.Model):\n        name = models.CharField(help_text=_('This is the help text'))\n\nUsing ``gettext_lazy()`` and ``ngettext_lazy()`` to mark strings in models\nand utility functions is a common operation. When you're working with these\nobjects elsewhere in your code, you should ensure that you don't accidentally\nconvert them to strings, because they should be converted as late as possible\n(so that the correct locale is in effect). This necessitates the use of the\nhelper function described next.\n\n.. _lazy-plural-translations:\n\nLazy translations and plural\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nWhen using lazy translation for a plural string (``[u]n[p]gettext_lazy``), you\ngenerally don't know the ``number`` argument at the time of the string\ndefinition. Therefore, you are authorized to pass a key name instead of an\ninteger as the ``number`` argument. Then ``number`` will be looked up in the\ndictionary under that key during string interpolation. Here's example::\n\n    from django import forms\n    from django.core.exceptions import ValidationError\n    from django.utils.translation import ngettext_lazy\n\n    class MyForm(forms.Form):\n        error_message = ngettext_lazy(\"You only provided %(num)d argument\",\n            \"You only provided %(num)d arguments\", 'num')\n\n        def clean(self):\n            # ...\n            if error:\n                raise ValidationError(self.error_message % {'num': number})\n\nIf the string contains exactly one unnamed placeholder, you can interpolate\ndirectly with the ``number`` argument::\n\n    class MyForm(forms.Form):\n        error_message = ngettext_lazy(\n            \"You provided %d argument\",\n            \"You provided %d arguments\",\n        )\n\n        def clean(self):\n            # ...\n            if error:\n                raise ValidationError(self.error_message % number)\n\n\nFormatting strings: ``format_lazy()``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nPython's :meth:`str.format()` method will not work when either the\n``format_string`` or any of the arguments to :meth:`str.format()`\ncontains lazy translation objects. Instead, you can use\n:func:`django.utils.text.format_lazy()`, which creates a lazy object\nthat runs the ``str.format()`` method only when the result is included\nin a string. For example::\n\n    from django.utils.text import format_lazy\n    from django.utils.translation import gettext_lazy\n    ...\n    name = gettext_lazy('John Lennon')\n    instrument = gettext_lazy('guitar')\n    result = format_lazy('{name}: {instrument}', name=name, instrument=instrument)\n\nIn this case, the lazy translations in ``result`` will only be converted to\nstrings when ``result`` itself is used in a string (usually at template\nrendering time).\n\nOther uses of lazy in delayed translations\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nFor any other case where you would like to delay the translation, but have to\npass the translatable string as argument to another function, you can wrap\nthis function inside a lazy call yourself. For example::\n\n    from django.utils.functional import lazy\n    from django.utils.safestring import mark_safe\n    from django.utils.translation import gettext_lazy as _\n\n    mark_safe_lazy = lazy(mark_safe, str)\n\nAnd then later::\n\n    lazy_string = mark_safe_lazy(_(\"<p>My <strong>string!</strong></p>\"))\n\nLocalized names of languages\n----------------------------\n\n.. function:: get_language_info\n\nThe ``get_language_info()`` function provides detailed information about\nlanguages::\n\n    >>> from django.utils.translation import activate, get_language_info\n    >>> activate('fr')\n    >>> li = get_language_info('de')\n    >>> print(li['name'], li['name_local'], li['name_translated'], li['bidi'])\n    German Deutsch Allemand False\n\nThe ``name``, ``name_local``, and ``name_translated`` attributes of the\ndictionary contain the name of the language in English, in the language\nitself, and in your current active language respectively.  The ``bidi``\nattribute is True only for bi-directional languages.\n\nThe source of the language information is the ``django.conf.locale`` module.\nSimilar access to this information is available for template code. See below.\n\n.. _specifying-translation-strings-in-template-code:\n\nInternationalization: in template code\n======================================\n\n.. highlight:: html+django\n\nTranslations in :doc:`Django templates </ref/templates/language>` uses two template\ntags and a slightly different syntax than in Python code. To give your template\naccess to these tags, put ``{% load i18n %}`` toward the top of your template.\nAs with all template tags, this tag needs to be loaded in all templates which\nuse translations, even those templates that extend from other templates which\nhave already loaded the ``i18n`` tag.\n\n.. warning::\n\n    Translated strings will not be escaped when rendered in a template.\n    This allows you to include HTML in translations, for example for emphasis,\n    but potentially dangerous characters (e.g. ``\"``) will also be rendered\n    unchanged.\n\n.. templatetag:: trans\n.. templatetag:: translate\n\n``translate`` template tag\n--------------------------\n\nThe ``{% translate %}`` template tag translates either a constant string\n(enclosed in single or double quotes) or variable content::\n\n    <title>{% translate \"This is the title.\" %}</title>\n    <title>{% translate myvar %}</title>\n\nIf the ``noop`` option is present, variable lookup still takes place but the\ntranslation is skipped. This is useful when \"stubbing out\" content that will\nrequire translation in the future::\n\n    <title>{% translate \"myvar\" noop %}</title>\n\nInternally, inline translations use an\n:func:`~django.utils.translation.gettext` call.\n\nIn case a template var (``myvar`` above) is passed to the tag, the tag will\nfirst resolve such variable to a string at run-time and then look up that\nstring in the message catalogs.\n\nIt's not possible to mix a template variable inside a string within\n``{% translate %}``. If your translations require strings with variables\n(placeholders), use :ttag:`{% blocktranslate %}<blocktranslate>` instead.\n\nIf you'd like to retrieve a translated string without displaying it, you can\nuse the following syntax::\n\n    {% translate \"This is the title\" as the_title %}\n\n    <title>{{ the_title }}</title>\n    <meta name=\"description\" content=\"{{ the_title }}\">\n\nIn practice you'll use this to get a string you can use in multiple places in a\ntemplate or so you can use the output as an argument for other template tags or\nfilters::\n\n    {% translate \"starting point\" as start %}\n    {% translate \"end point\" as end %}\n    {% translate \"La Grande Boucle\" as race %}\n\n    <h1>\n      <a href=\"/\" title=\"{% blocktranslate %}Back to '{{ race }}' homepage{% endblocktranslate %}\">{{ race }}</a>\n    </h1>\n    <p>\n    {% for stage in tour_stages %}\n        {% cycle start end %}: {{ stage }}{% if forloop.counter|divisibleby:2 %}<br>{% else %}, {% endif %}\n    {% endfor %}\n    </p>\n\n``{% translate %}`` also supports :ref:`contextual markers<contextual-markers>`\nusing the ``context`` keyword:\n\n.. code-block:: html+django\n\n    {% translate \"May\" context \"month name\" %}\n\n.. versionchanged:: 3.1\n\n   The ``trans`` tag was renamed to ``translate``.  The ``trans``\n   tag is still supported as an alias for backwards compatibility.\n\n.. templatetag:: blocktrans\n.. templatetag:: blocktranslate\n\n``blocktranslate`` template tag\n-------------------------------\n\nContrarily to the :ttag:`translate` tag, the ``blocktranslate`` tag allows you\nto mark complex sentences consisting of literals and variable content for\ntranslation by making use of placeholders::\n\n    {% blocktranslate %}This string will have {{ value }} inside.{% endblocktranslate %}\n\nTo translate a template expression -- say, accessing object attributes or\nusing template filters -- you need to bind the expression to a local variable\nfor use within the translation block. Examples::\n\n    {% blocktranslate with amount=article.price %}\n    That will cost $ {{ amount }}.\n    {% endblocktranslate %}\n\n    {% blocktranslate with myvar=value|filter %}\n    This will have {{ myvar }} inside.\n    {% endblocktranslate %}\n\nYou can use multiple expressions inside a single ``blocktranslate`` tag::\n\n    {% blocktranslate with book_t=book|title author_t=author|title %}\n    This is {{ book_t }} by {{ author_t }}\n    {% endblocktranslate %}\n\n.. note:: The previous more verbose format is still supported:\n   ``{% blocktranslate with book|title as book_t and author|title as author_t %}``\n\nOther block tags (for example ``{% for %}`` or ``{% if %}``) are not allowed\ninside a ``blocktranslate`` tag.\n\nIf resolving one of the block arguments fails, ``blocktranslate`` will fall\nback to the default language by deactivating the currently active language\ntemporarily with the :func:`~django.utils.translation.deactivate_all`\nfunction.\n\nThis tag also provides for pluralization. To use it:\n\n* Designate and bind a counter value with the name ``count``. This value will\n  be the one used to select the right plural form.\n\n* Specify both the singular and plural forms separating them with the\n  ``{% plural %}`` tag within the ``{% blocktranslate %}`` and\n  ``{% endblocktranslate %}`` tags.\n\nAn example::\n\n    {% blocktranslate count counter=list|length %}\n    There is only one {{ name }} object.\n    {% plural %}\n    There are {{ counter }} {{ name }} objects.\n    {% endblocktranslate %}\n\nA more complex example::\n\n    {% blocktranslate with amount=article.price count years=i.length %}\n    That will cost $ {{ amount }} per year.\n    {% plural %}\n    That will cost $ {{ amount }} per {{ years }} years.\n    {% endblocktranslate %}\n\nWhen you use both the pluralization feature and bind values to local variables\nin addition to the counter value, keep in mind that the ``blocktranslate``\nconstruct is internally converted to an ``ngettext`` call. This means the\nsame :ref:`notes regarding ngettext variables <pluralization-var-notes>`\napply.\n\nReverse URL lookups cannot be carried out within the ``blocktranslate`` and\nshould be retrieved (and stored) beforehand::\n\n    {% url 'path.to.view' arg arg2 as the_url %}\n    {% blocktranslate %}\n    This is a URL: {{ the_url }}\n    {% endblocktranslate %}\n\nIf you'd like to retrieve a translated string without displaying it, you can\nuse the following syntax::\n\n    {% blocktranslate asvar the_title %}The title is {{ title }}.{% endblocktranslate %}\n    <title>{{ the_title }}</title>\n    <meta name=\"description\" content=\"{{ the_title }}\">\n\nIn practice you'll use this to get a string you can use in multiple places in a\ntemplate or so you can use the output as an argument for other template tags or\nfilters.\n\n``{% blocktranslate %}`` also supports :ref:`contextual\nmarkers<contextual-markers>` using the ``context`` keyword:\n\n.. code-block:: html+django\n\n    {% blocktranslate with name=user.username context \"greeting\" %}Hi {{ name }}{% endblocktranslate %}\n\nAnother feature ``{% blocktranslate %}`` supports is the ``trimmed`` option.\nThis option will remove newline characters from the beginning and the end of\nthe content of the ``{% blocktranslate %}`` tag, replace any whitespace at the\nbeginning and end of a line and merge all lines into one using a space\ncharacter to separate them. This is quite useful for indenting the content of a\n``{% blocktranslate %}`` tag without having the indentation characters end up\nin the corresponding entry in the PO file, which makes the translation process\neasier.\n\nFor instance, the following ``{% blocktranslate %}`` tag::\n\n    {% blocktranslate trimmed %}\n      First sentence.\n      Second paragraph.\n    {% endblocktranslate %}\n\nwill result in the entry ``\"First sentence. Second paragraph.\"`` in the PO file,\ncompared to ``\"\\n  First sentence.\\n  Second sentence.\\n\"``, if the ``trimmed``\noption had not been specified.\n\n.. versionchanged:: 3.1\n\n   The ``blocktrans`` tag was renamed to ``blocktranslate``. The ``blocktrans``\n   tag is still supported as an alias for backwards compatibility.\n\nString literals passed to tags and filters\n------------------------------------------\n\nYou can translate string literals passed as arguments to tags and filters\nby using the familiar ``_()`` syntax::\n\n    {% some_tag _(\"Page not found\") value|yesno:_(\"yes,no\") %}\n\nIn this case, both the tag and the filter will see the translated string,\nso they don't need to be aware of translations.\n\n.. note::\n    In this example, the translation infrastructure will be passed the string\n    ``\"yes,no\"``, not the individual strings ``\"yes\"`` and ``\"no\"``. The\n    translated string will need to contain the comma so that the filter\n    parsing code knows how to split up the arguments. For example, a German\n    translator might translate the string ``\"yes,no\"`` as ``\"ja,nein\"``\n    (keeping the comma intact).\n\n.. _translator-comments-in-templates:\n\nComments for translators in templates\n-------------------------------------\n\nJust like with :ref:`Python code <translator-comments>`, these notes for\ntranslators can be specified using comments, either with the :ttag:`comment`\ntag:\n\n.. code-block:: html+django\n\n    {% comment %}Translators: View verb{% endcomment %}\n    {% translate \"View\" %}\n\n    {% comment %}Translators: Short intro blurb{% endcomment %}\n    <p>{% blocktranslate %}A multiline translatable\n    literal.{% endblocktranslate %}</p>\n\nor with the ``{#`` ... ``#}`` :ref:`one-line comment constructs <template-comments>`:\n\n.. code-block:: html+django\n\n    {# Translators: Label of a button that triggers search #}\n    <button type=\"submit\">{% translate \"Go\" %}</button>\n\n    {# Translators: This is a text of the base template #}\n    {% blocktranslate %}Ambiguous translatable block of text{% endblocktranslate %}\n\n.. note:: Just for completeness, these are the corresponding fragments of the\n    resulting ``.po`` file:\n\n    .. code-block:: po\n\n        #. Translators: View verb\n        # path/to/template/file.html:10\n        msgid \"View\"\n        msgstr \"\"\n\n        #. Translators: Short intro blurb\n        # path/to/template/file.html:13\n        msgid \"\"\n        \"A multiline translatable\"\n        \"literal.\"\n        msgstr \"\"\n\n        # ...\n\n        #. Translators: Label of a button that triggers search\n        # path/to/template/file.html:100\n        msgid \"Go\"\n        msgstr \"\"\n\n        #. Translators: This is a text of the base template\n        # path/to/template/file.html:103\n        msgid \"Ambiguous translatable block of text\"\n        msgstr \"\"\n\n.. templatetag:: language\n\nSwitching language in templates\n-------------------------------\n\nIf you want to select a language within a template, you can use the\n``language`` template tag:\n\n.. code-block:: html+django\n\n    {% load i18n %}\n\n    {% get_current_language as LANGUAGE_CODE %}\n    <!-- Current language: {{ LANGUAGE_CODE }} -->\n    <p>{% translate \"Welcome to our page\" %}</p>\n\n    {% language 'en' %}\n        {% get_current_language as LANGUAGE_CODE %}\n        <!-- Current language: {{ LANGUAGE_CODE }} -->\n        <p>{% translate \"Welcome to our page\" %}</p>\n    {% endlanguage %}\n\nWhile the first occurrence of \"Welcome to our page\" uses the current language,\nthe second will always be in English.\n\n.. _i18n-template-tags:\n\nOther tags\n----------\n\nThese tags also require a ``{% load i18n %}``.\n\n.. templatetag:: get_available_languages\n\n``get_available_languages``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n``{% get_available_languages as LANGUAGES %}`` returns a list of tuples in\nwhich the first element is the :term:`language code` and the second is the\nlanguage name (translated into the currently active locale).\n\n.. templatetag:: get_current_language\n\n``get_current_language``\n~~~~~~~~~~~~~~~~~~~~~~~~\n\n``{% get_current_language as LANGUAGE_CODE %}`` returns the current user's\npreferred language as a string. Example: ``en-us``. See\n:ref:`how-django-discovers-language-preference`.\n\n.. templatetag:: get_current_language_bidi\n\n``get_current_language_bidi``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n``{% get_current_language_bidi as LANGUAGE_BIDI %}`` returns the current\nlocale's direction. If ``True``, it's a right-to-left language, e.g. Hebrew,\nArabic. If ``False`` it's a left-to-right language, e.g. English, French,\nGerman, etc.\n\n.. _template-translation-vars:\n\n``i18n`` context processor\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf you enable the :class:`django.template.context_processors.i18n` context\nprocessor, then each ``RequestContext`` will have access to ``LANGUAGES``,\n``LANGUAGE_CODE``, and ``LANGUAGE_BIDI`` as defined above.\n\n.. templatetag:: get_language_info\n\n``get_language_info``\n~~~~~~~~~~~~~~~~~~~~~\n\nYou can also retrieve information about any of the available languages using\nprovided template tags and filters. To get information about a single language,\nuse the ``{% get_language_info %}`` tag::\n\n    {% get_language_info for LANGUAGE_CODE as lang %}\n    {% get_language_info for \"pl\" as lang %}\n\nYou can then access the information::\n\n    Language code: {{ lang.code }}<br>\n    Name of language: {{ lang.name_local }}<br>\n    Name in English: {{ lang.name }}<br>\n    Bi-directional: {{ lang.bidi }}\n    Name in the active language: {{ lang.name_translated }}\n\n.. templatetag:: get_language_info_list\n\n``get_language_info_list``\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nYou can also use the ``{% get_language_info_list %}`` template tag to retrieve\ninformation for a list of languages (e.g. active languages as specified in\n:setting:`LANGUAGES`). See :ref:`the section about the set_language redirect\nview <set_language-redirect-view>` for an example of how to display a language\nselector using ``{% get_language_info_list %}``.\n\nIn addition to :setting:`LANGUAGES` style list of tuples,\n``{% get_language_info_list %}`` supports lists of language codes.\nIf you do this in your view:\n\n.. code-block:: python\n\n    context = {'available_languages': ['en', 'es', 'fr']}\n    return render(request, 'mytemplate.html', context)\n\nyou can iterate over those languages in the template::\n\n  {% get_language_info_list for available_languages as langs %}\n  {% for lang in langs %} ... {% endfor %}\n\n.. templatefilter:: language_name\n.. templatefilter:: language_name_local\n.. templatefilter:: language_bidi\n.. templatefilter:: language_name_translated\n\nTemplate filters\n~~~~~~~~~~~~~~~~\n\nThere are also some filters available for convenience:\n\n* ``{{ LANGUAGE_CODE|language_name }}`` (\"German\")\n* ``{{ LANGUAGE_CODE|language_name_local }}`` (\"Deutsch\")\n* ``{{ LANGUAGE_CODE|language_bidi }}`` (False)\n* ``{{ LANGUAGE_CODE|language_name_translated }}`` (\"německy\", when active language is Czech)\n\nInternationalization: in JavaScript code\n========================================\n\n.. highlight:: python\n\nAdding translations to JavaScript poses some problems:\n\n* JavaScript code doesn't have access to a ``gettext`` implementation.\n\n* JavaScript code doesn't have access to ``.po`` or ``.mo`` files; they need to\n  be delivered by the server.\n\n* The translation catalogs for JavaScript should be kept as small as\n  possible.\n\nDjango provides an integrated solution for these problems: It passes the\ntranslations into JavaScript, so you can call ``gettext``, etc., from within\nJavaScript.\n\nThe main solution to these problems is the following ``JavaScriptCatalog`` view,\nwhich generates a JavaScript code library with functions that mimic the\n``gettext`` interface, plus an array of translation strings.\n\nThe ``JavaScriptCatalog`` view\n------------------------------\n\n.. module:: django.views.i18n\n\n.. class:: JavaScriptCatalog\n\n    A view that produces a JavaScript code library with functions that mimic\n    the ``gettext`` interface, plus an array of translation strings.\n\n    **Attributes**\n\n    .. attribute:: domain\n\n        Translation domain containing strings to add in the view output.\n        Defaults to ``'djangojs'``.\n\n    .. attribute:: packages\n\n        A list of :attr:`application names <django.apps.AppConfig.name>` among\n        installed applications. Those apps should contain a ``locale``\n        directory. All those catalogs plus all catalogs found in\n        :setting:`LOCALE_PATHS` (which are always included) are merged into one\n        catalog. Defaults to ``None``, which means that all available\n        translations from all :setting:`INSTALLED_APPS` are provided in the\n        JavaScript output.\n\n    **Example with default values**::\n\n        from django.views.i18n import JavaScriptCatalog\n\n        urlpatterns = [\n            path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'),\n        ]\n\n    **Example with custom packages**::\n\n        urlpatterns = [\n            path('jsi18n/myapp/',\n                 JavaScriptCatalog.as_view(packages=['your.app.label']),\n                 name='javascript-catalog'),\n        ]\n\n    If your root URLconf uses :func:`~django.conf.urls.i18n.i18n_patterns`,\n    ``JavaScriptCatalog`` must also be wrapped by ``i18n_patterns()`` for the\n    catalog to be correctly generated.\n\n    **Example with** ``i18n_patterns()``::\n\n        from django.conf.urls.i18n import i18n_patterns\n\n        urlpatterns = i18n_patterns(\n            path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'),\n        )\n\nThe precedence of translations is such that the packages appearing later in the\n``packages`` argument have higher precedence than the ones appearing at the\nbeginning. This is important in the case of clashing translations for the same\nliteral.\n\nIf you use more than one ``JavaScriptCatalog`` view on a site and some of them\ndefine the same strings, the strings in the catalog that was loaded last take\nprecedence.\n\nUsing the JavaScript translation catalog\n----------------------------------------\n\n.. highlight:: javascript\n\nTo use the catalog, pull in the dynamically generated script like this:\n\n.. code-block:: html+django\n\n    <script src=\"{% url 'javascript-catalog' %}\"></script>\n\nThis uses reverse URL lookup to find the URL of the JavaScript catalog view.\nWhen the catalog is loaded, your JavaScript code can use the following methods:\n\n* ``gettext``\n* ``ngettext``\n* ``interpolate``\n* ``get_format``\n* ``gettext_noop``\n* ``pgettext``\n* ``npgettext``\n* ``pluralidx``\n\n``gettext``\n~~~~~~~~~~~\n\nThe ``gettext`` function behaves similarly to the standard ``gettext``\ninterface within your Python code::\n\n    document.write(gettext('this is to be translated'));\n\n``ngettext``\n~~~~~~~~~~~~\n\nThe ``ngettext`` function provides an interface to pluralize words and\nphrases::\n\n    var object_count = 1 // or 0, or 2, or 3, ...\n    s = ngettext('literal for the singular case',\n            'literal for the plural case', object_count);\n\n``interpolate``\n~~~~~~~~~~~~~~~\n\nThe ``interpolate`` function supports dynamically populating a format string.\nThe interpolation syntax is borrowed from Python, so the ``interpolate``\nfunction supports both positional and named interpolation:\n\n* Positional interpolation: ``obj`` contains a JavaScript Array object\n  whose elements values are then sequentially interpolated in their\n  corresponding ``fmt`` placeholders in the same order they appear.\n  For example::\n\n    fmts = ngettext('There is %s object. Remaining: %s',\n            'There are %s objects. Remaining: %s', 11);\n    s = interpolate(fmts, [11, 20]);\n    // s is 'There are 11 objects. Remaining: 20'\n\n* Named interpolation: This mode is selected by passing the optional\n  boolean ``named`` parameter as ``true``. ``obj`` contains a JavaScript\n  object or associative array. For example::\n\n    d = {\n        count: 10,\n        total: 50\n    };\n\n    fmts = ngettext('Total: %(total)s, there is %(count)s object',\n    'there are %(count)s of a total of %(total)s objects', d.count);\n    s = interpolate(fmts, d, true);\n\nYou shouldn't go over the top with string interpolation, though: this is still\nJavaScript, so the code has to make repeated regular-expression substitutions.\nThis isn't as fast as string interpolation in Python, so keep it to those\ncases where you really need it (for example, in conjunction with ``ngettext``\nto produce proper pluralizations).\n\n``get_format``\n~~~~~~~~~~~~~~\n\nThe ``get_format`` function has access to the configured i18n formatting\nsettings and can retrieve the format string for a given setting name::\n\n    document.write(get_format('DATE_FORMAT'));\n    // 'N j, Y'\n\nIt has access to the following settings:\n\n* :setting:`DATE_FORMAT`\n* :setting:`DATE_INPUT_FORMATS`\n* :setting:`DATETIME_FORMAT`\n* :setting:`DATETIME_INPUT_FORMATS`\n* :setting:`DECIMAL_SEPARATOR`\n* :setting:`FIRST_DAY_OF_WEEK`\n* :setting:`MONTH_DAY_FORMAT`\n* :setting:`NUMBER_GROUPING`\n* :setting:`SHORT_DATE_FORMAT`\n* :setting:`SHORT_DATETIME_FORMAT`\n* :setting:`THOUSAND_SEPARATOR`\n* :setting:`TIME_FORMAT`\n* :setting:`TIME_INPUT_FORMATS`\n* :setting:`YEAR_MONTH_FORMAT`\n\nThis is useful for maintaining formatting consistency with the Python-rendered\nvalues.\n\n``gettext_noop``\n~~~~~~~~~~~~~~~~\n\nThis emulates the ``gettext`` function but does nothing, returning whatever\nis passed to it::\n\n    document.write(gettext_noop('this will not be translated'));\n\nThis is useful for stubbing out portions of the code that will need translation\nin the future.\n\n``pgettext``\n~~~~~~~~~~~~\n\nThe ``pgettext`` function behaves like the Python variant\n(:func:`~django.utils.translation.pgettext()`), providing a contextually\ntranslated word::\n\n    document.write(pgettext('month name', 'May'));\n\n``npgettext``\n~~~~~~~~~~~~~\n\nThe ``npgettext`` function also behaves like the Python variant\n(:func:`~django.utils.translation.npgettext()`), providing a **pluralized**\ncontextually translated word::\n\n    document.write(npgettext('group', 'party', 1));\n    // party\n    document.write(npgettext('group', 'party', 2));\n    // parties\n\n``pluralidx``\n~~~~~~~~~~~~~\n\nThe ``pluralidx`` function works in a similar way to the :tfilter:`pluralize`\ntemplate filter, determining if a given ``count`` should use a plural form of\na word or not::\n\n    document.write(pluralidx(0));\n    // true\n    document.write(pluralidx(1));\n    // false\n    document.write(pluralidx(2));\n    // true\n\nIn the simplest case, if no custom pluralization is needed, this returns\n``false`` for the integer ``1`` and ``true`` for all other numbers.\n\nHowever, pluralization is not this simple in all languages. If the language does\nnot support pluralization, an empty value is provided.\n\nAdditionally, if there are complex rules around pluralization, the catalog view\nwill render a conditional expression. This will evaluate to either a ``true``\n(should pluralize) or ``false`` (should **not** pluralize) value.\n\n.. highlight:: python\n\nThe ``JSONCatalog`` view\n------------------------\n\n.. class:: JSONCatalog\n\n    In order to use another client-side library to handle translations, you may\n    want to take advantage of the ``JSONCatalog`` view. It's similar to\n    :class:`~django.views.i18n.JavaScriptCatalog` but returns a JSON response.\n\n    See the documentation for :class:`~django.views.i18n.JavaScriptCatalog`\n    to learn about possible values and use of the ``domain`` and ``packages``\n    attributes.\n\n    The response format is as follows:\n\n    .. code-block:: text\n\n        {\n            \"catalog\": {\n                # Translations catalog\n            },\n            \"formats\": {\n                # Language formats for date, time, etc.\n            },\n            \"plural\": \"...\"  # Expression for plural forms, or null.\n        }\n\n    .. JSON doesn't allow comments so highlighting as JSON won't work here.\n\nNote on performance\n-------------------\n\nThe various JavaScript/JSON i18n views generate the catalog from ``.mo`` files\non every request. Since its output is constant, at least for a given version\nof a site, it's a good candidate for caching.\n\nServer-side caching will reduce CPU load. It's easily implemented with the\n:func:`~django.views.decorators.cache.cache_page` decorator. To trigger cache\ninvalidation when your translations change, provide a version-dependent key\nprefix, as shown in the example below, or map the view at a version-dependent\nURL::\n\n    from django.views.decorators.cache import cache_page\n    from django.views.i18n import JavaScriptCatalog\n\n    # The value returned by get_version() must change when translations change.\n    urlpatterns = [\n        path('jsi18n/',\n             cache_page(86400, key_prefix='js18n-%s' % get_version())(JavaScriptCatalog.as_view()),\n             name='javascript-catalog'),\n    ]\n\nClient-side caching will save bandwidth and make your site load faster. If\nyou're using ETags (:class:`~django.middleware.http.ConditionalGetMiddleware`),\nyou're already covered. Otherwise, you can apply :ref:`conditional decorators\n<conditional-decorators>`. In the following example, the cache is invalidated\nwhenever you restart your application server::\n\n    from django.utils import timezone\n    from django.views.decorators.http import last_modified\n    from django.views.i18n import JavaScriptCatalog\n\n    last_modified_date = timezone.now()\n\n    urlpatterns = [\n        path('jsi18n/',\n             last_modified(lambda req, **kw: last_modified_date)(JavaScriptCatalog.as_view()),\n             name='javascript-catalog'),\n    ]\n\nYou can even pre-generate the JavaScript catalog as part of your deployment\nprocedure and serve it as a static file. This radical technique is implemented\nin django-statici18n_.\n\n.. _django-statici18n: https://django-statici18n.readthedocs.io/en/latest/\n\n.. _url-internationalization:\n\nInternationalization: in URL patterns\n=====================================\n\n.. module:: django.conf.urls.i18n\n\nDjango provides two mechanisms to internationalize URL patterns:\n\n* Adding the language prefix to the root of the URL patterns to make it\n  possible for :class:`~django.middleware.locale.LocaleMiddleware` to detect\n  the language to activate from the requested URL.\n\n* Making URL patterns themselves translatable via the\n  :func:`django.utils.translation.gettext_lazy()` function.\n\n.. warning::\n\n    Using either one of these features requires that an active language be set\n    for each request; in other words, you need to have\n    :class:`django.middleware.locale.LocaleMiddleware` in your\n    :setting:`MIDDLEWARE` setting.\n\nLanguage prefix in URL patterns\n-------------------------------\n\n.. function:: i18n_patterns(*urls, prefix_default_language=True)\n\nThis function can be used in a root URLconf and Django will automatically\nprepend the current active language code to all URL patterns defined within\n:func:`~django.conf.urls.i18n.i18n_patterns`.\n\nSetting ``prefix_default_language`` to ``False`` removes the prefix from the\ndefault language (:setting:`LANGUAGE_CODE`). This can be useful when adding\ntranslations to existing site so that the current URLs won't change.\n\nExample URL patterns::\n\n    from django.conf.urls.i18n import i18n_patterns\n    from django.urls import include, path\n\n    from about import views as about_views\n    from news import views as news_views\n    from sitemap.views import sitemap\n\n    urlpatterns = [\n        path('sitemap.xml', sitemap, name='sitemap-xml'),\n    ]\n\n    news_patterns = ([\n        path('', news_views.index, name='index'),\n        path('category/<slug:slug>/', news_views.category, name='category'),\n        path('<slug:slug>/', news_views.details, name='detail'),\n    ], 'news')\n\n    urlpatterns += i18n_patterns(\n        path('about/', about_views.main, name='about'),\n        path('news/', include(news_patterns, namespace='news')),\n    )\n\nAfter defining these URL patterns, Django will automatically add the\nlanguage prefix to the URL patterns that were added by the ``i18n_patterns``\nfunction. Example::\n\n    >>> from django.urls import reverse\n    >>> from django.utils.translation import activate\n\n    >>> activate('en')\n    >>> reverse('sitemap-xml')\n    '/sitemap.xml'\n    >>> reverse('news:index')\n    '/en/news/'\n\n    >>> activate('nl')\n    >>> reverse('news:detail', kwargs={'slug': 'news-slug'})\n    '/nl/news/news-slug/'\n\nWith ``prefix_default_language=False`` and  ``LANGUAGE_CODE='en'``, the URLs\nwill be::\n\n    >>> activate('en')\n    >>> reverse('news:index')\n    '/news/'\n\n    >>> activate('nl')\n    >>> reverse('news:index')\n    '/nl/news/'\n\n.. warning::\n\n    :func:`~django.conf.urls.i18n.i18n_patterns` is only allowed in a root\n    URLconf. Using it within an included URLconf will throw an\n    :exc:`~django.core.exceptions.ImproperlyConfigured` exception.\n\n.. warning::\n\n    Ensure that you don't have non-prefixed URL patterns that might collide\n    with an automatically-added language prefix.\n\n.. _translating-urlpatterns:\n\nTranslating URL patterns\n------------------------\n\nURL patterns can also be marked translatable using the\n:func:`~django.utils.translation.gettext_lazy` function. Example::\n\n    from django.conf.urls.i18n import i18n_patterns\n    from django.urls import include, path\n    from django.utils.translation import gettext_lazy as _\n\n    from about import views as about_views\n    from news import views as news_views\n    from sitemaps.views import sitemap\n\n    urlpatterns = [\n        path('sitemap.xml', sitemap, name='sitemap-xml'),\n    ]\n\n    news_patterns = ([\n        path('', news_views.index, name='index'),\n        path(_('category/<slug:slug>/'), news_views.category, name='category'),\n        path('<slug:slug>/', news_views.details, name='detail'),\n    ], 'news')\n\n    urlpatterns += i18n_patterns(\n        path(_('about/'), about_views.main, name='about'),\n        path(_('news/'), include(news_patterns, namespace='news')),\n    )\n\nAfter you've created the translations, the :func:`~django.urls.reverse`\nfunction will return the URL in the active language. Example::\n\n    >>> from django.urls import reverse\n    >>> from django.utils.translation import activate\n\n    >>> activate('en')\n    >>> reverse('news:category', kwargs={'slug': 'recent'})\n    '/en/news/category/recent/'\n\n    >>> activate('nl')\n    >>> reverse('news:category', kwargs={'slug': 'recent'})\n    '/nl/nieuws/categorie/recent/'\n\n.. warning::\n\n    In most cases, it's best to use translated URLs only within a language code\n    prefixed block of patterns (using\n    :func:`~django.conf.urls.i18n.i18n_patterns`), to avoid the possibility\n    that a carelessly translated URL causes a collision with a non-translated\n    URL pattern.\n\n.. _reversing_in_templates:\n\nReversing in templates\n----------------------\n\nIf localized URLs get reversed in templates they always use the current\nlanguage. To link to a URL in another language use the :ttag:`language`\ntemplate tag. It enables the given language in the enclosed template section:\n\n.. code-block:: html+django\n\n    {% load i18n %}\n\n    {% get_available_languages as languages %}\n\n    {% translate \"View this category in:\" %}\n    {% for lang_code, lang_name in languages %}\n        {% language lang_code %}\n        <a href=\"{% url 'category' slug=category.slug %}\">{{ lang_name }}</a>\n        {% endlanguage %}\n    {% endfor %}\n\nThe :ttag:`language` tag expects the language code as the only argument.\n\n.. _how-to-create-language-files:\n\nLocalization: how to create language files\n==========================================\n\nOnce the string literals of an application have been tagged for later\ntranslation, the translation themselves need to be written (or obtained). Here's\nhow that works.\n\nMessage files\n-------------\n\nThe first step is to create a :term:`message file` for a new language. A message\nfile is a plain-text file, representing a single language, that contains all\navailable translation strings and how they should be represented in the given\nlanguage. Message files have a ``.po`` file extension.\n\nDjango comes with a tool, :djadmin:`django-admin makemessages\n<makemessages>`, that automates the creation and upkeep of these files.\n\n.. admonition:: Gettext utilities\n\n    The ``makemessages`` command (and ``compilemessages`` discussed later) use\n    commands from the GNU gettext toolset: ``xgettext``, ``msgfmt``,\n    ``msgmerge`` and ``msguniq``.\n\n    The minimum version of the ``gettext`` utilities supported is 0.15.\n\nTo create or update a message file, run this command::\n\n    django-admin makemessages -l de\n\n...where ``de`` is the :term:`locale name` for the message file you want to\ncreate. For example, ``pt_BR`` for Brazilian Portuguese, ``de_AT`` for Austrian\nGerman or ``id`` for Indonesian.\n\nThe script should be run from one of two places:\n\n* The root directory of your Django project (the one that contains\n  ``manage.py``).\n* The root directory of one of your Django apps.\n\nThe script runs over your project source tree or your application source tree\nand pulls out all strings marked for translation (see\n:ref:`how-django-discovers-translations` and be sure :setting:`LOCALE_PATHS`\nis configured correctly). It creates (or updates) a message file in the\ndirectory ``locale/LANG/LC_MESSAGES``. In the ``de`` example, the file will be\n``locale/de/LC_MESSAGES/django.po``.\n\nWhen you run ``makemessages`` from the root directory of your project, the\nextracted strings will be automatically distributed to the proper message files.\nThat is, a string extracted from a file of an app containing a ``locale``\ndirectory will go in a message file under that directory. A string extracted\nfrom a file of an app without any ``locale`` directory will either go in a\nmessage file under the directory listed first in :setting:`LOCALE_PATHS` or\nwill generate an error if :setting:`LOCALE_PATHS` is empty.\n\nBy default :djadmin:`django-admin makemessages <makemessages>` examines every\nfile that has the ``.html``, ``.txt`` or ``.py`` file extension. If you want to\noverride that default, use the :option:`--extension <makemessages --extension>`\nor ``-e`` option to specify the file extensions to examine::\n\n    django-admin makemessages -l de -e txt\n\nSeparate multiple extensions with commas and/or use ``-e`` or ``--extension``\nmultiple times::\n\n    django-admin makemessages -l de -e html,txt -e xml\n\n.. warning::\n\n    When :ref:`creating message files from JavaScript source code\n    <creating-message-files-from-js-code>` you need to use the special\n    ``djangojs`` domain, **not** ``-e js``.\n\n.. admonition:: Using Jinja2 templates?\n\n    :djadmin:`makemessages` doesn't understand the syntax of Jinja2 templates.\n    To extract strings from a project containing Jinja2 templates, use `Message\n    Extracting`_ from Babel_ instead.\n\n    Here's an example ``babel.cfg`` configuration file::\n\n        # Extraction from Python source files\n        [python: **.py]\n\n        # Extraction from Jinja2 templates\n        [jinja2: **.jinja]\n        extensions = jinja2.ext.with_\n\n    Make sure you list all extensions you're using! Otherwise Babel won't\n    recognize the tags defined by these extensions and will ignore Jinja2\n    templates containing them entirely.\n\n    Babel provides similar features to :djadmin:`makemessages`, can replace it\n    in general, and doesn't depend on ``gettext``. For more information, read\n    its documentation about `working with message catalogs`_.\n\n    .. _Message extracting: http://babel.pocoo.org/en/latest/messages.html#message-extraction\n    .. _Babel: http://babel.pocoo.org/\n    .. _working with message catalogs: http://babel.pocoo.org/en/latest/messages.html\n\n.. admonition:: No gettext?\n\n    If you don't have the ``gettext`` utilities installed,\n    :djadmin:`makemessages` will create empty files. If that's the case, either\n    install the ``gettext`` utilities or copy the English message file\n    (``locale/en/LC_MESSAGES/django.po``) if available and use it as a starting\n    point, which is an empty translation file.\n\n.. admonition:: Working on Windows?\n\n   If you're using Windows and need to install the GNU gettext utilities so\n   :djadmin:`makemessages` works, see :ref:`gettext_on_windows` for more\n   information.\n\nEach ``.po`` file contains a small bit of metadata, such as the translation\nmaintainer's contact information, but the bulk of the file is a list of\n**messages** -- mappings between translation strings and the actual translated\ntext for the particular language.\n\nFor example, if your Django app contained a translation string for the text\n``\"Welcome to my site.\"``, like so::\n\n    _(\"Welcome to my site.\")\n\n...then :djadmin:`django-admin makemessages <makemessages>` will have created\na ``.po`` file containing the following snippet -- a message:\n\n.. code-block:: po\n\n    #: path/to/python/module.py:23\n    msgid \"Welcome to my site.\"\n    msgstr \"\"\n\nA quick explanation:\n\n* ``msgid`` is the translation string, which appears in the source. Don't\n  change it.\n* ``msgstr`` is where you put the language-specific translation. It starts\n  out empty, so it's your responsibility to change it. Make sure you keep\n  the quotes around your translation.\n* As a convenience, each message includes, in the form of a comment line\n  prefixed with ``#`` and located above the ``msgid`` line, the filename and\n  line number from which the translation string was gleaned.\n\nLong messages are a special case. There, the first string directly after the\n``msgstr`` (or ``msgid``) is an empty string. Then the content itself will be\nwritten over the next few lines as one string per line. Those strings are\ndirectly concatenated. Don't forget trailing spaces within the strings;\notherwise, they'll be tacked together without whitespace!\n\n.. admonition:: Mind your charset\n\n    Due to the way the ``gettext`` tools work internally and because we want to\n    allow non-ASCII source strings in Django's core and your applications, you\n    **must** use UTF-8 as the encoding for your PO files (the default when PO\n    files are created).  This means that everybody will be using the same\n    encoding, which is important when Django processes the PO files.\n\nTo reexamine all source code and templates for new translation strings and\nupdate all message files for **all** languages, run this::\n\n    django-admin makemessages -a\n\nCompiling message files\n-----------------------\n\nAfter you create your message file -- and each time you make changes to it --\nyou'll need to compile it into a more efficient form, for use by ``gettext``. Do\nthis with the :djadmin:`django-admin compilemessages <compilemessages>`\nutility.\n\nThis tool runs over all available ``.po`` files and creates ``.mo`` files, which\nare binary files optimized for use by ``gettext``. In the same directory from\nwhich you ran :djadmin:`django-admin makemessages <makemessages>`, run\n:djadmin:`django-admin compilemessages <compilemessages>` like this::\n\n   django-admin compilemessages\n\nThat's it. Your translations are ready for use.\n\n.. admonition:: Working on Windows?\n\n   If you're using Windows and need to install the GNU gettext utilities so\n   :djadmin:`django-admin compilemessages <compilemessages>` works see\n   :ref:`gettext_on_windows` for more information.\n\n.. admonition:: .po files: Encoding and BOM usage.\n\n   Django only supports ``.po`` files encoded in UTF-8 and without any BOM\n   (Byte Order Mark) so if your text editor adds such marks to the beginning of\n   files by default then you will need to reconfigure it.\n\nTroubleshooting: ``gettext()`` incorrectly detects ``python-format`` in strings with percent signs\n--------------------------------------------------------------------------------------------------\n\nIn some cases, such as strings with a percent sign followed by a space and a\n:ref:`string conversion type <old-string-formatting>` (e.g.\n``_(\"10% interest\")``), :func:`~django.utils.translation.gettext` incorrectly\nflags strings with ``python-format``.\n\nIf you try to compile message files with incorrectly flagged strings, you'll\nget an error message like ``number of format specifications in 'msgid' and\n'msgstr' does not match`` or ``'msgstr' is not a valid Python format string,\nunlike 'msgid'``.\n\nTo workaround this, you can escape percent signs by adding a second percent\nsign::\n\n    from django.utils.translation import gettext as _\n    output = _(\"10%% interest\")\n\nOr you can use ``no-python-format`` so that all percent signs are treated as\nliterals::\n\n    # xgettext:no-python-format\n    output = _(\"10% interest\")\n\n.. _creating-message-files-from-js-code:\n\nCreating message files from JavaScript source code\n--------------------------------------------------\n\nYou create and update the message files the same way as the other Django message\nfiles -- with the :djadmin:`django-admin makemessages <makemessages>` tool.\nThe only difference is you need to explicitly specify what in gettext parlance\nis known as a domain in this case the ``djangojs`` domain, by providing a ``-d\ndjangojs`` parameter, like this::\n\n    django-admin makemessages -d djangojs -l de\n\nThis would create or update the message file for JavaScript for German. After\nupdating message files, run :djadmin:`django-admin compilemessages\n<compilemessages>` the same way as you do with normal Django message files.\n\n.. _gettext_on_windows:\n\n``gettext`` on Windows\n----------------------\n\nThis is only needed for people who either want to extract message IDs or compile\nmessage files (``.po``). Translation work itself involves editing existing\nfiles of this type, but if you want to create your own message files, or want\nto test or compile a changed message file, download `a precompiled binary\ninstaller <https://mlocati.github.io/articles/gettext-iconv-windows.html>`_.\n\nYou may also use ``gettext`` binaries you have obtained elsewhere, so long as\nthe ``xgettext --version`` command works properly. Do not attempt to use Django\ntranslation utilities with a ``gettext`` package if the command ``xgettext\n--version`` entered at a Windows command prompt causes a popup window saying\n\"xgettext.exe has generated errors and will be closed by Windows\".\n\n.. _customizing-makemessages:\n\nCustomizing the ``makemessages`` command\n----------------------------------------\n\nIf you want to pass additional parameters to ``xgettext``, you need to create a\ncustom :djadmin:`makemessages` command and override its ``xgettext_options``\nattribute::\n\n    from django.core.management.commands import makemessages\n\n    class Command(makemessages.Command):\n        xgettext_options = makemessages.Command.xgettext_options + ['--keyword=mytrans']\n\nIf you need more flexibility, you could also add a new argument to your custom\n:djadmin:`makemessages` command::\n\n    from django.core.management.commands import makemessages\n\n    class Command(makemessages.Command):\n\n        def add_arguments(self, parser):\n            super().add_arguments(parser)\n            parser.add_argument(\n                '--extra-keyword',\n                dest='xgettext_keywords',\n                action='append',\n            )\n\n        def handle(self, *args, **options):\n            xgettext_keywords = options.pop('xgettext_keywords')\n            if xgettext_keywords:\n                self.xgettext_options = (\n                    makemessages.Command.xgettext_options[:] +\n                    ['--keyword=%s' % kwd for kwd in xgettext_keywords]\n                )\n            super().handle(*args, **options)\n\nMiscellaneous\n=============\n\n.. _set_language-redirect-view:\n\nThe ``set_language`` redirect view\n----------------------------------\n\n.. currentmodule:: django.views.i18n\n\n.. function:: set_language(request)\n\nAs a convenience, Django comes with a view, :func:`django.views.i18n.set_language`,\nthat sets a user's language preference and redirects to a given URL or, by default,\nback to the previous page.\n\nActivate this view by adding the following line to your URLconf::\n\n    path('i18n/', include('django.conf.urls.i18n')),\n\n(Note that this example makes the view available at ``/i18n/setlang/``.)\n\n.. warning::\n\n    Make sure that you don't include the above URL within\n    :func:`~django.conf.urls.i18n.i18n_patterns` - it needs to be\n    language-independent itself to work correctly.\n\nThe view expects to be called via the ``POST`` method, with a ``language``\nparameter set in request. If session support is enabled, the view saves the\nlanguage choice in the user's session. It also saves the language choice in a\ncookie that is named ``django_language`` by default. (The name can be changed\nthrough the :setting:`LANGUAGE_COOKIE_NAME` setting.)\n\nAfter setting the language choice, Django looks for a ``next`` parameter in the\n``POST`` or ``GET`` data. If that is found and Django considers it to be a safe\nURL (i.e. it doesn't point to a different host and uses a safe scheme), a\nredirect to that URL will be performed. Otherwise, Django may fall back to\nredirecting the user to the URL from the ``Referer`` header or, if it is not\nset, to ``/``, depending on the nature of the request:\n\n* If the request accepts HTML content (based on its ``Accept`` HTTP header),\n  the fallback will always be performed.\n\n* If the request doesn't accept HTML, the fallback will be performed only if\n  the ``next`` parameter was set. Otherwise a 204 status code (No Content) will\n  be returned.\n\n.. versionchanged:: 3.1\n\n    In older versions, the distinction for the fallback is based on whether the\n    ``X-Requested-With`` header is set to the value ``XMLHttpRequest``. This is\n    set by the jQuery ``ajax()`` method.\n\nHere's example HTML template code:\n\n.. code-block:: html+django\n\n    {% load i18n %}\n\n    <form action=\"{% url 'set_language' %}\" method=\"post\">{% csrf_token %}\n        <input name=\"next\" type=\"hidden\" value=\"{{ redirect_to }}\">\n        <select name=\"language\">\n            {% get_current_language as LANGUAGE_CODE %}\n            {% get_available_languages as LANGUAGES %}\n            {% get_language_info_list for LANGUAGES as languages %}\n            {% for language in languages %}\n                <option value=\"{{ language.code }}\"{% if language.code == LANGUAGE_CODE %} selected{% endif %}>\n                    {{ language.name_local }} ({{ language.code }})\n                </option>\n            {% endfor %}\n        </select>\n        <input type=\"submit\" value=\"Go\">\n    </form>\n\nIn this example, Django looks up the URL of the page to which the user will be\nredirected in the ``redirect_to`` context variable.\n\n.. _explicitly-setting-the-active-language:\n\nExplicitly setting the active language\n--------------------------------------\n\n.. highlight:: python\n\nYou may want to set the active language for the current session explicitly. Perhaps\na user's language preference is retrieved from another system, for example.\nYou've already been introduced to :func:`django.utils.translation.activate()`. That\napplies to the current thread only. To persist the language for the entire\nsession in a cookie, set the :setting:`LANGUAGE_COOKIE_NAME` cookie on the\nresponse::\n\n    from django.conf import settings\n    from django.http import HttpResponse\n    from django.utils import translation\n    user_language = 'fr'\n    translation.activate(user_language)\n    response = HttpResponse(...)\n    response.set_cookie(settings.LANGUAGE_COOKIE_NAME, user_language)\n\nYou would typically want to use both: :func:`django.utils.translation.activate()`\nchanges the language for this thread, and setting the cookie makes this\npreference persist in future requests.\n\nUsing translations outside views and templates\n----------------------------------------------\n\nWhile Django provides a rich set of i18n tools for use in views and templates,\nit does not restrict the usage to Django-specific code. The Django translation\nmechanisms can be used to translate arbitrary texts to any language that is\nsupported by Django (as long as an appropriate translation catalog exists, of\ncourse). You can load a translation catalog, activate it and translate text to\nlanguage of your choice, but remember to switch back to original language, as\nactivating a translation catalog is done on per-thread basis and such change\nwill affect code running in the same thread.\n\nFor example::\n\n    from django.utils import translation\n\n    def welcome_translated(language):\n        cur_language = translation.get_language()\n        try:\n            translation.activate(language)\n            text = translation.gettext('welcome')\n        finally:\n            translation.activate(cur_language)\n        return text\n\nCalling this function with the value ``'de'`` will give you ``\"Willkommen\"``,\nregardless of :setting:`LANGUAGE_CODE` and language set by middleware.\n\nFunctions of particular interest are\n:func:`django.utils.translation.get_language()` which returns the language used\nin the current thread, :func:`django.utils.translation.activate()` which\nactivates a translation catalog for the current thread, and\n:func:`django.utils.translation.check_for_language()`\nwhich checks if the given language is supported by Django.\n\nTo help write more concise code, there is also a context manager\n:func:`django.utils.translation.override()` that stores the current language on\nenter and restores it on exit. With it, the above example becomes::\n\n    from django.utils import translation\n\n    def welcome_translated(language):\n        with translation.override(language):\n            return translation.gettext('welcome')\n\nLanguage cookie\n---------------\n\nA number of settings can be used to adjust language cookie options:\n\n* :setting:`LANGUAGE_COOKIE_NAME`\n* :setting:`LANGUAGE_COOKIE_AGE`\n* :setting:`LANGUAGE_COOKIE_DOMAIN`\n* :setting:`LANGUAGE_COOKIE_HTTPONLY`\n* :setting:`LANGUAGE_COOKIE_PATH`\n* :setting:`LANGUAGE_COOKIE_SAMESITE`\n* :setting:`LANGUAGE_COOKIE_SECURE`\n\nImplementation notes\n====================\n\n.. _specialties-of-django-i18n:\n\nSpecialties of Django translation\n---------------------------------\n\nDjango's translation machinery uses the standard ``gettext`` module that comes\nwith Python. If you know ``gettext``, you might note these specialties in the\nway Django does translation:\n\n* The string domain is ``django`` or ``djangojs``. This string domain is\n  used to differentiate between different programs that store their data\n  in a common message-file library (usually ``/usr/share/locale/``). The\n  ``django`` domain is used for Python and template translation strings\n  and is loaded into the global translation catalogs. The ``djangojs``\n  domain is only used for JavaScript translation catalogs to make sure\n  that those are as small as possible.\n* Django doesn't use ``xgettext`` alone. It uses Python wrappers around\n  ``xgettext`` and ``msgfmt``. This is mostly for convenience.\n\n.. _how-django-discovers-language-preference:\n\nHow Django discovers language preference\n----------------------------------------\n\nOnce you've prepared your translations -- or, if you want to use the\ntranslations that come with Django -- you'll need to activate translation for\nyour app.\n\nBehind the scenes, Django has a very flexible model of deciding which language\nshould be used -- installation-wide, for a particular user, or both.\n\nTo set an installation-wide language preference, set :setting:`LANGUAGE_CODE`.\nDjango uses this language as the default translation -- the final attempt if no\nbetter matching translation is found through one of the methods employed by the\nlocale middleware (see below).\n\nIf all you want is to run Django with your native language all you need to do\nis set :setting:`LANGUAGE_CODE` and make sure the corresponding :term:`message\nfiles <message file>` and their compiled versions (``.mo``) exist.\n\nIf you want to let each individual user specify which language they\nprefer, then you also need to use the ``LocaleMiddleware``.\n``LocaleMiddleware`` enables language selection based on data from the request.\nIt customizes content for each user.\n\nTo use ``LocaleMiddleware``, add ``'django.middleware.locale.LocaleMiddleware'``\nto your :setting:`MIDDLEWARE` setting. Because middleware order matters, follow\nthese guidelines:\n\n* Make sure it's one of the first middleware installed.\n* It should come after ``SessionMiddleware``, because ``LocaleMiddleware``\n  makes use of session data. And it should come before ``CommonMiddleware``\n  because ``CommonMiddleware`` needs an activated language in order\n  to resolve the requested URL.\n* If you use ``CacheMiddleware``, put ``LocaleMiddleware`` after it.\n\nFor example, your :setting:`MIDDLEWARE` might look like this::\n\n    MIDDLEWARE = [\n       'django.contrib.sessions.middleware.SessionMiddleware',\n       'd