Django projects consist of multiple Python modules called applications (or, more commonly, apps) that combine different modular functionalities. Each app can have models, views, forms, URL configurations, management commands, migrations, signals, tests, context processors, middlewares, and so on. The Django framework has an application registry, where all apps and models are collected and later used for configuration and introspection. Since Django 1.7, metainformation about apps can be saved in the AppConfig instance for each app. Let's create a sample magazine app to take a look at how to use the app configuration there.
Creating an app configuration
Getting ready
You can create a Django app either by calling the startapp management command or by creating the app module manually:
(env)$ cd myproject/apps/
(env)$ django-admin.py startapp magazine
With your magazine app created, add a NewsArticle model to models.py, create administration for the model in admin.py, and put "myproject.apps.magazine" in INSTALLED_APPS in the settings. If you are not yet familiar with these tasks, study the official Django tutorial at https://docs.djangoproject.com/en/3.0/intro/tutorial01/.
How to do it...
Follow these steps to create and use the app configuration:
- Modify the apps.py file and insert the following content into it, as follows:
# myproject/apps/magazine/apps.py
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class MagazineAppConfig(AppConfig):
name = "myproject.apps.magazine"
verbose_name = _("Magazine")
def ready(self):
from . import signals
- Edit the __init__.py file in the magazine module to contain the following content:
# myproject/apps/magazine/__init__.py
default_app_config = "myproject.apps.magazine.apps.MagazineAppConfig"
- Let's create a signals.py file and add some signal handlers there:
# myproject/apps/magazine/signals.py
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.conf import settings
from .models import NewsArticle
@receiver(post_save, sender=NewsArticle)
def news_save_handler(sender, **kwargs):
if settings.DEBUG:
print(f"{kwargs['instance']} saved.")
@receiver(post_delete, sender=NewsArticle)
def news_delete_handler(sender, **kwargs):
if settings.DEBUG:
print(f"{kwargs['instance']} deleted.")
How it works...
When you run an HTTP server or invoke a management command, django.setup() is called. It loads the settings, sets up logging, and prepares the app registry. This registry is initialized in three steps. Django first imports the configurations for each item from INSTALLED_APPS in the settings. These items can point to app names or configurations directly—for example, "myproject.apps.magazine" or "myproject.apps.magazine.apps.MagazineAppConfig".
Django then tries to import models.py from each app in INSTALLED_APPS and collect all of the models.
Finally, Django runs the ready() method for each app configuration. This method presents a good point in the development process to register signal handlers, if you have any. The ready() method is optional.
In our example, the MagazineAppConfig class sets the configuration for the magazine app. The name parameter defines the module of the current app. The verbose_name parameter defines a human name that is used in the Django model administration, where models are presented and grouped by apps. The ready() method imports and activates the signal handlers that, when in DEBUG mode, print in the terminal that a NewsArticle object was saved or deleted.
There's more...
After calling django.setup(), you can load the app configurations and models from the registry as follows:
>>> from django.apps import apps as django_apps
>>> magazine_app_config = django_apps.get_app_config("magazine")
>>> magazine_app_config
<MagazineAppConfig: magazine>
>>> magazine_app_config.models_module
<module 'magazine.models' from '/path/to/myproject/apps/magazine/models.py'>
>>> NewsArticle = django_apps.get_model("magazine", "NewsArticle")
>>> NewsArticle
<class 'magazine.models.NewsArticle'>
You can read more about app configuration in the official Django documentation at
https://docs.djangoproject.com/en/2.2/ref/applications/.
See also
- The Working with a virtual environment recipe
- The Working with Docker containers for Django, Gunicorn, Nginx, and PostgreSQL recipe
- The Defining overwritable app settings recipe
- Chapter 6, Model Administration