| 1 |
============ |
| 2 |
Applications |
| 3 |
============ |
| 4 |
|
| 5 |
.. module:: django.apps |
| 6 |
|
| 7 |
Django contains a registry of installed applications that stores configuration |
| 8 |
and provides introspection. It also maintains a list of available :doc:`models |
| 9 |
</topics/db/models>`. |
| 10 |
|
| 11 |
This registry is called :attr:`~django.apps.apps` and it's available in |
| 12 |
:mod:`django.apps`: |
| 13 |
|
| 14 |
.. code-block:: pycon |
| 15 |
|
| 16 |
>>> from django.apps import apps |
| 17 |
>>> apps.get_app_config("admin").verbose_name |
| 18 |
'Administration' |
| 19 |
|
| 20 |
Projects and applications |
| 21 |
========================= |
| 22 |
|
| 23 |
The term **project** describes a Django web application. The project Python |
| 24 |
package is defined primarily by a settings module, but it usually contains |
| 25 |
other things. For example, when you run ``django-admin startproject mysite`` |
| 26 |
you'll get a ``mysite`` project directory that contains a ``mysite`` Python |
| 27 |
package with ``settings.py``, ``urls.py``, ``asgi.py`` and ``wsgi.py``. The |
| 28 |
project package is often extended to include things like fixtures, CSS, and |
| 29 |
templates which aren't tied to a particular application. |
| 30 |
|
| 31 |
A **project's root directory** (the one that contains ``manage.py``) is usually |
| 32 |
the container for all of a project's applications which aren't installed |
| 33 |
separately. |
| 34 |
|
| 35 |
The term **application** describes a Python package that provides some set of |
| 36 |
features. Applications :doc:`may be reused </intro/reusable-apps/>` in various |
| 37 |
projects. |
| 38 |
|
| 39 |
Applications include some combination of models, views, templates, template |
| 40 |
tags, static files, URLs, middleware, etc. They're generally wired into |
| 41 |
projects with the :setting:`INSTALLED_APPS` setting and optionally with other |
| 42 |
mechanisms such as URLconfs, the :setting:`MIDDLEWARE` setting, or template |
| 43 |
inheritance. |
| 44 |
|
| 45 |
It is important to understand that a Django application is a set of code |
| 46 |
that interacts with various parts of the framework. There's no such thing as |
| 47 |
an ``Application`` object. However, there's a few places where Django needs to |
| 48 |
interact with installed applications, mainly for configuration and also for |
| 49 |
introspection. That's why the application registry maintains metadata in an |
| 50 |
:class:`~django.apps.AppConfig` instance for each installed application. |
| 51 |
|
| 52 |
There's no restriction that a project package can't also be considered an |
| 53 |
application and have models, etc. (which would require adding it to |
| 54 |
:setting:`INSTALLED_APPS`). |
| 55 |
|
| 56 |
.. _configuring-applications-ref: |
| 57 |
|
| 58 |
Configuring applications |
| 59 |
======================== |
| 60 |
|
| 61 |
To configure an application, create an ``apps.py`` module inside the |
| 62 |
application, then define a subclass of :class:`AppConfig` there. |
| 63 |
|
| 64 |
When :setting:`INSTALLED_APPS` contains the dotted path to an application |
| 65 |
module, by default, if Django finds exactly one :class:`AppConfig` subclass in |
| 66 |
the ``apps.py`` submodule, it uses that configuration for the application. This |
| 67 |
behavior may be disabled by setting :attr:`AppConfig.default` to ``False``. |
| 68 |
|
| 69 |
If the ``apps.py`` module contains more than one :class:`AppConfig` subclass, |
| 70 |
Django will look for a single one where :attr:`AppConfig.default` is ``True``. |
| 71 |
|
| 72 |
If no :class:`AppConfig` subclass is found, the base :class:`AppConfig` class |
| 73 |
will be used. |
| 74 |
|
| 75 |
Alternatively, :setting:`INSTALLED_APPS` may contain the dotted path to a |
| 76 |
configuration class to specify it explicitly:: |
| 77 |
|
| 78 |
INSTALLED_APPS = [ |
| 79 |
..., |
| 80 |
"polls.apps.PollsAppConfig", |
| 81 |
..., |
| 82 |
] |
| 83 |
|
| 84 |
For application authors |
| 85 |
----------------------- |
| 86 |
|
| 87 |
If you're creating a pluggable app called "Rock ’n’ roll", here's how you |
| 88 |
would provide a proper name for the admin:: |
| 89 |
|
| 90 |
# rock_n_roll/apps.py |
| 91 |
|
| 92 |
from django.apps import AppConfig |
| 93 |
|
| 94 |
|
| 95 |
class RockNRollConfig(AppConfig): |
| 96 |
name = "rock_n_roll" |
| 97 |
verbose_name = "Rock ’n’ roll" |
| 98 |
|
| 99 |
``RockNRollConfig`` will be loaded automatically when :setting:`INSTALLED_APPS` |
| 100 |
contains ``'rock_n_roll'``. If you need to prevent this, set |
| 101 |
:attr:`~AppConfig.default` to ``False`` in the class definition. |
| 102 |
|
| 103 |
You can provide several :class:`AppConfig` subclasses with different behaviors. |
| 104 |
To tell Django which one to use by default, set :attr:`~AppConfig.default` to |
| 105 |
``True`` in its definition. If your users want to pick a non-default |
| 106 |
configuration, they must replace ``'rock_n_roll'`` with the dotted path to that |
| 107 |
specific class in their :setting:`INSTALLED_APPS` setting. |
| 108 |
|
| 109 |
The :attr:`AppConfig.name` attribute tells Django which application this |
| 110 |
configuration applies to. You can define any other attribute documented in the |
| 111 |
:class:`~django.apps.AppConfig` API reference. |
| 112 |
|
| 113 |
:class:`AppConfig` subclasses may be defined anywhere. The ``apps.py`` |
| 114 |
convention merely allows Django to load them automatically when |
| 115 |
:setting:`INSTALLED_APPS` contains the path to an application module rather |
| 116 |
than the path to a configuration class. |
| 117 |
|
| 118 |
.. note:: |
| 119 |
|
| 120 |
If your code imports the application registry in an application's |
| 121 |
``__init__.py``, the name ``apps`` will clash with the ``apps`` submodule. |
| 122 |
The best practice is to move that code to a submodule and import it. A |
| 123 |
workaround is to import the registry under a different name:: |
| 124 |
|
| 125 |
from django.apps import apps as django_apps |
| 126 |
|
| 127 |
For application users |
| 128 |
--------------------- |
| 129 |
|
| 130 |
If you're using "Rock ’n’ roll" in a project called ``anthology``, but you |
| 131 |
want it to show up as "Jazz Manouche" instead, you can provide your own |
| 132 |
configuration:: |
| 133 |
|
| 134 |
# anthology/apps.py |
| 135 |
|
| 136 |
from rock_n_roll.apps import RockNRollConfig |
| 137 |
|
| 138 |
|
| 139 |
class JazzManoucheConfig(RockNRollConfig): |
| 140 |
verbose_name = "Jazz Manouche" |
| 141 |
|
| 142 |
|
| 143 |
# anthology/settings.py |
| 144 |
|
| 145 |
INSTALLED_APPS = [ |
| 146 |
"anthology.apps.JazzManoucheConfig", |
| 147 |
# ... |
| 148 |
] |
| 149 |
|
| 150 |
This example shows project-specific configuration classes located in a |
| 151 |
submodule called ``apps.py``. This is a convention, not a requirement. |
| 152 |
:class:`AppConfig` subclasses may be defined anywhere. |
| 153 |
|
| 154 |
In this situation, :setting:`INSTALLED_APPS` must contain the dotted path to |
| 155 |
the configuration class because it lives outside of an application and thus |
| 156 |
cannot be automatically detected. |
| 157 |
|
| 158 |
Application configuration |
| 159 |
========================= |
| 160 |
|
| 161 |
.. class:: AppConfig |
| 162 |
|
| 163 |
Application configuration objects store metadata for an application. Some |
| 164 |
attributes can be configured in :class:`~django.apps.AppConfig` |
| 165 |
subclasses. Others are set by Django and read-only. |
| 166 |
|
| 167 |
Configurable attributes |
| 168 |
----------------------- |
| 169 |
|
| 170 |
.. attribute:: AppConfig.name |
| 171 |
|
| 172 |
Full Python path to the application, e.g. ``'django.contrib.admin'``. |
| 173 |
|
| 174 |
This attribute defines which application the configuration applies to. It |
| 175 |
must be set in all :class:`~django.apps.AppConfig` subclasses. |
| 176 |
|
| 177 |
It must be unique across a Django project. |
| 178 |
|
| 179 |
.. attribute:: AppConfig.label |
| 180 |
|
| 181 |
Short name for the application, e.g. ``'admin'`` |
| 182 |
|
| 183 |
This attribute allows relabeling an application when two applications |
| 184 |
have conflicting labels. It defaults to the last component of ``name``. |
| 185 |
It should be a valid Python identifier. |
| 186 |
|
| 187 |
It must be unique across a Django project. |
| 188 |
|
| 189 |
.. warning:: |
| 190 |
|
| 191 |
Changing this attribute after migrations have been applied for an |
| 192 |
application will result in breaking changes to a project or, in the |
| 193 |
case of a reusable app, any existing installs of that app. This is |
| 194 |
because ``AppConfig.label`` is used in database tables and migration |
| 195 |
files when referencing an app in the dependencies list. |
| 196 |
|
| 197 |
.. attribute:: AppConfig.verbose_name |
| 198 |
|
| 199 |
Human-readable name for the application, e.g. "Administration". |
| 200 |
|
| 201 |
This attribute defaults to ``label.title()``. |
| 202 |
|
| 203 |
.. attribute:: AppConfig.path |
| 204 |
|
| 205 |
Filesystem path to the application directory, e.g. |
| 206 |
``'/usr/lib/pythonX.Y/dist-packages/django/contrib/admin'``. |
| 207 |
|
| 208 |
In most cases, Django can automatically detect and set this, but you can |
| 209 |
also provide an explicit override as a class attribute on your |
| 210 |
:class:`~django.apps.AppConfig` subclass. In a few situations this is |
| 211 |
required; for instance if the app package is a `namespace package`_ with |
| 212 |
multiple paths. |
| 213 |
|
| 214 |
.. attribute:: AppConfig.default |
| 215 |
|
| 216 |
Set this attribute to ``False`` to prevent Django from selecting a |
| 217 |
configuration class automatically. This is useful when ``apps.py`` defines |
| 218 |
only one :class:`AppConfig` subclass but you don't want Django to use it by |
| 219 |
default. |
| 220 |
|
| 221 |
Set this attribute to ``True`` to tell Django to select a configuration |
| 222 |
class automatically. This is useful when ``apps.py`` defines more than one |
| 223 |
:class:`AppConfig` subclass and you want Django to use one of them by |
| 224 |
default. |
| 225 |
|
| 226 |
By default, this attribute isn't set. |
| 227 |
|
| 228 |
.. attribute:: AppConfig.default_auto_field |
| 229 |
|
| 230 |
The implicit primary key type to add to models within this app. You can |
| 231 |
use this to keep :class:`~django.db.models.AutoField` as the primary key |
| 232 |
type for third party applications. |
| 233 |
|
| 234 |
By default, this is the value of :setting:`DEFAULT_AUTO_FIELD`. |
| 235 |
|
| 236 |
Read-only attributes |
| 237 |
-------------------- |
| 238 |
|
| 239 |
.. attribute:: AppConfig.module |
| 240 |
|
| 241 |
Root module for the application, e.g. ``<module 'django.contrib.admin' from |
| 242 |
'django/contrib/admin/__init__.py'>``. |
| 243 |
|
| 244 |
.. attribute:: AppConfig.models_module |
| 245 |
|
| 246 |
Module containing the models, e.g. ``<module 'django.contrib.admin.models' |
| 247 |
from 'django/contrib/admin/models.py'>``. |
| 248 |
|
| 249 |
It may be ``None`` if the application doesn't contain a ``models`` module. |
| 250 |
Note that the database related signals such as |
| 251 |
:data:`~django.db.models.signals.pre_migrate` and |
| 252 |
:data:`~django.db.models.signals.post_migrate` |
| 253 |
are only emitted for applications that have a ``models`` module. |
| 254 |
|
| 255 |
Methods |
| 256 |
------- |
| 257 |
|
| 258 |
.. method:: AppConfig.get_models(include_auto_created=False, include_swapped=False) |
| 259 |
|
| 260 |
Returns an iterable of :class:`~django.db.models.Model` classes for this |
| 261 |
application. |
| 262 |
|
| 263 |
Requires the app registry to be fully populated. |
| 264 |
|
| 265 |
.. method:: AppConfig.get_model(model_name, require_ready=True) |
| 266 |
|
| 267 |
Returns the :class:`~django.db.models.Model` with the given |
| 268 |
``model_name``. ``model_name`` is case-insensitive. |
| 269 |
|
| 270 |
Raises :exc:`LookupError` if no such model exists in this application. |
| 271 |
|
| 272 |
Requires the app registry to be fully populated unless the |
| 273 |
``require_ready`` argument is set to ``False``. ``require_ready`` behaves |
| 274 |
exactly as in :meth:`apps.get_model()`. |
| 275 |
|
| 276 |
.. method:: AppConfig.ready() |
| 277 |
|
| 278 |
Subclasses can override this method to perform initialization tasks such |
| 279 |
as registering signals. It is called as soon as the registry is fully |
| 280 |
populated. |
| 281 |
|
| 282 |
Although you can't import models at the module-level where |
| 283 |
:class:`~django.apps.AppConfig` classes are defined, you can import them in |
| 284 |
``ready()``, using either an ``import`` statement or |
| 285 |
:meth:`~AppConfig.get_model`. |
| 286 |
|
| 287 |
If you're registering :mod:`model signals <django.db.models.signals>`, you |
| 288 |
can refer to the sender by its string label instead of using the model |
| 289 |
class itself. |
| 290 |
|
| 291 |
Example:: |
| 292 |
|
| 293 |
from django.apps import AppConfig |
| 294 |
from django.db.models.signals import pre_save |
| 295 |
|
| 296 |
|
| 297 |
class RockNRollConfig(AppConfig): |
| 298 |
# ... |
| 299 |
|
| 300 |
def ready(self): |
| 301 |
# importing model classes |
| 302 |
from .models import MyModel # or... |
| 303 |
|
| 304 |
MyModel = self.get_model("MyModel") |
| 305 |
|
| 306 |
# registering signals with the model's string label |
| 307 |
pre_save.connect(receiver, sender="app_label.MyModel") |
| 308 |
|
| 309 |
.. warning:: |
| 310 |
|
| 311 |
Although you can access model classes as described above, avoid |
| 312 |
interacting with the database in your :meth:`ready()` implementation. |
| 313 |
This includes model methods that execute queries |
| 314 |
(:meth:`~django.db.models.Model.save()`, |
| 315 |
:meth:`~django.db.models.Model.delete()`, manager methods etc.), and |
| 316 |
also raw SQL queries via ``django.db.connection``. Your |
| 317 |
:meth:`ready()` method will run during startup of every management |
| 318 |
command. For example, even though the test database configuration is |
| 319 |
separate from the production settings, ``manage.py test`` would still |
| 320 |
execute some queries against your **production** database! |
| 321 |
|
| 322 |
.. note:: |
| 323 |
|
| 324 |
In the usual initialization process, the ``ready`` method is only called |
| 325 |
once by Django. But in some corner cases, particularly in tests which |
| 326 |
are fiddling with installed applications, ``ready`` might be called more |
| 327 |
than once. In that case, either write idempotent methods, or put a flag |
| 328 |
on your ``AppConfig`` classes to prevent rerunning code which should |
| 329 |
be executed exactly one time. |
| 330 |
|
| 331 |
.. _namespace package: |
| 332 |
|
| 333 |
Namespace packages as apps |
| 334 |
-------------------------- |
| 335 |
|
| 336 |
Python packages without an ``__init__.py`` file are known as "namespace |
| 337 |
packages" and may be spread across multiple directories at different locations |
| 338 |
on ``sys.path`` (see :pep:`420`). |
| 339 |
|
| 340 |
Django applications require a single base filesystem path where Django |
| 341 |
(depending on configuration) will search for templates, static assets, |
| 342 |
etc. Thus, namespace packages may only be Django applications if one of the |
| 343 |
following is true: |
| 344 |
|
| 345 |
#. The namespace package actually has only a single location (i.e. is not |
| 346 |
spread across more than one directory.) |
| 347 |
|
| 348 |
#. The :class:`~django.apps.AppConfig` class used to configure the application |
| 349 |
has a :attr:`~django.apps.AppConfig.path` class attribute, which is the |
| 350 |
absolute directory path Django will use as the single base path for the |
| 351 |
application. |
| 352 |
|
| 353 |
If neither of these conditions is met, Django will raise |
| 354 |
:exc:`~django.core.exceptions.ImproperlyConfigured`. |
| 355 |
|
| 356 |
Application registry |
| 357 |
==================== |
| 358 |
|
| 359 |
.. data:: apps |
| 360 |
|
| 361 |
The application registry provides the following public API. Methods that |
| 362 |
aren't listed below are considered private and may change without notice. |
| 363 |
|
| 364 |
.. attribute:: apps.ready |
| 365 |
|
| 366 |
Boolean attribute that is set to ``True`` after the registry is fully |
| 367 |
populated and all :meth:`AppConfig.ready` methods are called. |
| 368 |
|
| 369 |
.. method:: apps.get_app_configs() |
| 370 |
|
| 371 |
Returns an iterable of :class:`~django.apps.AppConfig` instances. |
| 372 |
|
| 373 |
.. method:: apps.get_app_config(app_label) |
| 374 |
|
| 375 |
Returns an :class:`~django.apps.AppConfig` for the application with the |
| 376 |
given ``app_label``. Raises :exc:`LookupError` if no such application |
| 377 |
exists. |
| 378 |
|
| 379 |
.. method:: apps.is_installed(app_name) |
| 380 |
|
| 381 |
Checks whether an application with the given name exists in the registry. |
| 382 |
``app_name`` is the full name of the app, e.g. ``'django.contrib.admin'``. |
| 383 |
|
| 384 |
.. method:: apps.get_model(app_label, model_name, require_ready=True) |
| 385 |
|
| 386 |
Returns the :class:`~django.db.models.Model` with the given ``app_label`` |
| 387 |
and ``model_name``. As a shortcut, this method also accepts a single |
| 388 |
argument in the form ``app_label.model_name``. ``model_name`` is |
| 389 |
case-insensitive. |
| 390 |
|
| 391 |
Raises :exc:`LookupError` if no such application or model exists. Raises |
| 392 |
:exc:`ValueError` when called with a single argument that doesn't contain |
| 393 |
exactly one dot. |
| 394 |
|
| 395 |
Requires the app registry to be fully populated unless the |
| 396 |
``require_ready`` argument is set to ``False``. |
| 397 |
|
| 398 |
Setting ``require_ready`` to ``False`` allows looking up models |
| 399 |
:ref:`while the app registry is being populated <app-loading-process>`, |
| 400 |
specifically during the second phase where it imports models. Then |
| 401 |
``get_model()`` has the same effect as importing the model. The main use |
| 402 |
case is to configure model classes with settings, such as |
| 403 |
:setting:`AUTH_USER_MODEL`. |
| 404 |
|
| 405 |
When ``require_ready`` is ``False``, ``get_model()`` returns a model class |
| 406 |
that may not be fully functional (reverse accessors may be missing, for |
| 407 |
example) until the app registry is fully populated. For this reason, it's |
| 408 |
best to leave ``require_ready`` to the default value of ``True`` whenever |
| 409 |
possible. |
| 410 |
|
| 411 |
.. _app-loading-process: |
| 412 |
|
| 413 |
Initialization process |
| 414 |
====================== |
| 415 |
|
| 416 |
How applications are loaded |
| 417 |
--------------------------- |
| 418 |
|
| 419 |
When Django starts, :func:`django.setup()` is responsible for populating the |
| 420 |
application registry. |
| 421 |
|
| 422 |
.. currentmodule:: django |
| 423 |
|
| 424 |
.. function:: setup(set_prefix=True) |
| 425 |
|
| 426 |
Configures Django by: |
| 427 |
|
| 428 |
* Loading the settings. |
| 429 |
* Setting up logging. |
| 430 |
* If ``set_prefix`` is True, setting the URL resolver script prefix to |
| 431 |
:setting:`FORCE_SCRIPT_NAME` if defined, or ``/`` otherwise. |
| 432 |
* Initializing the application registry. |
| 433 |
|
| 434 |
This function is called automatically: |
| 435 |
|
| 436 |
* When running an HTTP server via Django's ASGI or WSGI support. |
| 437 |
* When invoking a management command. |
| 438 |
|
| 439 |
It must be called explicitly in other cases, for instance in plain Python |
| 440 |
scripts. |
| 441 |
|
| 442 |
.. currentmodule:: django.apps |
| 443 |
|
| 444 |
The application registry is initialized in three stages. At each stage, Django |
| 445 |
processes all applications in the order of :setting:`INSTALLED_APPS`. |
| 446 |
|
| 447 |
#. First Django imports each item in :setting:`INSTALLED_APPS`. |
| 448 |
|
| 449 |
If it's an application configuration class, Django imports the root package |
| 450 |
of the application, defined by its :attr:`~AppConfig.name` attribute. If |
| 451 |
it's a Python package, Django looks for an application configuration in an |
| 452 |
``apps.py`` submodule, or else creates a default application configuration. |
| 453 |
|
| 454 |
*At this stage, your code shouldn't import any models!* |
| 455 |
|
| 456 |
In other words, your applications' root packages and the modules that |
| 457 |
define your application configuration classes shouldn't import any models, |
| 458 |
even indirectly. |
| 459 |
|
| 460 |
Strictly speaking, Django allows importing models once their application |
| 461 |
configuration is loaded. However, in order to avoid needless constraints on |
| 462 |
the order of :setting:`INSTALLED_APPS`, it's strongly recommended not |
| 463 |
import any models at this stage. |
| 464 |
|
| 465 |
Once this stage completes, APIs that operate on application configurations |
| 466 |
such as :meth:`~apps.get_app_config()` become usable. |
| 467 |
|
| 468 |
#. Then Django attempts to import the ``models`` submodule of each application, |
| 469 |
if there is one. |
| 470 |
|
| 471 |
You must define or import all models in your application's ``models.py`` or |
| 472 |
``models/__init__.py``. Otherwise, the application registry may not be fully |
| 473 |
populated at this point, which could cause the ORM to malfunction. |
| 474 |
|
| 475 |
Once this stage completes, APIs that operate on models such as |
| 476 |
:meth:`~apps.get_model()` become usable. |
| 477 |
|
| 478 |
#. Finally Django runs the :meth:`~AppConfig.ready()` method of each application |
| 479 |
configuration. |
| 480 |
|
| 481 |
.. _applications-troubleshooting: |
| 482 |
|
| 483 |
Troubleshooting |
| 484 |
--------------- |
| 485 |
|
| 486 |
Here are some common problems that you may encounter during initialization: |
| 487 |
|
| 488 |
* :class:`~django.core.exceptions.AppRegistryNotReady`: This happens when |
| 489 |
importing an application configuration or a models module triggers code that |
| 490 |
depends on the app registry. |
| 491 |
|
| 492 |
For example, :func:`~django.utils.translation.gettext()` uses the app |
| 493 |
registry to look up translation catalogs in applications. To translate at |
| 494 |
import time, you need :func:`~django.utils.translation.gettext_lazy()` |
| 495 |
instead. (Using :func:`~django.utils.translation.gettext()` would be a bug, |
| 496 |
because the translation would happen at import time, rather than at each |
| 497 |
request depending on the active language.) |
| 498 |
|
| 499 |
Executing database queries with the ORM at import time in models modules |
| 500 |
will also trigger this exception. The ORM cannot function properly until all |
| 501 |
models are available. |
| 502 |
|
| 503 |
This exception also happens if you forget to call :func:`django.setup()` in |
| 504 |
a standalone Python script. |
| 505 |
|
| 506 |
* ``ImportError: cannot import name ...`` This happens if the import sequence |
| 507 |
ends up in a loop. |
| 508 |
|
| 509 |
To eliminate such problems, you should minimize dependencies between your |
| 510 |
models modules and do as little work as possible at import time. To avoid |
| 511 |
executing code at import time, you can move it into a function and cache its |
| 512 |
results. The code will be executed when you first need its results. This |
| 513 |
concept is known as "lazy evaluation". |
| 514 |
|
| 515 |
* ``django.contrib.admin`` automatically performs autodiscovery of ``admin`` |
| 516 |
modules in installed applications. To prevent it, change your |
| 517 |
:setting:`INSTALLED_APPS` to contain |
| 518 |
``'django.contrib.admin.apps.SimpleAdminConfig'`` instead of |
| 519 |
``'django.contrib.admin'``. |
| 520 |
|
| 521 |
* ``RuntimeWarning: Accessing the database during app initialization is |
| 522 |
discouraged.`` This warning is triggered for database queries executed before |
| 523 |
apps are ready, such as during module imports or in the |
| 524 |
:meth:`AppConfig.ready` method. Such premature database queries are |
| 525 |
discouraged because they will run during the startup of every management |
| 526 |
command, which will slow down your project startup, potentially cache stale |
| 527 |
data, and can even fail if migrations are pending. |
| 528 |
|
| 529 |
For example, a common mistake is making a database query to populate form |
| 530 |
field choices:: |
| 531 |
|
| 532 |
class LocationForm(forms.Form): |
| 533 |
country = forms.ChoiceField(choices=[c.name for c in Country.objects.all()]) |
| 534 |
|
| 535 |
In the example above, the query from ``Country.objects.all()`` is executed |
| 536 |
during module import, because the ``QuerySet`` is iterated over. To avoid the |
| 537 |
warning, the form could use a :class:`~django.forms.ModelChoiceField` |
| 538 |
instead:: |
| 539 |
|
| 540 |
class LocationForm(forms.Form): |
| 541 |
country = forms.ModelChoiceField(queryset=Country.objects.all()) |
| 542 |
|
| 543 |
To make it easier to find the code that triggered this warning, you can make |
| 544 |
Python :ref:`treat warnings as errors <python:warning-filter>` to reveal the |
| 545 |
stack trace, for example with ``python -Werror manage.py shell``. |