Django contains a registry of installed applications that stores configuration and provides introspection. It also maintains a list of available models.
>>> from django.apps import apps >>> apps.get_app_config('admin').verbose_name 'Admin'
Projects and applications¶
The term project describes a Django web application. The project Python
package is defined primarily by a settings module, but it usually contains
other things. For example, when you run
django-admin startproject mysite
you’ll get a
mysite project directory that contains a
wsgi.py. The project package
is often extended to include things like fixtures, CSS, and templates which
aren’t tied to a particular application.
A project’s root directory (the one that contains
manage.py) is usually
the container for all of a project’s applications which aren’t installed
The term application describes a Python package that provides some set of features. Applications may be reused in various projects.
Applications include some combination of models, views, templates, template
tags, static files, URLs, middleware, etc. They’re generally wired into
projects with the
INSTALLED_APPS setting and optionally with other
mechanisms such as URLconfs, the
MIDDLEWARE setting, or template
It is important to understand that a Django application is just a set of code
that interacts with various parts of the framework. There’s no such thing as
Application object. However, there’s a few places where Django needs to
interact with installed applications, mainly for configuration and also for
introspection. That’s why the application registry maintains metadata in an
AppConfig instance for each installed application.
There’s no restriction that a project package can’t also be considered an
application and have models, etc. (which would require adding it to
INSTALLED_APPS simply contains the dotted path to an
application module, Django checks for a
default_app_config variable in
If it’s defined, it’s the dotted path to the
subclass for that application.
If there is no
default_app_config, Django uses the base
For application users¶
If you’re using “Rock ’n’ roll” in a project called
anthology, but you
want it to show up as “Jazz Manouche” instead, you can provide your own
# anthology/apps.py from rock_n_roll.apps import RockNRollConfig class JazzManoucheConfig(RockNRollConfig): verbose_name = "Jazz Manouche" # anthology/settings.py INSTALLED_APPS = [ 'anthology.apps.JazzManoucheConfig', # ... ]
Again, defining project-specific configuration classes in a submodule called
apps is a convention, not a requirement.
Application configuration objects store metadata for an application. Some attributes can be configured in
AppConfigsubclasses. Others are set by Django and read-only.
Full Python path to the application, e.g.
This attribute defines which application the configuration applies to. It must be set in all
It must be unique across a Django project.
Short name for the application, e.g.
This attribute allows relabeling an application when two applications have conflicting labels. It defaults to the last component of
name. It should be a valid Python identifier.
It must be unique across a Django project.
Human-readable name for the application, e.g. “Administration”.
This attribute defaults to
Filesystem path to the application directory, e.g.
In most cases, Django can automatically detect and set this, but you can also provide an explicit override as a class attribute on your
AppConfigsubclass. In a few situations this is required; for instance if the app package is a namespace package with multiple paths.
Root module for the application, e.g.
<module 'django.contrib.admin' from 'django/contrib/admin/__init__.pyc'>.
Module containing the models, e.g.
<module 'django.contrib.admin.models' from 'django/contrib/admin/models.pyc'>.
It may be
Noneif the application doesn’t contain a
modelsmodule. Note that the database related signals such as
post_migrateare only emitted for applications that have a
Subclasses can override this method to perform initialization tasks such as registering signals. It is called as soon as the registry is fully populated.
If you’re registering
model signals, you can refer to the sender by its string label instead of using the model class itself.
from django.db.models.signals import pre_save def ready(self): # importing model classes from .models import MyModel # or... MyModel = self.get_model('MyModel') # registering signals with the model's string label pre_save.connect(receiver, sender='app_label.MyModel')
Although you can access model classes as described above, avoid interacting with the database in your
ready()implementation. This includes model methods that execute queries (
delete(), manager methods etc.), and also raw SQL queries via
ready()method will run during startup of every management command. For example, even though the test database configuration is separate from the production settings,
manage.py testwould still execute some queries against your production database!
In the usual initialization process, the
readymethod is only called once by Django. But in some corner cases, particularly in tests which are fiddling with installed applications,
readymight be called more than once. In that case, either write idempotent methods, or put a flag on your
AppConfigclasses to prevent re-running code which should be executed exactly one time.
Namespace packages as apps (Python 3.3+)¶
Python versions 3.3 and later support Python packages without an
__init__.py file. These packages are known as “namespace packages” and may
be spread across multiple directories at different locations on
(see PEP 420).
Django applications require a single base filesystem path where Django (depending on configuration) will search for templates, static assets, etc. Thus, namespace packages may only be Django applications if one of the following is true:
- The namespace package actually has only a single location (i.e. is not spread across more than one directory.)
AppConfigclass used to configure the application has a
pathclass attribute, which is the absolute directory path Django will use as the single base path for the application.
If neither of these conditions is met, Django will raise
The application registry provides the following public API. Methods that aren’t listed below are considered private and may change without notice.
Boolean attribute that is set to
Trueafter the registry is fully populated and all
AppConfig.ready()methods are called.
Checks whether an application with the given name exists in the registry.
app_nameis the full name of the app, e.g.
Modelwith the given
model_name. As a shortcut, this method also accepts a single argument in the form
How applications are loaded¶
When Django starts,
django.setup() is responsible for populating the
Configures Django by:
Changed in Django 1.10:
- Loading the settings.
- Setting up logging.
set_prefixis True, setting the URL resolver script prefix to
FORCE_SCRIPT_NAMEif defined, or
- Initializing the application registry.
The ability to set the URL resolver script prefix is new.
This function is called automatically:
- When running an HTTP server via Django’s WSGI support.
- When invoking a management command.
It must be called explicitly in other cases, for instance in plain Python scripts.
The application registry is initialized in three stages. At each stage, Django
processes all applications in the order of
First Django imports each item in
If it’s an application configuration class, Django imports the root package of the application, defined by its
nameattribute. If it’s a Python package, Django creates a default application configuration.
At this stage, your code shouldn’t import any models!
In other words, your applications’ root packages and the modules that define your application configuration classes shouldn’t import any models, even indirectly.
Strictly speaking, Django allows importing models once their application configuration is loaded. However, in order to avoid needless constraints on the order of
INSTALLED_APPS, it’s strongly recommended not import any models at this stage.
Once this stage completes, APIs that operate on application configurations such as
Then Django attempts to import the
modelssubmodule of each application, if there is one.
You must define or import all models in your application’s
models/__init__.py. Otherwise, the application registry may not be fully populated at this point, which could cause the ORM to malfunction.
Once this stage completes, APIs that operate on models such as
Finally Django runs the
ready()method of each application configuration.
Here are some common problems that you may encounter during initialization:
AppRegistryNotReady: This happens when importing an application configuration or a models module triggers code that depends on the app registry.
ugettext()uses the app registry to look up translation catalogs in applications. To translate at import time, you need
ugettext()would be a bug, because the translation would happen at import time, rather than at each request depending on the active language.)
Executing database queries with the ORM at import time in models modules will also trigger this exception. The ORM cannot function properly until all models are available.
This exception also happens if you forget to call
django.setup()in a standalone Python script.
ImportError: cannot import name ...This happens if the import sequence ends up in a loop.
To eliminate such problems, you should minimize dependencies between your models modules and do as little work as possible at import time. To avoid executing code at import time, you can move it into a function and cache its results. The code will be executed when you first need its results. This concept is known as “lazy evaluation”.
django.contrib.adminautomatically performs autodiscovery of
adminmodules in installed applications. To prevent it, change your