applications.txt 17 KB

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