applications.txt 21 KB

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