---
title: "アプリケーション"
version: 2.0
locale: ja
source: https://docs.djangoproject.com/ja/2.0/ref/applications/
canonical: https://djangodocs.dev/ja/2.0/ref/applications/
---
# アプリケーション

Django には、設定の保存と調査の手段を提供するインストール済みアプリケーションのレジストリがあり、利用可能な [モデル](/ja/2.0/topics/db/models/) のリストもアクセスできます。

このレジストリは単に [`apps`](#django.apps.apps) と呼ばれ、次のようにして [`django.apps`](#module-django.apps) から使用できます。

```
>>> from django.apps import apps
>>> apps.get_app_config('admin').verbose_name
'Admin'
```

## プロジェクトとアプリケーション

**プロジェクト (project)** という単語は、Django の web アプリケーションを指します。プロジェクトの Python パッケージは主に settings モジュールで定義されますが、通常は他のファイルも含まれます。たとえば、 `django-admin startproject mysite` を実行すると、`mysite` プロジェクトディレクトリが作成され、その中には `settings.py`、`urls.py`、`wsgi.py` などのファイルが含まれる `mysite` Python パッケージが作られます。プロジェクトパッケージは、fixture や CSS、テンプレートなど特定のアプリケーションに束縛されないファイルも含まれることがふつうです。

**プロジェクトのルートディレクトリ** (`manage.py` があるディレクトリ) は、プロジェクトと一緒にインストールされるすべてのアプリケーションのコンテナとして機能します。

**アプリケーション (application)** という言葉は、何らかの機能を提供する Python パッケージを意味します。アプリケーションはさまざまなプロジェクトで [再利用する](/ja/2.0/intro/reusable-apps/) ことができます。

アプリケーションには、モデル、ビュー、テンプレート、テンプレートタグ、スタティックファイル、ミドルウェアなどが含まれます。これらは一般に [`INSTALLED_APPS`](/ja/2.0/ref/settings/#std-setting-INSTALLED_APPS) 設定で有効になり、それ以外では URLconfs、 [`MIDDLEWARE`](/ja/2.0/ref/settings/#std-setting-MIDDLEWARE) 設定、テンプレート継承などの仕組みから使われます。

Django のアプリケーションは、フレームワークのさまざまなパーツとやりとりをする単なるコードの集まりであると理解するのは大切です。`Application` オブジェクトのようなものは存在しません。しかしながら、Django がインストール済みのアプリケーションの主に設定やイントロスペクションとやりとりをする必要があることもあります。そのため、インストールアプリケーションごとのメタデータは、アプリケーションレジストリが [`AppConfig`](#django.apps.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`](/ja/2.0/ref/settings/#std-setting-INSTALLED_APPS)).

## アプリケーションを設定する

アプリケーションを設定するには、 [`AppConfig`](#django.apps.AppConfig) のサブクラスを作り、そのサブクラスへのドット区切りのパスを [`INSTALLED_APPS`](/ja/2.0/ref/settings/#std-setting-INSTALLED_APPS) に追加します。

[`INSTALLED_APPS`](/ja/2.0/ref/settings/#std-setting-INSTALLED_APPS) にアプリケーションモジュールを指すドット区切りのパスがある場合、Django はそのモジュールの `default_app_config` 変数をチェックします。

もしこの変数が定義されていれば、そのドット区切りのパスがアプリケーション [`AppConfig`](#django.apps.AppConfig) サブクラスになります。

もし `default_app_config` が定義されていなければ、Django は ベースとなる [`AppConfig`](#django.apps.AppConfig) クラスを使用します。

`default_app_config` allows applications that predate Django 1.7 such as
`django.contrib.admin` to opt-in to [`AppConfig`](#django.apps.AppConfig) features
without requiring users to update their [`INSTALLED_APPS`](/ja/2.0/ref/settings/#std-setting-INSTALLED_APPS).

New applications should avoid `default_app_config`. Instead they should
require the dotted path to the appropriate [`AppConfig`](#django.apps.AppConfig)
subclass to be configured explicitly in [`INSTALLED_APPS`](/ja/2.0/ref/settings/#std-setting-INSTALLED_APPS).

### For application authors

If you're creating a pluggable app called "Rock ’n’ roll", here's how you
would provide a proper name for the admin:

```
# rock_n_roll/apps.py

from django.apps import AppConfig

class RockNRollConfig(AppConfig):
    name = 'rock_n_roll'
    verbose_name = "Rock ’n’ roll"
```

You can make your application load this [`AppConfig`](#django.apps.AppConfig)
subclass by default as follows:

```
# rock_n_roll/__init__.py

default_app_config = 'rock_n_roll.apps.RockNRollConfig'
```

That will cause `RockNRollConfig` to be used when [`INSTALLED_APPS`](/ja/2.0/ref/settings/#std-setting-INSTALLED_APPS)
just contains `'rock_n_roll'`. This allows you to make use of
[`AppConfig`](#django.apps.AppConfig) features without requiring your users to
update their [`INSTALLED_APPS`](/ja/2.0/ref/settings/#std-setting-INSTALLED_APPS) setting. Besides this use case, it's
best to avoid using `default_app_config` and instead specify the app config
class in [`INSTALLED_APPS`](/ja/2.0/ref/settings/#std-setting-INSTALLED_APPS) as described next.

Of course, you can also tell your users to put
`'rock_n_roll.apps.RockNRollConfig'` in their [`INSTALLED_APPS`](/ja/2.0/ref/settings/#std-setting-INSTALLED_APPS)
setting. You can even provide several different
[`AppConfig`](#django.apps.AppConfig) subclasses with different behaviors and allow
your users to choose one via their [`INSTALLED_APPS`](/ja/2.0/ref/settings/#std-setting-INSTALLED_APPS) setting.

The recommended convention is to put the configuration class in a submodule of
the application called `apps`. However, this isn't enforced by Django.

You must include the [`name`](#django.apps.AppConfig.name) attribute for Django
to determine which application this configuration applies to. You can define
any attributes documented in the [`AppConfig`](#django.apps.AppConfig) API
reference.

> **Note**
>
> 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
> ```

### アプリケーションユーザー向け

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
configuration:

```
# 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

#### `class AppConfig`

Application configuration objects store metadata for an application. Some
attributes can be configured in [`AppConfig`](#django.apps.AppConfig)
subclasses. Others are set by Django and read-only.

### Configurable attributes

#### `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 [`AppConfig`](#django.apps.AppConfig) subclasses.

Djangoプロジェクト全体の中で固有である必要があります。

#### `AppConfig.label`

Short name for the application, e.g. `'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/python3.4/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
[`AppConfig`](#django.apps.AppConfig) subclass. In a few situations this is
required; for instance if the app package is a [namespace package](#namespace-package) with
multiple paths.

### 読み取り専用属性

#### `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 `None` if the application doesn't contain a `models` module.
Note that the database related signals such as
[`pre_migrate`](/ja/2.0/ref/signals/#django.db.models.signals.pre_migrate) and
[`post_migrate`](/ja/2.0/ref/signals/#django.db.models.signals.post_migrate)
are only emitted for applications that have a `models` module.

### メソッド

#### `AppConfig.get_models()`

Returns an iterable of [`Model`](/ja/2.0/ref/models/instances/#django.db.models.Model) classes for this
application.

Requires the app registry to be fully populated.

#### `AppConfig.get_model(model_name, require_ready=True)`

Returns the [`Model`](/ja/2.0/ref/models/instances/#django.db.models.Model) with the given
`model_name`. `model_name` is case-insensitive.

Raises [`LookupError`](https://docs.python.org/3/library/exceptions.html#LookupError) if no such model exists in this application.

Requires the app registry to be fully populated unless the
`require_ready` argument is set to `False`. `require_ready` behaves
exactly as in [`apps.get_model()`](#django.apps.apps.get_model).

> **New in Django 1.11**
>
> キーワード引数 `require_ready` が追加されました。

#### `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
[`AppConfig`](#django.apps.AppConfig) classes are defined, you can import them in
`ready()`, using either an `import` statement or
[`get_model()`](#django.apps.AppConfig.get_model).

If you're registering [`model signals`](/ja/2.0/ref/signals/#module-django.db.models.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')
```

> **Warning**
>
> Although you can access model classes as described above, avoid
> interacting with the database in your [`ready()`](#django.apps.AppConfig.ready) implementation.
> This includes model methods that execute queries
> ([`save()`](/ja/2.0/ref/models/instances/#django.db.models.Model.save),
> [`delete()`](/ja/2.0/ref/models/instances/#django.db.models.Model.delete), manager methods etc.), and
> also raw SQL queries via `django.db.connection`. Your
> [`ready()`](#django.apps.AppConfig.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 test` would still
> execute some queries against your **production** database!

> **Note**
>
> In the usual initialization process, the `ready` method is only called
> once by Django. But in some corner cases, particularly in tests which
> are fiddling with installed applications, `ready` might be called more
> than once. In that case, either write idempotent methods, or put a flag
> on your `AppConfig` classes 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**](https://peps.python.org/pep-0420/)).

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:

1. The namespace package actually has only a single location (i.e. is not
   spread across more than one directory.)
2. The [`AppConfig`](#django.apps.AppConfig) class used to configure the application
   has a [`path`](#django.apps.AppConfig.path) class 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`](/ja/2.0/ref/exceptions/#django.core.exceptions.ImproperlyConfigured).

## Application registry

#### `apps`

The application registry provides the following public API. Methods that
aren't listed below are considered private and may change without notice.

#### `apps.ready`

Boolean attribute that is set to `True` after the registry is fully
populated and all [`AppConfig.ready()`](#django.apps.AppConfig.ready) methods are called.

#### `apps.get_app_configs()`

Returns an iterable of [`AppConfig`](#django.apps.AppConfig) instances.

#### `apps.get_app_config(app_label)`

Returns an [`AppConfig`](#django.apps.AppConfig) for the application with the
given `app_label`. Raises [`LookupError`](https://docs.python.org/3/library/exceptions.html#LookupError) if no such application
exists.

#### `apps.is_installed(app_name)`

Checks whether an application with the given name exists in the registry.
`app_name` is the full name of the app, e.g. `'django.contrib.admin'`.

#### `apps.get_model(app_label, model_name, require_ready=True)`

Returns the [`Model`](/ja/2.0/ref/models/instances/#django.db.models.Model) with the given `app_label`
and `model_name`. As a shortcut, this method also accepts a single
argument in the form `app_label.model_name`. `model_name` is
case-insensitive.

Raises [`LookupError`](https://docs.python.org/3/library/exceptions.html#LookupError) if no such application or model exists. Raises
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) when called with a single argument that doesn't contain
exactly one dot.

Requires the app registry to be fully populated unless the
`require_ready` argument is set to `False`.

Setting `require_ready` to `False` allows looking up models
[while the app registry is being populated](#app-loading-process),
specifically during the second phase where it imports models. Then
`get_model()` has the same effect as importing the model. The main use
case is to configure model classes with settings, such as
[`AUTH_USER_MODEL`](/ja/2.0/ref/settings/#std-setting-AUTH_USER_MODEL).

When `require_ready` is `False`, `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 leave `require_ready` to the default value of `True` whenever
possible.

> **New in Django 1.11**
>
> キーワード引数 `require_ready` が追加されました。

## Initialization process

### How applications are loaded

When Django starts, [`django.setup()`](#django.setup) is responsible for populating the
application registry.

#### `setup(set_prefix=True)`

Configures Django by:

- Loading the settings.
- Setting up logging.
- If `set_prefix` is True, setting the URL resolver script prefix to
  [`FORCE_SCRIPT_NAME`](/ja/2.0/ref/settings/#std-setting-FORCE_SCRIPT_NAME) if 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`](/ja/2.0/ref/settings/#std-setting-INSTALLED_APPS).

1. First Django imports each item in [`INSTALLED_APPS`](/ja/2.0/ref/settings/#std-setting-INSTALLED_APPS).

   If it's an application configuration class, Django imports the root package
   of the application, defined by its [`name`](#django.apps.AppConfig.name) attribute. 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`](/ja/2.0/ref/settings/#std-setting-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()`](#django.apps.apps.get_app_config) become usable.
2. Then Django attempts to import the `models` submodule of each application,
   if there is one.

   You must define or import all models in your application's `models.py` or
   `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
   [`get_model()`](#django.apps.apps.get_model) become usable.
3. Finally Django runs the [`ready()`](#django.apps.AppConfig.ready) method of each application
   configuration.

### トラブルシューティング

Here are some common problems that you may encounter during initialization:

- [`AppRegistryNotReady`](/ja/2.0/ref/exceptions/#django.core.exceptions.AppRegistryNotReady): This happens when
  importing an application configuration or a models module triggers code that
  depends on the app registry.

  For example, [`gettext()`](/ja/2.0/ref/utils/#django.utils.translation.gettext) uses the app
  registry to look up translation catalogs in applications. To translate at
  import time, you need [`gettext_lazy()`](/ja/2.0/ref/utils/#django.utils.translation.gettext_lazy)
  instead. (Using [`gettext()`](/ja/2.0/ref/utils/#django.utils.translation.gettext) 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()`](#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.admin` automatically performs autodiscovery of `admin`
  modules in installed applications. To prevent it, change your
  [`INSTALLED_APPS`](/ja/2.0/ref/settings/#std-setting-INSTALLED_APPS) to contain
  `'django.contrib.admin.apps.SimpleAdminConfig'` instead of
  `'django.contrib.admin'`.
