applications.txt 18 KB

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