applications.txt 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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 relabeling 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. "Administration".
  116. This attribute defaults to ``label.title()``.
  117. .. attribute:: AppConfig.path
  118. Filesystem path to the application directory, e.g.
  119. ``'/usr/lib/python3.4/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. Note that the database related signals such as
  135. :data:`~django.db.models.signals.pre_migrate` and
  136. :data:`~django.db.models.signals.post_migrate`
  137. are only emitted for applications that have a ``models`` module.
  138. Methods
  139. -------
  140. .. method:: AppConfig.get_models()
  141. Returns an iterable of :class:`~django.db.models.Model` classes.
  142. .. method:: AppConfig.get_model(model_name)
  143. Returns the :class:`~django.db.models.Model` with the given
  144. ``model_name``. Raises :exc:`LookupError` if no such model exists.
  145. ``model_name`` is case-insensitive.
  146. .. method:: AppConfig.ready()
  147. Subclasses can override this method to perform initialization tasks such
  148. as registering signals. It is called as soon as the registry is fully
  149. populated.
  150. You cannot import models in modules that define application configuration
  151. classes, but you can use :meth:`get_model` to access a model class by
  152. name, like this::
  153. def ready(self):
  154. MyModel = self.get_model('MyModel')
  155. .. warning::
  156. Although you can access model classes as described above, avoid
  157. interacting with the database in your :meth:`ready()` implementation.
  158. This includes model methods that execute queries
  159. (:meth:`~django.db.models.Model.save()`,
  160. :meth:`~django.db.models.Model.delete()`, manager methods etc.), and
  161. also raw SQL queries via ``django.db.connection``. Your
  162. :meth:`ready()` method will run during startup of every management
  163. command. For example, even though the test database configuration is
  164. separate from the production settings, ``manage.py test`` would still
  165. execute some queries against your **production** database!
  166. .. note::
  167. In the usual initialization process, the ``ready`` method is only called
  168. once by Django. But in some corner cases, particularly in tests which
  169. are fiddling with installed applications, ``ready`` might be called more
  170. than once. In that case, either write idempotents methods, or put a flag
  171. on your ``AppConfig`` classes to prevent re-running code which should
  172. be executed exactly one time.
  173. .. _namespace package:
  174. Namespace packages as apps (Python 3.3+)
  175. ----------------------------------------
  176. Python versions 3.3 and later support Python packages without an
  177. ``__init__.py`` file. These packages are known as "namespace packages" and may
  178. be spread across multiple directories at different locations on ``sys.path``
  179. (see :pep:`420`).
  180. Django applications require a single base filesystem path where Django
  181. (depending on configuration) will search for templates, static assets,
  182. etc. Thus, namespace packages may only be Django applications if one of the
  183. following is true:
  184. 1. The namespace package actually has only a single location (i.e. is not
  185. spread across more than one directory.)
  186. 2. The :class:`~django.apps.AppConfig` class used to configure the application
  187. has a :attr:`~django.apps.AppConfig.path` class attribute, which is the
  188. absolute directory path Django will use as the single base path for the
  189. application.
  190. If neither of these conditions is met, Django will raise
  191. :exc:`~django.core.exceptions.ImproperlyConfigured`.
  192. Application registry
  193. ====================
  194. .. data:: apps
  195. The application registry provides the following public API. Methods that
  196. aren't listed below are considered private and may change without notice.
  197. .. attribute:: apps.ready
  198. Boolean attribute that is set to ``True`` when the registry is fully
  199. populated.
  200. .. method:: apps.get_app_configs()
  201. Returns an iterable of :class:`~django.apps.AppConfig` instances.
  202. .. method:: apps.get_app_config(app_label)
  203. Returns an :class:`~django.apps.AppConfig` for the application with the
  204. given ``app_label``. Raises :exc:`LookupError` if no such application
  205. exists.
  206. .. method:: apps.is_installed(app_name)
  207. Checks whether an application with the given name exists in the registry.
  208. ``app_name`` is the full name of the app, e.g. ``'django.contrib.admin'``.
  209. .. method:: apps.get_model(app_label, model_name)
  210. Returns the :class:`~django.db.models.Model` with the given ``app_label``
  211. and ``model_name``. As a shortcut, this method also accepts a single
  212. argument in the form ``app_label.model_name``. ``model_name`` is case-
  213. insensitive.
  214. Raises :exc:`LookupError` if no such application or model exists. Raises
  215. :exc:`ValueError` when called with a single argument that doesn't contain
  216. exactly one dot.
  217. Initialization process
  218. ======================
  219. How applications are loaded
  220. ---------------------------
  221. When Django starts, :func:`django.setup()` is responsible for populating the
  222. application registry.
  223. .. currentmodule:: django
  224. .. function:: setup()
  225. Configures Django by:
  226. * Loading the settings.
  227. * Setting up logging.
  228. * Initializing the application registry.
  229. This function is called automatically:
  230. * When running an HTTP server via Django's WSGI support.
  231. * When invoking a management command.
  232. It must be called explicitly in other cases, for instance in plain Python
  233. scripts.
  234. .. currentmodule:: django.apps
  235. The application registry is initialized in three stages. At each stage, Django
  236. processes all applications in the order of :setting:`INSTALLED_APPS`.
  237. #. First Django imports each item in :setting:`INSTALLED_APPS`.
  238. If it's an application configuration class, Django imports the root package
  239. of the application, defined by its :attr:`~AppConfig.name` attribute. If
  240. it's a Python package, Django creates a default application configuration.
  241. *At this stage, your code shouldn't import any models!*
  242. In other words, your applications' root packages and the modules that
  243. define your application configuration classes shouldn't import any models,
  244. even indirectly.
  245. Strictly speaking, Django allows importing models once their application
  246. configuration is loaded. However, in order to avoid needless constraints on
  247. the order of :setting:`INSTALLED_APPS`, it's strongly recommended not
  248. import any models at this stage.
  249. Once this stage completes, APIs that operate on application configurations
  250. such as :meth:`~apps.get_app_config()` become usable.
  251. #. Then Django attempts to import the ``models`` submodule of each application,
  252. if there is one.
  253. You must define or import all models in your application's ``models.py`` or
  254. ``models/__init__.py``. Otherwise, the application registry may not be fully
  255. populated at this point, which could cause the ORM to malfunction.
  256. Once this stage completes, APIs that operate on models such as
  257. :meth:`~apps.get_model()` become usable.
  258. #. Finally Django runs the :meth:`~AppConfig.ready()` method of each application
  259. configuration.
  260. .. _applications-troubleshooting:
  261. Troubleshooting
  262. ---------------
  263. Here are some common problems that you may encounter during initialization:
  264. * ``AppRegistryNotReady`` This happens when importing an application
  265. configuration or a models module triggers code that depends on the app
  266. registry.
  267. For example, :func:`~django.utils.translation.ugettext()` uses the app
  268. registry to look up translation catalogs in applications. To translate at
  269. import time, you need :func:`~django.utils.translation.ugettext_lazy()`
  270. instead. (Using :func:`~django.utils.translation.ugettext()` would be a bug,
  271. because the translation would happen at import time, rather than at each
  272. request depending on the active language.)
  273. Executing database queries with the ORM at import time in models modules
  274. will also trigger this exception. The ORM cannot function properly until all
  275. models are available.
  276. Another common culprit is :func:`django.contrib.auth.get_user_model()`. Use
  277. the :setting:`AUTH_USER_MODEL` setting to reference the User model at import
  278. time.
  279. This exception also happens if you forget to call :func:`django.setup()` in
  280. a standalone Python script.
  281. * ``ImportError: cannot import name ...`` This happens if the import sequence
  282. ends up in a loop.
  283. To eliminate such problems, you should minimize dependencies between your
  284. models modules and do as little work as possible at import time. To avoid
  285. executing code at import time, you can move it into a function and cache its
  286. results. The code will be executed when you first need its results. This
  287. concept is known as "lazy evaluation".
  288. * ``django.contrib.admin`` automatically performs autodiscovery of ``admin``
  289. modules in installed applications. To prevent it, change your
  290. :setting:`INSTALLED_APPS` to contain
  291. ``'django.contrib.admin.apps.SimpleAdminConfig'`` instead of
  292. ``'django.contrib.admin'``.