Book Image

Django 3 Web Development Cookbook - Fourth Edition

By : Aidas Bendoraitis, Jake Kronika
Book Image

Django 3 Web Development Cookbook - Fourth Edition

By: Aidas Bendoraitis, Jake Kronika

Overview of this book

Django is a web framework for perfectionists with deadlines, designed to help you build manageable medium and large web projects in a short time span. This fourth edition of the Django Web Development Cookbook is updated with Django 3's latest features to guide you effectively through the development process. This Django book starts by helping you create a virtual environment and project structure for building Python web apps. You'll learn how to build models, views, forms, and templates for your web apps and then integrate JavaScript in your Django apps to add more features. As you advance, you'll create responsive multilingual websites, ready to be shared on social networks. The book will take you through uploading and processing images, rendering data in HTML5, PDF, and Excel, using and creating APIs, and navigating different data types in Django. You'll become well-versed in security best practices and caching techniques to enhance your website's security and speed. This edition not only helps you work with the PostgreSQL database but also the MySQL database. You'll also discover advanced recipes for using Django with Docker and Ansible in development, staging, and production environments. By the end of this book, you will have become proficient in using Django's powerful features and will be equipped to create robust websites.
Table of Contents (15 chapters)

Creating an app configuration

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.

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)$ startapp magazine

With your magazine app created, add a NewsArticle model to, create administration for the model in, 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

How to do it...

Follow these steps to create and use the app configuration:

  1. Modify the file and insert the following content into it, as follows:
# myproject/apps/magazine/
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
  1. Edit the file in the magazine module to contain the following content:
# myproject/apps/magazine/
default_app_config = "myproject.apps.magazine.apps.MagazineAppConfig"
  1. Let's create a file and add some signal handlers there:
# myproject/apps/magazine/
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 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/'>
>>> 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​.

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