applications.txt 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. ============
  2. Applications
  3. ============
  4. .. module:: django.apps
  5. .. versionadded:: 1.7
  6. Django contains a registry of installed applications that stores configuration
  7. and provides introspection. It also maintains a list of available :doc:`models
  8. </topics/db/models>`.
  9. This registry is simply called :attr:`~django.apps.apps` and it's available in
  10. :mod:`django.apps`::
  11. >>> from django.apps import apps
  12. >>> apps.get_app_config('admin').verbose_name
  13. 'Admin'
  14. Projects and applications
  15. =========================
  16. Django has historically used the term **project** to describe an installation
  17. of Django. A project is defined primarily by a settings module.
  18. The term **application** describes a Python package that provides some set of
  19. features. Applications may be reused in various projects.
  20. .. note::
  21. This terminology is somewhat confusing these days as it became common to
  22. use the phrase "web app" to describe what equates to a Django project.
  23. Applications include some combination of models, views, templates, template
  24. tags, static files, URLs, middleware, etc. They're generally wired into
  25. projects with the :setting:`INSTALLED_APPS` setting and optionally with other
  26. mechanisms such as URLconfs, the :setting:`MIDDLEWARE_CLASSES` setting, or
  27. template inheritance.
  28. It is important to understand that a Django application is just a set of code
  29. that interacts with various parts of the framework. There's no such thing as
  30. an ``Application`` object. However, there's a few places where Django needs to
  31. interact with installed applications, mainly for configuration and also for
  32. introspection. That's why the application registry maintains metadata in an
  33. :class:`~django.apps.AppConfig` instance for each installed application.
  34. Configuring applications
  35. ========================
  36. To configure an application, subclass :class:`~django.apps.AppConfig` and put
  37. the dotted path to that subclass in :setting:`INSTALLED_APPS`.
  38. When :setting:`INSTALLED_APPS` simply contains the dotted path to an
  39. application module, Django checks for a ``default_app_config`` variable in
  40. that module.
  41. If it's defined, it's the dotted path to the :class:`~django.apps.AppConfig`
  42. subclass for that application.
  43. If there is no ``default_app_config``, Django uses the base
  44. :class:`~django.apps.AppConfig` class.
  45. For application authors
  46. -----------------------
  47. If you're creating a pluggable app called "Rock ’n’ roll", here's how you
  48. would provide a proper name for the admin::
  49. # rock_n_roll/apps.py
  50. from django.apps import AppConfig
  51. class RockNRollConfig(AppConfig):
  52. name = 'rock_n_roll'
  53. verbose_name = "Rock ’n’ roll"
  54. You can make your application load this :class:`~django.apps.AppConfig`
  55. subclass by default as follows::
  56. # rock_n_roll/__init__.py
  57. default_app_config = 'rock_n_roll.apps.RockNRollConfig'
  58. That will cause ``RockNRollConfig`` to be used when :setting:`INSTALLED_APPS`
  59. just contains ``'rock_n_roll'``. This allows you to make use of
  60. :class:`~django.apps.AppConfig` features without requiring your users to
  61. update their :setting:`INSTALLED_APPS` setting.
  62. Of course, you can also tell your users to put
  63. ``'rock_n_roll.apps.RockNRollConfig'`` in their :setting:`INSTALLED_APPS`
  64. setting. You can even provide several different
  65. :class:`~django.apps.AppConfig` subclasses with different behaviors and allow
  66. your users to choose one via their :setting:`INSTALLED_APPS` setting.
  67. The recommended convention is to put the configuration class in a submodule of
  68. the application called ``apps``. However, this isn't enforced by Django.
  69. You must include the :attr:`~django.apps.AppConfig.name` attribute for Django
  70. to determine which application this configuration applies to. You can define
  71. any attributes documented in the :class:`~django.apps.AppConfig` API
  72. reference.
  73. .. note::
  74. If your code imports the application registry in an application's
  75. ``__init__.py``, the name ``apps`` will clash with the ``apps`` submodule.
  76. The best practice is to move that code to a submodule and import it. A
  77. workaround is to import the registry under a different name::
  78. from django.apps import apps as django_apps
  79. For application users
  80. ---------------------
  81. If you're using "Rock ’n’ roll" in a project called ``anthology``, but you
  82. want it to show up as "Gypsy jazz" instead, you can provide your own
  83. configuration::
  84. # anthology/apps.py
  85. from rock_n_roll.apps import RockNRollConfig
  86. class GypsyJazzConfig(RockNRollConfig):
  87. verbose_name = "Gypsy jazz"
  88. # anthology/settings.py
  89. INSTALLED_APPS = [
  90. 'anthology.apps.GypsyJazzConfig',
  91. # ...
  92. ]
  93. Again, defining project-specific configuration classes in a submodule called
  94. ``apps`` is a convention, not a requirement.
  95. Application configuration
  96. =========================
  97. .. class:: AppConfig
  98. Application configuration objects store metadata for an application. Some
  99. attributes can be configured in :class:`~django.apps.AppConfig`
  100. subclasses. Others are set by Django and read-only.
  101. Configurable attributes
  102. -----------------------
  103. .. attribute:: AppConfig.name
  104. Full Python path to the application, e.g. ``'django.contrib.admin'``.
  105. This attribute defines which application the configuration applies to. It
  106. must be set in all :class:`~django.apps.AppConfig` subclasses.
  107. It must be unique across a Django project.
  108. .. attribute:: AppConfig.label
  109. Short name for the application, e.g. ``'admin'``
  110. This attribute allows relabelling an application when two applications
  111. have conflicting labels. It defaults to the last component of ``name``.
  112. It should be a valid Python identifier.
  113. It must be unique across a Django project.
  114. .. attribute:: AppConfig.verbose_name
  115. Human-readable name for the application, e.g. "Admin".
  116. This attribute defaults to ``label.title()``.
  117. .. attribute:: AppConfig.path
  118. Filesystem path to the application directory, e.g.
  119. ``'/usr/lib/python2.7/dist-packages/django/contrib/admin'``.
  120. In most cases, Django can automatically detect and set this, but you can
  121. also provide an explicit override as a class attribute on your
  122. :class:`~django.apps.AppConfig` subclass. In a few situations this is
  123. required; for instance if the app package is a `namespace package`_ with
  124. multiple paths.
  125. Read-only attributes
  126. --------------------
  127. .. attribute:: AppConfig.module
  128. Root module for the application, e.g. ``<module 'django.contrib.admin' from
  129. 'django/contrib/admin/__init__.pyc'>``.
  130. .. attribute:: AppConfig.models_module
  131. Module containing the models, e.g. ``<module 'django.contrib.admin.models'
  132. from 'django/contrib/admin/models.pyc'>``.
  133. It may be ``None`` if the application doesn't contain a ``models`` module.
  134. Methods
  135. -------
  136. .. method:: AppConfig.get_models()
  137. Returns an iterable of :class:`~django.db.models.Model` classes.
  138. .. method:: AppConfig.get_model(model_name)
  139. Returns the :class:`~django.db.models.Model` with the given
  140. ``model_name``. Raises :exc:`~exceptions.LookupError` if no such model
  141. exists. ``model_name`` is case-insensitive.
  142. .. method:: AppConfig.ready()
  143. Subclasses can override this method to perform initialization tasks such
  144. as registering signals. It is called as soon as the registry is fully
  145. populated.
  146. You cannot import models in modules that define application configuration
  147. classes, but you can use :meth:`get_model` to access a model class by
  148. name, like this::
  149. def ready(self):
  150. MyModel = self.get_model('MyModel')
  151. .. warning::
  152. Although you can access model classes as described above, avoid
  153. interacting with the database in your :meth:`ready()` implementation.
  154. This includes model methods that execute queries
  155. (:meth:`~django.db.models.Model.save()`,
  156. :meth:`~django.db.models.Model.delete()`, manager methods etc.), and
  157. also raw SQL queries via ``django.db.connection``. Your
  158. :meth:`ready()` method will run during startup of every management
  159. command. For example, even though the test database configuration is
  160. separate from the production settings, ``manage.py test`` would still
  161. execute some queries against your **production** database!
  162. .. _namespace package:
  163. Namespace packages as apps (Python 3.3+)
  164. ----------------------------------------
  165. Python versions 3.3 and later support Python packages without an
  166. ``__init__.py`` file. These packages are known as "namespace packages" and may
  167. be spread across multiple directories at different locations on ``sys.path``
  168. (see :pep:`420`).
  169. Django applications require a single base filesystem path where Django
  170. (depending on configuration) will search for templates, static assets,
  171. etc. Thus, namespace packages may only be Django applications if one of the
  172. following is true:
  173. 1. The namespace package actually has only a single location (i.e. is not
  174. spread across more than one directory.)
  175. 2. The :class:`~django.apps.AppConfig` class used to configure the application
  176. has a :attr:`~django.apps.AppConfig.path` class attribute, which is the
  177. absolute directory path Django will use as the single base path for the
  178. application.
  179. If neither of these conditions is met, Django will raise
  180. :exc:`~django.core.exceptions.ImproperlyConfigured`.
  181. Application registry
  182. ====================
  183. .. data:: apps
  184. The application registry provides the following public API. Methods that
  185. aren't listed below are considered private and may change without notice.
  186. .. attribute:: apps.ready
  187. Boolean attribute that is set to ``True`` when the registry is fully
  188. populated.
  189. .. method:: apps.get_app_configs()
  190. Returns an iterable of :class:`~django.apps.AppConfig` instances.
  191. .. method:: apps.get_app_config(app_label)
  192. Returns an :class:`~django.apps.AppConfig` for the application with the
  193. given ``app_label``. Raises :exc:`~exceptions.LookupError` if no such
  194. application exists.
  195. .. method:: apps.is_installed(app_name)
  196. Checks whether an application with the given name exists in the registry.
  197. ``app_name`` is the full name of the app, e.g. ``'django.contrib.admin'``.
  198. Unlike :meth:`~django.apps.apps.get_app_config`, this method can be called
  199. safely at import time. If the registry is still being populated, it may
  200. return ``False``, even though the app will become available later.
  201. .. method:: apps.get_model(app_label, model_name)
  202. Returns the :class:`~django.db.models.Model` with the given ``app_label``
  203. and ``model_name``. As a shortcut, this method also accepts a single
  204. argument in the form ``app_label.model_name``. ``model_name`` is case-
  205. insensitive.
  206. Raises :exc:`~exceptions.LookupError` if no such application or model
  207. exists. Raises :exc:`~exceptions.ValueError` when called with a single
  208. argument that doesn't contain exactly one dot.