applications.txt 15 KB

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