アプリケーション¶
Django には、設定の保存と調査の手段を提供するインストール済みアプリケーションのレジストリがあり、利用可能な モデル のリストもアクセスできます。
このレジストリは apps と呼ばれ、 django.apps:: にあります。
>>> from django.apps import apps
>>> apps.get_app_config('admin').verbose_name
'Administration'
プロジェクトとアプリケーション¶
プロジェクト (project) という単語は、Django の web アプリケーションを指します。プロジェクトの Python パッケージは主に settings モジュールで定義されますが、通常は他のファイルも含まれます。たとえば、 django-admin startproject mysite を実行すると、mysite プロジェクトディレクトリが作成され、その中には settings.py、urls.py、asgi.py、wsgi.py などのファイルが含まれる mysite Python パッケージが作られます。プロジェクトパッケージは、fixture や CSS、テンプレートなど特定のアプリケーションに束縛されないファイルも含まれることがふつうです。
プロジェクトのルートディレクトリ (manage.py があるディレクトリ) は、プロジェクトと一緒にインストールされるすべてのアプリケーションのコンテナとして機能します。
アプリケーション (application) という言葉は、何らかの機能を提供する Python パッケージを意味します。アプリケーションはさまざまなプロジェクトで 再利用する ことができます。
アプリケーションには、モデル、ビュー、テンプレート、テンプレートタグ、スタティックファイル、ミドルウェアなどが含まれます。これらは一般に INSTALLED_APPS 設定で有効になり、それ以外では URLconfs、 MIDDLEWARE 設定、テンプレート継承などの仕組みから使われます。
Django のアプリケーションは、フレームワークのさまざまなパーツとやりとりをするコードの集まりであると理解するのは大切です。Application オブジェクトのようなものは存在しません。しかしながら、Django がインストール済みのアプリケーションの主に設定やイントロスペクションとやりとりをする必要があることもあります。そのため、インストールアプリケーションごとのメタデータは、アプリケーションレジストリが AppConfig インスタンス内に保存しています。
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).
アプリケーションを設定する¶
アプリケーションを設定するためには、アプリケーション内に apps.py モジュールを作成し、そこに AppConfig のサブクラスを定義してください。
When INSTALLED_APPS contains the dotted path to an application
module, by default, if Django finds exactly one AppConfig subclass in
the apps.py submodule, it uses that configuration for the application. This
behavior may be disabled by setting AppConfig.default to False.
apps.py モジュールに複数の AppConfig のサブクラスが含まれている場合、Djangoは AppConfig.default が `` True`` である単一のサブクラスを探します。
もし AppConfig のサブクラスが見つからなければ、 AppConfig の基底クラスが使用されます。
Alternatively, INSTALLED_APPS may contain the dotted path to a
configuration class to specify it explicitly:
INSTALLED_APPS = [
...
'polls.apps.PollsAppConfig',
...
]
アプリケーション開発者向け¶
例えば、あなたが"Rock 'n' roll"という名前のプラガブルなアプリケーションを作っているとしたら、このようにアプリケーションのadminに適切な名前をつけることになるでしょう:
# rock_n_roll/apps.py
from django.apps import AppConfig
class RockNRollConfig(AppConfig):
name = 'rock_n_roll'
verbose_name = "Rock ’n’ roll"
RockNRollConfig will be loaded automatically when INSTALLED_APPS
contains 'rock_n_roll'. If you need to prevent this, set
default to False in the class definition.
You can provide several AppConfig subclasses with different behaviors.
To tell Django which one to use by default, set default to
True in its definition. If your users want to pick a non-default
configuration, they must replace 'rock_n_roll' with the dotted path to that
specific class in their INSTALLED_APPS setting.
The AppConfig.name attribute tells Django which application this
configuration applies to. You can define any other attribute documented in the
AppConfig API reference.
AppConfig subclasses may be defined anywhere. The apps.py
convention merely allows Django to load them automatically when
INSTALLED_APPS contains the path to an application module rather
than the path to a configuration class.
注釈
If your code imports the application registry in an application's
__init__.py, the name apps will clash with the apps submodule.
The best practice is to move that code to a submodule and import it. A
workaround is to import the registry under a different name:
from django.apps import apps as django_apps
In previous versions, a default_app_config variable in the application
module was used to identify the default application configuration class.
アプリケーションユーザー向け¶
anthology という名前のプロジェクト内にて "Rock 'n' roll" を利用するものの、その表示は "Jazz Manouche" としたいとします。この場合は設定を以下のようにします。
# 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',
# ...
]
This example shows project-specific configuration classes located in a
submodule called apps.py. This is a convention, not a requirement.
AppConfig subclasses may be defined anywhere.
In this situation, INSTALLED_APPS must contain the dotted path to
the configuration class because it lives outside of an application and thus
cannot be automatically detected.
アプリケーションの設定¶
-
class
AppConfig[ソース]¶ Application configuration objects store metadata for an application. Some attributes can be configured in
AppConfigsubclasses. Others are set by Django and read-only.
設定可能な属性¶
-
AppConfig.name¶ Full Python path to the application, e.g.
'django.contrib.admin'.This attribute defines which application the configuration applies to. It must be set in all
AppConfigsubclasses.Djangoプロジェクト全体の中で固有である必要があります。
-
AppConfig.label¶ アプリケーション用のショートネーム 例 "'admin'"
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.Djangoプロジェクト全体の中で固有である必要があります。
-
AppConfig.verbose_name¶ Human-readable name for the application, e.g. "Administration".
This attribute defaults to
label.title().
-
AppConfig.path¶ Filesystem path to the application directory, e.g.
'/usr/lib/pythonX.Y/dist-packages/django/contrib/admin'.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.
-
AppConfig.default¶ - New in Django 3.2.
Set this attribute to
Falseto prevent Django from selecting a configuration class automatically. This is useful whenapps.pydefines only oneAppConfigsubclass but you don't want Django to use it by default.Set this attribute to
Trueto tell Django to select a configuration class automatically. This is useful whenapps.pydefines more than oneAppConfigsubclass and you want Django to use one of them by default.デフォルトではこの属性(attribute)は設定されていません。
-
AppConfig.default_auto_field¶ - New in Django 3.2.
The implicit primary key type to add to models within this app. You can use this to keep
AutoFieldas the primary key type for third party applications.By default, this is the value of
DEFAULT_AUTO_FIELD.
読み取り専用属性¶
-
AppConfig.module¶ Root module for the application, e.g.
<module 'django.contrib.admin' from 'django/contrib/admin/__init__.py'>.
-
AppConfig.models_module¶ Module containing the models, e.g.
<module 'django.contrib.admin.models' from 'django/contrib/admin/models.py'>.It may be
Noneif the application doesn't contain amodelsmodule. Note that the database related signals such aspre_migrateandpost_migrateare only emitted for applications that have amodelsmodule.
メソッド¶
-
AppConfig.get_models(include_auto_created=False, include_swapped=False)[ソース]¶ Returns an iterable of
Modelclasses for this application.Requires the app registry to be fully populated.
-
AppConfig.get_model(model_name, require_ready=True)[ソース]¶ Returns the
Modelwith the givenmodel_name.model_nameis case-insensitive.Raises
LookupErrorif no such model exists in this application.Requires the app registry to be fully populated unless the
require_readyargument is set toFalse.require_readybehaves exactly as inapps.get_model().
-
AppConfig.ready()[ソース]¶ Subclasses can override this method to perform initialization tasks such as registering signals. It is called as soon as the registry is fully populated.
Although you can't import models at the module-level where
AppConfigclasses are defined, you can import them inready(), using either animportstatement orget_model().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.apps import AppConfig from django.db.models.signals import pre_save class RockNRollConfig(AppConfig): # ... 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 (save(),delete(), manager methods etc.), and also raw SQL queries viadjango.db.connection. Yourready()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 yourAppConfigclasses to prevent re-running code which should be executed exactly one time.
Namespace packages as apps¶
Python packages without an __init__.py file are known as "namespace
packages" and may be spread across multiple directories at different locations
on sys.path (see PEP 420).
Djangoアプリケーションは(設定に応じて)、Djangoがテンプレートや静的アセットを探す単一のベースファイスシステムパスを必要とします。したがって、名前空間パッケージは以下のいずれかが真である場合にのみ、Django アプリケーションになることができます。
- 名前空間パッケージは実際には単一の場所にしか存在しません(つまり、複数のディレクトリに分散していないということです)。
- The
AppConfigclass used to configure the application has apathclass 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
ImproperlyConfigured.
アプリケーションレジストリ¶
-
apps¶ アプリケーションレジストリは、以下の公開APIを提供しています。以下に記載されていないメソッドは非公開とみなされ、予告なく変更される可能性があります。
-
apps.ready¶ Boolean attribute that is set to
Trueafter the registry is fully populated and allAppConfig.ready()methods are called.
-
apps.get_app_config(app_label)¶ Returns an
AppConfigfor the application with the givenapp_label. RaisesLookupErrorif no such application exists.
-
apps.is_installed(app_name)¶ Checks whether an application with the given name exists in the registry.
app_nameis the full name of the app, e.g.'django.contrib.admin'.
-
apps.get_model(app_label, model_name, require_ready=True)¶ Returns the
Modelwith the givenapp_labelandmodel_name. As a shortcut, this method also accepts a single argument in the formapp_label.model_name.model_nameis case-insensitive.Raises
LookupErrorif no such application or model exists. RaisesValueErrorwhen called with a single argument that doesn't contain exactly one dot.Requires the app registry to be fully populated unless the
require_readyargument is set toFalse.Setting
require_readytoFalseallows looking up models while the app registry is being populated, specifically during the second phase where it imports models. Thenget_model()has the same effect as importing the model. The main use case is to configure model classes with settings, such asAUTH_USER_MODEL.When
require_readyisFalse,get_model()returns a model class that may not be fully functional (reverse accessors may be missing, for example) until the app registry is fully populated. For this reason, it's best to leaverequire_readyto the default value ofTruewhenever possible.
Initialization process¶
How applications are loaded¶
When Django starts, django.setup() is responsible for populating the
application registry.
-
setup(set_prefix=True)[ソース]¶ Configures Django by:
- Loading the settings.
- Setting up logging.
- If
set_prefixis True, setting the URL resolver script prefix toFORCE_SCRIPT_NAMEif defined, or/otherwise. - Initializing the application registry.
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 INSTALLED_APPS.
First Django imports each item in
INSTALLED_APPS.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 looks for an application configuration in anapps.pysubmodule, or else creates a default application configuration."この時点では、どのモデルもインポートしてはいけません!"
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
get_app_config()become usable.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.pyormodels/__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
get_model()become usable.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.For example,
gettext()uses the app registry to look up translation catalogs in applications. To translate at import time, you needgettext_lazy()instead. (Usinggettext()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 ofadminmodules in installed applications. To prevent it, change yourINSTALLED_APPSto contain'django.contrib.admin.apps.SimpleAdminConfig'instead of'django.contrib.admin'.