1. ============
    
  2. Applications
    
  3. ============
    
  4. 
    
  5. .. module:: django.apps
    
  6. 
    
  7. Django contains a registry of installed applications that stores configuration
    
  8. and provides introspection. It also maintains a list of available :doc:`models
    
  9. </topics/db/models>`.
    
  10. 
    
  11. This registry is called :attr:`~django.apps.apps` and it's available in
    
  12. :mod:`django.apps`::
    
  13. 
    
  14.     >>> from django.apps import apps
    
  15.     >>> apps.get_app_config('admin').verbose_name
    
  16.     'Administration'
    
  17. 
    
  18. Projects and applications
    
  19. =========================
    
  20. 
    
  21. The term **project** describes a Django web application. The project Python
    
  22. package is defined primarily by a settings module, but it usually contains
    
  23. other things. For example, when you run  ``django-admin startproject mysite``
    
  24. you'll get a ``mysite`` project directory that contains a ``mysite`` Python
    
  25. package with ``settings.py``, ``urls.py``, ``asgi.py`` and ``wsgi.py``. The
    
  26. project package is often extended to include things like fixtures, CSS, and
    
  27. templates which aren't tied to a particular application.
    
  28. 
    
  29. A **project's root directory** (the one that contains ``manage.py``) is usually
    
  30. the container for all of a project's applications which aren't installed
    
  31. separately.
    
  32. 
    
  33. The term **application** describes a Python package that provides some set of
    
  34. features. Applications :doc:`may be reused </intro/reusable-apps/>` in various
    
  35. projects.
    
  36. 
    
  37. Applications include some combination of models, views, templates, template
    
  38. tags, static files, URLs, middleware, etc. They're generally wired into
    
  39. projects with the :setting:`INSTALLED_APPS` setting and optionally with other
    
  40. mechanisms such as URLconfs, the :setting:`MIDDLEWARE` setting, or template
    
  41. inheritance.
    
  42. 
    
  43. It is important to understand that a Django application is a set of code
    
  44. that interacts with various parts of the framework. There's no such thing as
    
  45. an ``Application`` object. However, there's a few places where Django needs to
    
  46. interact with installed applications, mainly for configuration and also for
    
  47. introspection. That's why the application registry maintains metadata in an
    
  48. :class:`~django.apps.AppConfig` instance for each installed application.
    
  49. 
    
  50. There's no restriction that a project package can't also be considered an
    
  51. application and have models, etc. (which would require adding it to
    
  52. :setting:`INSTALLED_APPS`).
    
  53. 
    
  54. .. _configuring-applications-ref:
    
  55. 
    
  56. Configuring applications
    
  57. ========================
    
  58. 
    
  59. To configure an application, create an ``apps.py`` module inside the
    
  60. application, then define a subclass of :class:`AppConfig` there.
    
  61. 
    
  62. When :setting:`INSTALLED_APPS` contains the dotted path to an application
    
  63. module, by default, if Django finds exactly one :class:`AppConfig` subclass in
    
  64. the ``apps.py`` submodule, it uses that configuration for the application. This
    
  65. behavior may be disabled by setting :attr:`AppConfig.default` to ``False``.
    
  66. 
    
  67. If the ``apps.py`` module contains more than one :class:`AppConfig` subclass,
    
  68. Django will look for a single one where :attr:`AppConfig.default` is ``True``.
    
  69. 
    
  70. If no :class:`AppConfig` subclass is found, the base :class:`AppConfig` class
    
  71. will be used.
    
  72. 
    
  73. Alternatively, :setting:`INSTALLED_APPS` may contain the dotted path to a
    
  74. configuration class to specify it explicitly::
    
  75. 
    
  76.     INSTALLED_APPS = [
    
  77.         ...
    
  78.         'polls.apps.PollsAppConfig',
    
  79.         ...
    
  80.     ]
    
  81. 
    
  82. For application authors
    
  83. -----------------------
    
  84. 
    
  85. If you're creating a pluggable app called "Rock ’n’ roll", here's how you
    
  86. would provide a proper name for the admin::
    
  87. 
    
  88.     # rock_n_roll/apps.py
    
  89. 
    
  90.     from django.apps import AppConfig
    
  91. 
    
  92.     class RockNRollConfig(AppConfig):
    
  93.         name = 'rock_n_roll'
    
  94.         verbose_name = "Rock ’n’ roll"
    
  95. 
    
  96. ``RockNRollConfig`` will be loaded automatically when :setting:`INSTALLED_APPS`
    
  97. contains ``'rock_n_roll'``. If you need to prevent this, set
    
  98. :attr:`~AppConfig.default` to ``False`` in the class definition.
    
  99. 
    
  100. You can provide several :class:`AppConfig` subclasses with different behaviors.
    
  101. To tell Django which one to use by default, set :attr:`~AppConfig.default` to
    
  102. ``True`` in its definition. If your users want to pick a non-default
    
  103. configuration, they must replace ``'rock_n_roll'`` with the dotted path to that
    
  104. specific class in their :setting:`INSTALLED_APPS` setting.
    
  105. 
    
  106. The :attr:`AppConfig.name` attribute tells Django which application this
    
  107. configuration applies to. You can define any other attribute documented in the
    
  108. :class:`~django.apps.AppConfig` API reference.
    
  109. 
    
  110. :class:`AppConfig` subclasses may be defined anywhere. The ``apps.py``
    
  111. convention merely allows Django to load them automatically when
    
  112. :setting:`INSTALLED_APPS` contains the path to an application module rather
    
  113. than the path to a configuration class.
    
  114. 
    
  115. .. note::
    
  116. 
    
  117.     If your code imports the application registry in an application's
    
  118.     ``__init__.py``, the name ``apps`` will clash with the ``apps`` submodule.
    
  119.     The best practice is to move that code to a submodule and import it. A
    
  120.     workaround is to import the registry under a different name::
    
  121. 
    
  122.         from django.apps import apps as django_apps
    
  123. 
    
  124. For application users
    
  125. ---------------------
    
  126. 
    
  127. If you're using "Rock ’n’ roll" in a project called ``anthology``, but you
    
  128. want it to show up as "Jazz Manouche" instead, you can provide your own
    
  129. configuration::
    
  130. 
    
  131.     # anthology/apps.py
    
  132. 
    
  133.     from rock_n_roll.apps import RockNRollConfig
    
  134. 
    
  135.     class JazzManoucheConfig(RockNRollConfig):
    
  136.         verbose_name = "Jazz Manouche"
    
  137. 
    
  138.     # anthology/settings.py
    
  139. 
    
  140.     INSTALLED_APPS = [
    
  141.         'anthology.apps.JazzManoucheConfig',
    
  142.         # ...
    
  143.     ]
    
  144. 
    
  145. This example shows project-specific configuration classes located in a
    
  146. submodule called ``apps.py``. This is a convention, not a requirement.
    
  147. :class:`AppConfig` subclasses may be defined anywhere.
    
  148. 
    
  149. In this situation, :setting:`INSTALLED_APPS` must contain the dotted path to
    
  150. the configuration class because it lives outside of an application and thus
    
  151. cannot be automatically detected.
    
  152. 
    
  153. Application configuration
    
  154. =========================
    
  155. 
    
  156. .. class:: AppConfig
    
  157. 
    
  158.     Application configuration objects store metadata for an application. Some
    
  159.     attributes can be configured in :class:`~django.apps.AppConfig`
    
  160.     subclasses. Others are set by Django and read-only.
    
  161. 
    
  162. Configurable attributes
    
  163. -----------------------
    
  164. 
    
  165. .. attribute:: AppConfig.name
    
  166. 
    
  167.     Full Python path to the application, e.g. ``'django.contrib.admin'``.
    
  168. 
    
  169.     This attribute defines which application the configuration applies to. It
    
  170.     must be set in all :class:`~django.apps.AppConfig` subclasses.
    
  171. 
    
  172.     It must be unique across a Django project.
    
  173. 
    
  174. .. attribute:: AppConfig.label
    
  175. 
    
  176.     Short name for the application, e.g. ``'admin'``
    
  177. 
    
  178.     This attribute allows relabeling an application when two applications
    
  179.     have conflicting labels. It defaults to the last component of ``name``.
    
  180.     It should be a valid Python identifier.
    
  181. 
    
  182.     It must be unique across a Django project.
    
  183. 
    
  184. .. attribute:: AppConfig.verbose_name
    
  185. 
    
  186.     Human-readable name for the application, e.g. "Administration".
    
  187. 
    
  188.     This attribute defaults to ``label.title()``.
    
  189. 
    
  190. .. attribute:: AppConfig.path
    
  191. 
    
  192.     Filesystem path to the application directory, e.g.
    
  193.     ``'/usr/lib/pythonX.Y/dist-packages/django/contrib/admin'``.
    
  194. 
    
  195.     In most cases, Django can automatically detect and set this, but you can
    
  196.     also provide an explicit override as a class attribute on your
    
  197.     :class:`~django.apps.AppConfig` subclass. In a few situations this is
    
  198.     required; for instance if the app package is a `namespace package`_ with
    
  199.     multiple paths.
    
  200. 
    
  201. .. attribute:: AppConfig.default
    
  202. 
    
  203.     Set this attribute to ``False`` to prevent Django from selecting a
    
  204.     configuration class automatically. This is useful when ``apps.py`` defines
    
  205.     only one :class:`AppConfig` subclass but you don't want Django to use it by
    
  206.     default.
    
  207. 
    
  208.     Set this attribute to ``True`` to tell Django to select a configuration
    
  209.     class automatically. This is useful when ``apps.py`` defines more than one
    
  210.     :class:`AppConfig` subclass and you want Django to use one of them by
    
  211.     default.
    
  212. 
    
  213.     By default, this attribute isn't set.
    
  214. 
    
  215. .. attribute:: AppConfig.default_auto_field
    
  216. 
    
  217.     The implicit primary key type to add to models within this app. You can
    
  218.     use this to keep :class:`~django.db.models.AutoField` as the primary key
    
  219.     type for third party applications.
    
  220. 
    
  221.     By default, this is the value of :setting:`DEFAULT_AUTO_FIELD`.
    
  222. 
    
  223. Read-only attributes
    
  224. --------------------
    
  225. 
    
  226. .. attribute:: AppConfig.module
    
  227. 
    
  228.     Root module for the application, e.g. ``<module 'django.contrib.admin' from
    
  229.     'django/contrib/admin/__init__.py'>``.
    
  230. 
    
  231. .. attribute:: AppConfig.models_module
    
  232. 
    
  233.     Module containing the models, e.g. ``<module 'django.contrib.admin.models'
    
  234.     from 'django/contrib/admin/models.py'>``.
    
  235. 
    
  236.     It may be ``None`` if the application doesn't contain a ``models`` module.
    
  237.     Note that the database related signals such as
    
  238.     :data:`~django.db.models.signals.pre_migrate` and
    
  239.     :data:`~django.db.models.signals.post_migrate`
    
  240.     are only emitted for applications that have a ``models`` module.
    
  241. 
    
  242. Methods
    
  243. -------
    
  244. 
    
  245. .. method:: AppConfig.get_models(include_auto_created=False, include_swapped=False)
    
  246. 
    
  247.     Returns an iterable of :class:`~django.db.models.Model` classes for this
    
  248.     application.
    
  249. 
    
  250.     Requires the app registry to be fully populated.
    
  251. 
    
  252. .. method:: AppConfig.get_model(model_name, require_ready=True)
    
  253. 
    
  254.     Returns the :class:`~django.db.models.Model` with the given
    
  255.     ``model_name``. ``model_name`` is case-insensitive.
    
  256. 
    
  257.     Raises :exc:`LookupError` if no such model exists in this application.
    
  258. 
    
  259.     Requires the app registry to be fully populated unless the
    
  260.     ``require_ready`` argument is set to ``False``. ``require_ready`` behaves
    
  261.     exactly as in :meth:`apps.get_model()`.
    
  262. 
    
  263. .. method:: AppConfig.ready()
    
  264. 
    
  265.     Subclasses can override this method to perform initialization tasks such
    
  266.     as registering signals. It is called as soon as the registry is fully
    
  267.     populated.
    
  268. 
    
  269.     Although you can't import models at the module-level where
    
  270.     :class:`~django.apps.AppConfig` classes are defined, you can import them in
    
  271.     ``ready()``, using either an ``import`` statement or
    
  272.     :meth:`~AppConfig.get_model`.
    
  273. 
    
  274.     If you're registering :mod:`model signals <django.db.models.signals>`, you
    
  275.     can refer to the sender by its string label instead of using the model
    
  276.     class itself.
    
  277. 
    
  278.     Example::
    
  279. 
    
  280.         from django.apps import AppConfig
    
  281.         from django.db.models.signals import pre_save
    
  282. 
    
  283. 
    
  284.         class RockNRollConfig(AppConfig):
    
  285.             # ...
    
  286. 
    
  287.             def ready(self):
    
  288.                 # importing model classes
    
  289.                 from .models import MyModel  # or...
    
  290.                 MyModel = self.get_model('MyModel')
    
  291. 
    
  292.                 # registering signals with the model's string label
    
  293.                 pre_save.connect(receiver, sender='app_label.MyModel')
    
  294. 
    
  295.     .. warning::
    
  296. 
    
  297.         Although you can access model classes as described above, avoid
    
  298.         interacting with the database in your :meth:`ready()` implementation.
    
  299.         This includes model methods that execute queries
    
  300.         (:meth:`~django.db.models.Model.save()`,
    
  301.         :meth:`~django.db.models.Model.delete()`, manager methods etc.), and
    
  302.         also raw SQL queries via ``django.db.connection``. Your
    
  303.         :meth:`ready()` method will run during startup of every management
    
  304.         command. For example, even though the test database configuration is
    
  305.         separate from the production settings, ``manage.py test`` would still
    
  306.         execute some queries against your **production** database!
    
  307. 
    
  308.     .. note::
    
  309. 
    
  310.         In the usual initialization process, the ``ready`` method is only called
    
  311.         once by Django. But in some corner cases, particularly in tests which
    
  312.         are fiddling with installed applications, ``ready`` might be called more
    
  313.         than once. In that case, either write idempotent methods, or put a flag
    
  314.         on your ``AppConfig`` classes to prevent rerunning code which should
    
  315.         be executed exactly one time.
    
  316. 
    
  317. .. _namespace package:
    
  318. 
    
  319. Namespace packages as apps
    
  320. --------------------------
    
  321. 
    
  322. Python packages without an ``__init__.py`` file are known as "namespace
    
  323. packages" and may be spread across multiple directories at different locations
    
  324. on ``sys.path`` (see :pep:`420`).
    
  325. 
    
  326. Django applications require a single base filesystem path where Django
    
  327. (depending on configuration) will search for templates, static assets,
    
  328. etc. Thus, namespace packages may only be Django applications if one of the
    
  329. following is true:
    
  330. 
    
  331. #. The namespace package actually has only a single location (i.e. is not
    
  332.    spread across more than one directory.)
    
  333. 
    
  334. #. The :class:`~django.apps.AppConfig` class used to configure the application
    
  335.    has a :attr:`~django.apps.AppConfig.path` class attribute, which is the
    
  336.    absolute directory path Django will use as the single base path for the
    
  337.    application.
    
  338. 
    
  339. If neither of these conditions is met, Django will raise
    
  340. :exc:`~django.core.exceptions.ImproperlyConfigured`.
    
  341. 
    
  342. Application registry
    
  343. ====================
    
  344. 
    
  345. .. data:: apps
    
  346. 
    
  347.     The application registry provides the following public API. Methods that
    
  348.     aren't listed below are considered private and may change without notice.
    
  349. 
    
  350. .. attribute:: apps.ready
    
  351. 
    
  352.     Boolean attribute that is set to ``True`` after the registry is fully
    
  353.     populated and all :meth:`AppConfig.ready` methods are called.
    
  354. 
    
  355. .. method:: apps.get_app_configs()
    
  356. 
    
  357.     Returns an iterable of :class:`~django.apps.AppConfig` instances.
    
  358. 
    
  359. .. method:: apps.get_app_config(app_label)
    
  360. 
    
  361.     Returns an :class:`~django.apps.AppConfig` for the application with the
    
  362.     given ``app_label``. Raises :exc:`LookupError` if no such application
    
  363.     exists.
    
  364. 
    
  365. .. method:: apps.is_installed(app_name)
    
  366. 
    
  367.     Checks whether an application with the given name exists in the registry.
    
  368.     ``app_name`` is the full name of the app, e.g. ``'django.contrib.admin'``.
    
  369. 
    
  370. .. method:: apps.get_model(app_label, model_name, require_ready=True)
    
  371. 
    
  372.     Returns the :class:`~django.db.models.Model` with the given ``app_label``
    
  373.     and ``model_name``. As a shortcut, this method also accepts a single
    
  374.     argument in the form ``app_label.model_name``. ``model_name`` is
    
  375.     case-insensitive.
    
  376. 
    
  377.     Raises :exc:`LookupError` if no such application or model exists. Raises
    
  378.     :exc:`ValueError` when called with a single argument that doesn't contain
    
  379.     exactly one dot.
    
  380. 
    
  381.     Requires the app registry to be fully populated unless the
    
  382.     ``require_ready`` argument is set to ``False``.
    
  383. 
    
  384.     Setting ``require_ready`` to ``False`` allows looking up models
    
  385.     :ref:`while the app registry is being populated <app-loading-process>`,
    
  386.     specifically during the second phase where it imports models. Then
    
  387.     ``get_model()`` has the same effect as importing the model. The main use
    
  388.     case is to configure model classes with settings, such as
    
  389.     :setting:`AUTH_USER_MODEL`.
    
  390. 
    
  391.     When ``require_ready`` is ``False``, ``get_model()`` returns a model class
    
  392.     that may not be fully functional (reverse accessors may be missing, for
    
  393.     example) until the app registry is fully populated. For this reason, it's
    
  394.     best to leave ``require_ready`` to the default value of ``True`` whenever
    
  395.     possible.
    
  396. 
    
  397. .. _app-loading-process:
    
  398. 
    
  399. Initialization process
    
  400. ======================
    
  401. 
    
  402. How applications are loaded
    
  403. ---------------------------
    
  404. 
    
  405. When Django starts, :func:`django.setup()` is responsible for populating the
    
  406. application registry.
    
  407. 
    
  408. .. currentmodule:: django
    
  409. 
    
  410. .. function:: setup(set_prefix=True)
    
  411. 
    
  412.     Configures Django by:
    
  413. 
    
  414.     * Loading the settings.
    
  415.     * Setting up logging.
    
  416.     * If ``set_prefix`` is True, setting the URL resolver script prefix to
    
  417.       :setting:`FORCE_SCRIPT_NAME` if defined, or ``/`` otherwise.
    
  418.     * Initializing the application registry.
    
  419. 
    
  420.     This function is called automatically:
    
  421. 
    
  422.     * When running an HTTP server via Django's WSGI support.
    
  423.     * When invoking a management command.
    
  424. 
    
  425.     It must be called explicitly in other cases, for instance in plain Python
    
  426.     scripts.
    
  427. 
    
  428. .. currentmodule:: django.apps
    
  429. 
    
  430. The application registry is initialized in three stages. At each stage, Django
    
  431. processes all applications in the order of :setting:`INSTALLED_APPS`.
    
  432. 
    
  433. #. First Django imports each item in :setting:`INSTALLED_APPS`.
    
  434. 
    
  435.    If it's an application configuration class, Django imports the root package
    
  436.    of the application, defined by its :attr:`~AppConfig.name` attribute. If
    
  437.    it's a Python package, Django looks for an application configuration in an
    
  438.    ``apps.py`` submodule, or else creates a default application configuration.
    
  439. 
    
  440.    *At this stage, your code shouldn't import any models!*
    
  441. 
    
  442.    In other words, your applications' root packages and the modules that
    
  443.    define your application configuration classes shouldn't import any models,
    
  444.    even indirectly.
    
  445. 
    
  446.    Strictly speaking, Django allows importing models once their application
    
  447.    configuration is loaded. However, in order to avoid needless constraints on
    
  448.    the order of :setting:`INSTALLED_APPS`, it's strongly recommended not
    
  449.    import any models at this stage.
    
  450. 
    
  451.    Once this stage completes, APIs that operate on application configurations
    
  452.    such as :meth:`~apps.get_app_config()` become usable.
    
  453. 
    
  454. #. Then Django attempts to import the ``models`` submodule of each application,
    
  455.    if there is one.
    
  456. 
    
  457.    You must define or import all models in your application's ``models.py`` or
    
  458.    ``models/__init__.py``. Otherwise, the application registry may not be fully
    
  459.    populated at this point, which could cause the ORM to malfunction.
    
  460. 
    
  461.    Once this stage completes, APIs that operate on models such as
    
  462.    :meth:`~apps.get_model()` become usable.
    
  463. 
    
  464. #. Finally Django runs the :meth:`~AppConfig.ready()` method of each application
    
  465.    configuration.
    
  466. 
    
  467. .. _applications-troubleshooting:
    
  468. 
    
  469. Troubleshooting
    
  470. ---------------
    
  471. 
    
  472. Here are some common problems that you may encounter during initialization:
    
  473. 
    
  474. * :class:`~django.core.exceptions.AppRegistryNotReady`: This happens when
    
  475.   importing an application configuration or a models module triggers code that
    
  476.   depends on the app registry.
    
  477. 
    
  478.   For example, :func:`~django.utils.translation.gettext()` uses the app
    
  479.   registry to look up translation catalogs in applications. To translate at
    
  480.   import time, you need :func:`~django.utils.translation.gettext_lazy()`
    
  481.   instead. (Using :func:`~django.utils.translation.gettext()` would be a bug,
    
  482.   because the translation would happen at import time, rather than at each
    
  483.   request depending on the active language.)
    
  484. 
    
  485.   Executing database queries with the ORM at import time in models modules
    
  486.   will also trigger this exception. The ORM cannot function properly until all
    
  487.   models are available.
    
  488. 
    
  489.   This exception also happens if you forget to call :func:`django.setup()` in
    
  490.   a standalone Python script.
    
  491. 
    
  492. * ``ImportError: cannot import name ...`` This happens if the import sequence
    
  493.   ends up in a loop.
    
  494. 
    
  495.   To eliminate such problems, you should minimize dependencies between your
    
  496.   models modules and do as little work as possible at import time. To avoid
    
  497.   executing code at import time, you can move it into a function and cache its
    
  498.   results. The code will be executed when you first need its results. This
    
  499.   concept is known as "lazy evaluation".
    
  500. 
    
  501. * ``django.contrib.admin`` automatically performs autodiscovery of ``admin``
    
  502.   modules in installed applications. To prevent it, change your
    
  503.   :setting:`INSTALLED_APPS` to contain
    
  504.   ``'django.contrib.admin.apps.SimpleAdminConfig'`` instead of
    
  505.   ``'django.contrib.admin'``.