Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Django 2 Web Development Cookbook

You're reading from   Django 2 Web Development Cookbook 100 practical recipes on building scalable Python web apps with Django 2

Arrow left icon
Product type Paperback
Published in Oct 2018
Publisher
ISBN-13 9781788837682
Length 544 pages
Edition 3rd Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Aidas Bendoraitis Aidas Bendoraitis
Author Profile Icon Aidas Bendoraitis
Aidas Bendoraitis
Jake Kronika Jake Kronika
Author Profile Icon Jake Kronika
Jake Kronika
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. Getting Started with Django 2.1 2. Database Structure and Modeling FREE CHAPTER 3. Forms and Views 4. Templates and JavaScript 5. Customizing Template Filters and Tags 6. Model Administration 7. Security and Performance 8. Django CMS 9. Hierarchical Structures 10. Importing and Exporting Data 11. Bells and Whistles 12. Testing and Deployment 13. Other Books You May Enjoy

Creating app configuration

When developing a website with Django, you create one module for the project itself, and then multiple Python modules called applications (or, more commonly, apps) that combine the different modular functionalities and usually consist of models, views, forms, URL configurations, management commands, migrations, signals, tests, and so on. The Django framework has application registry, where all apps and models are collected and later used for configuration and introspection. Since Django 1.7, meta information about apps can be saved in the AppConfig instance for each used 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 in one of three ways:

  • Generate all of the files manually, which can be an excellent tool for learning, but is far from the most efficient approach.
  • Use the startapp command in your virtual environment, as follows:
(myproject_env)$ django-admin.py startapp magazine

Learn how to use virtual environments in the Working with a virtual environment and Creating a virtual environment project file structure recipes.

  • Use the startapp command in a Docker project, as follows:
myproject_django/$ docker-compose run app django-admin.py startapp magazine
Learn how to use Docker in the Working with Docker and Creating a Docker project file structure recipes.

With your magazine app created, add a NewsArticle model to models.py, create administration for the model in admin.py, and put "magazine" in INSTALLED_APPS in the settings.py. If you are not yet familiar with these tasks, study the official Django tutorial at:
https://docs.djangoproject.com/en/2.1/intro/tutorial01/.

How to do it...

Follow these steps to create and use the app configuration:

  1. Create the apps.py file and put the following content in it, as follows:
# magazine/apps.py
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _


class MagazineAppConfig(AppConfig):
name = "magazine"
verbose_name = _("Magazine")

def ready(self):
from . import signals
  1. Edit the __init__.py file in the magazine module to contain the following content:
# magazine/__init__.py
default_app_config = "magazine.apps.MagazineAppConfig"
  1. Let's create a signals.py file and add some signal handlers there:
# 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, as follows:

  • Django imports the configurations for each item from INSTALLED_APPS in the settings. These items can point to app names or configuration directly, for example, "magazine" or "magazine.apps.NewsAppConfig".
  • Django 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 is a correct place 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 name of the current app. The verbose_name parameter 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 is 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 '/usr/src/app/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.1/ref/applications/.

See also

  • The Working with a virtual environment recipe
  • The Working with Docker recipe
  • The Defining overwritable app settings recipe
  • Chapter 6, Model Administration
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime