Book Image

Web Development with Django Cookbook- Second Edition - Second Edition

By : Aidas Bendoraitis
Book Image

Web Development with Django Cookbook- Second Edition - Second Edition

By: Aidas Bendoraitis

Overview of this book

Django is a web framework that was designed to strike a balance between rapid web development and high performance. It has the capacity to handle applications with high levels of user traffic and interaction, and can integrate with massive databases on the backend, constantly collecting and processing data in real time. Through this book, you'll discover that collecting data from different sources and providing it to others in different formats isn't as difficult as you thought. It follows a task-based approach to guide you through all the web development processes using the Django framework. We’ll start by setting up the virtual environment for a Django project and configuring it. Then you’ll learn to write reusable pieces of code for your models and find out how to manage database schema changes using South migrations. After that, we’ll take you through working with forms and views to enter and list data. With practical examples on using templates and JavaScript together, you will discover how to create the best user experience. In the final chapters, you'll be introduced to some programming and debugging tricks and finally, you will be shown how to test and deploy the project to a remote dedicated server. By the end of this book, you will have a good understanding of the new features added to Django 1.8 and be an expert at web development processes.
Table of Contents (18 chapters)
Web Development with Django Cookbook Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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

Either create your Django app manually or using this command in your virtual environment (learn how to use virtual environments in the Working with a virtual environment recipe), as follows:

(myproject_env)$ django-admin.py startapp magazine

Add some NewsArticle model to models.py, create administration for the model in admin.py, and put "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/1.8/intro/tutorial01/.

How to do it…

Follow these steps to create and use the app configuration:

  1. First of all, create the apps.py file and put this content in it, as follows:

    # magazine/apps.py
    # -*- coding: UTF-8 -*-
    from __future__ import unicode_literals
    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
  2. Then, edit the __init__.py file of the app and put the following content:

    # magazine/__init__.py
    # -*- coding: UTF-8 -*-
    from __future__ import unicode_literals
    default_app_config = "magazine.apps.MagazineAppConfig"
  3. Lastly, let's create a signals.py file and add some signal handlers there:

    # magazine/signals.py
    # -*- coding: UTF-8 -*-
    from __future__ import unicode_literals
    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("%s saved." % kwargs['instance'])
    
    @receiver(post_delete, sender=NewsArticle)
    def news_delete_handler(sender, **kwargs):
        if settings.DEBUG:
            print("%s deleted." % kwargs['instance'])

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 initializes app registry. The app registry is initialized in three steps, as shown in the following:

  • 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 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 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 'magazine/models.pyc'>
NewsArticle = django_apps.get_model("magazine", "NewsArticle")

You can read more about app configuration in the official Django documentation at https://docs.djangoproject.com/en/1.8/ref/applications/

See also

  • The Working with a virtual environment recipe

  • The Defining overwritable app settings recipe

  • Chapter 6, Model Administration